clusterinfo_dump.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package clusterinfo
  14. import (
  15. "fmt"
  16. "io"
  17. "os"
  18. "path"
  19. "time"
  20. "github.com/spf13/cobra"
  21. corev1 "k8s.io/api/core/v1"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/cli-runtime/pkg/genericclioptions"
  24. "k8s.io/cli-runtime/pkg/printers"
  25. appsv1client "k8s.io/client-go/kubernetes/typed/apps/v1"
  26. corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
  27. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  28. "k8s.io/kubernetes/pkg/kubectl/polymorphichelpers"
  29. "k8s.io/kubernetes/pkg/kubectl/scheme"
  30. "k8s.io/kubernetes/pkg/kubectl/util/i18n"
  31. "k8s.io/kubernetes/pkg/kubectl/util/templates"
  32. )
  33. const (
  34. defaultPodLogsTimeout = 20 * time.Second
  35. timeout = 5 * time.Minute
  36. )
  37. type ClusterInfoDumpOptions struct {
  38. PrintFlags *genericclioptions.PrintFlags
  39. PrintObj printers.ResourcePrinterFunc
  40. OutputDir string
  41. AllNamespaces bool
  42. Namespaces []string
  43. Timeout time.Duration
  44. AppsClient appsv1client.AppsV1Interface
  45. CoreClient corev1client.CoreV1Interface
  46. Namespace string
  47. RESTClientGetter genericclioptions.RESTClientGetter
  48. LogsForObject polymorphichelpers.LogsForObjectFunc
  49. genericclioptions.IOStreams
  50. }
  51. func NewCmdClusterInfoDump(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
  52. o := &ClusterInfoDumpOptions{
  53. PrintFlags: genericclioptions.NewPrintFlags("").WithTypeSetter(scheme.Scheme).WithDefaultOutput("json"),
  54. IOStreams: ioStreams,
  55. }
  56. cmd := &cobra.Command{
  57. Use: "dump",
  58. Short: i18n.T("Dump lots of relevant info for debugging and diagnosis"),
  59. Long: dumpLong,
  60. Example: dumpExample,
  61. Run: func(cmd *cobra.Command, args []string) {
  62. cmdutil.CheckErr(o.Complete(f, cmd))
  63. cmdutil.CheckErr(o.Run())
  64. },
  65. }
  66. o.PrintFlags.AddFlags(cmd)
  67. cmd.Flags().StringVar(&o.OutputDir, "output-directory", o.OutputDir, i18n.T("Where to output the files. If empty or '-' uses stdout, otherwise creates a directory hierarchy in that directory"))
  68. cmd.Flags().StringSliceVar(&o.Namespaces, "namespaces", o.Namespaces, "A comma separated list of namespaces to dump.")
  69. cmd.Flags().BoolVarP(&o.AllNamespaces, "all-namespaces", "A", o.AllNamespaces, "If true, dump all namespaces. If true, --namespaces is ignored.")
  70. cmdutil.AddPodRunningTimeoutFlag(cmd, defaultPodLogsTimeout)
  71. return cmd
  72. }
  73. var (
  74. dumpLong = templates.LongDesc(i18n.T(`
  75. Dumps cluster info out suitable for debugging and diagnosing cluster problems. By default, dumps everything to
  76. stdout. You can optionally specify a directory with --output-directory. If you specify a directory, kubernetes will
  77. build a set of files in that directory. By default only dumps things in the 'kube-system' namespace, but you can
  78. switch to a different namespace with the --namespaces flag, or specify --all-namespaces to dump all namespaces.
  79. The command also dumps the logs of all of the pods in the cluster, these logs are dumped into different directories
  80. based on namespace and pod name.`))
  81. dumpExample = templates.Examples(i18n.T(`
  82. # Dump current cluster state to stdout
  83. kubectl cluster-info dump
  84. # Dump current cluster state to /path/to/cluster-state
  85. kubectl cluster-info dump --output-directory=/path/to/cluster-state
  86. # Dump all namespaces to stdout
  87. kubectl cluster-info dump --all-namespaces
  88. # Dump a set of namespaces to /path/to/cluster-state
  89. kubectl cluster-info dump --namespaces default,kube-system --output-directory=/path/to/cluster-state`))
  90. )
  91. func setupOutputWriter(dir string, defaultWriter io.Writer, filename string) io.Writer {
  92. if len(dir) == 0 || dir == "-" {
  93. return defaultWriter
  94. }
  95. fullFile := path.Join(dir, filename)
  96. parent := path.Dir(fullFile)
  97. cmdutil.CheckErr(os.MkdirAll(parent, 0755))
  98. file, err := os.Create(path.Join(dir, filename))
  99. cmdutil.CheckErr(err)
  100. return file
  101. }
  102. func (o *ClusterInfoDumpOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error {
  103. printer, err := o.PrintFlags.ToPrinter()
  104. if err != nil {
  105. return err
  106. }
  107. o.PrintObj = printer.PrintObj
  108. config, err := f.ToRESTConfig()
  109. if err != nil {
  110. return err
  111. }
  112. o.CoreClient, err = corev1client.NewForConfig(config)
  113. if err != nil {
  114. return err
  115. }
  116. o.AppsClient, err = appsv1client.NewForConfig(config)
  117. if err != nil {
  118. return err
  119. }
  120. o.Timeout, err = cmdutil.GetPodRunningTimeoutFlag(cmd)
  121. if err != nil {
  122. return err
  123. }
  124. o.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()
  125. if err != nil {
  126. return err
  127. }
  128. // TODO this should eventually just be the completed kubeconfigflag struct
  129. o.RESTClientGetter = f
  130. o.LogsForObject = polymorphichelpers.LogsForObjectFn
  131. return nil
  132. }
  133. func (o *ClusterInfoDumpOptions) Run() error {
  134. nodes, err := o.CoreClient.Nodes().List(metav1.ListOptions{})
  135. if err != nil {
  136. return err
  137. }
  138. if err := o.PrintObj(nodes, setupOutputWriter(o.OutputDir, o.Out, "nodes.json")); err != nil {
  139. return err
  140. }
  141. var namespaces []string
  142. if o.AllNamespaces {
  143. namespaceList, err := o.CoreClient.Namespaces().List(metav1.ListOptions{})
  144. if err != nil {
  145. return err
  146. }
  147. for ix := range namespaceList.Items {
  148. namespaces = append(namespaces, namespaceList.Items[ix].Name)
  149. }
  150. } else {
  151. if len(o.Namespaces) == 0 {
  152. namespaces = []string{
  153. metav1.NamespaceSystem,
  154. o.Namespace,
  155. }
  156. }
  157. }
  158. for _, namespace := range namespaces {
  159. // TODO: this is repetitive in the extreme. Use reflection or
  160. // something to make this a for loop.
  161. events, err := o.CoreClient.Events(namespace).List(metav1.ListOptions{})
  162. if err != nil {
  163. return err
  164. }
  165. if err := o.PrintObj(events, setupOutputWriter(o.OutputDir, o.Out, path.Join(namespace, "events.json"))); err != nil {
  166. return err
  167. }
  168. rcs, err := o.CoreClient.ReplicationControllers(namespace).List(metav1.ListOptions{})
  169. if err != nil {
  170. return err
  171. }
  172. if err := o.PrintObj(rcs, setupOutputWriter(o.OutputDir, o.Out, path.Join(namespace, "replication-controllers.json"))); err != nil {
  173. return err
  174. }
  175. svcs, err := o.CoreClient.Services(namespace).List(metav1.ListOptions{})
  176. if err != nil {
  177. return err
  178. }
  179. if err := o.PrintObj(svcs, setupOutputWriter(o.OutputDir, o.Out, path.Join(namespace, "services.json"))); err != nil {
  180. return err
  181. }
  182. sets, err := o.AppsClient.DaemonSets(namespace).List(metav1.ListOptions{})
  183. if err != nil {
  184. return err
  185. }
  186. if err := o.PrintObj(sets, setupOutputWriter(o.OutputDir, o.Out, path.Join(namespace, "daemonsets.json"))); err != nil {
  187. return err
  188. }
  189. deps, err := o.AppsClient.Deployments(namespace).List(metav1.ListOptions{})
  190. if err != nil {
  191. return err
  192. }
  193. if err := o.PrintObj(deps, setupOutputWriter(o.OutputDir, o.Out, path.Join(namespace, "deployments.json"))); err != nil {
  194. return err
  195. }
  196. rps, err := o.AppsClient.ReplicaSets(namespace).List(metav1.ListOptions{})
  197. if err != nil {
  198. return err
  199. }
  200. if err := o.PrintObj(rps, setupOutputWriter(o.OutputDir, o.Out, path.Join(namespace, "replicasets.json"))); err != nil {
  201. return err
  202. }
  203. pods, err := o.CoreClient.Pods(namespace).List(metav1.ListOptions{})
  204. if err != nil {
  205. return err
  206. }
  207. if err := o.PrintObj(pods, setupOutputWriter(o.OutputDir, o.Out, path.Join(namespace, "pods.json"))); err != nil {
  208. return err
  209. }
  210. printContainer := func(writer io.Writer, container corev1.Container, pod *corev1.Pod) {
  211. writer.Write([]byte(fmt.Sprintf("==== START logs for container %s of pod %s/%s ====\n", container.Name, pod.Namespace, pod.Name)))
  212. defer writer.Write([]byte(fmt.Sprintf("==== END logs for container %s of pod %s/%s ====\n", container.Name, pod.Namespace, pod.Name)))
  213. requests, err := o.LogsForObject(o.RESTClientGetter, pod, &corev1.PodLogOptions{Container: container.Name}, timeout, false)
  214. if err != nil {
  215. // Print error and return.
  216. writer.Write([]byte(fmt.Sprintf("Create log request error: %s\n", err.Error())))
  217. return
  218. }
  219. for _, request := range requests {
  220. data, err := request.DoRaw()
  221. if err != nil {
  222. // Print error and return.
  223. writer.Write([]byte(fmt.Sprintf("Request log error: %s\n", err.Error())))
  224. return
  225. }
  226. writer.Write(data)
  227. }
  228. }
  229. for ix := range pods.Items {
  230. pod := &pods.Items[ix]
  231. containers := pod.Spec.Containers
  232. writer := setupOutputWriter(o.OutputDir, o.Out, path.Join(namespace, pod.Name, "logs.txt"))
  233. for i := range containers {
  234. printContainer(writer, containers[i], pod)
  235. }
  236. }
  237. }
  238. dest := o.OutputDir
  239. if len(dest) == 0 {
  240. dest = "standard output"
  241. }
  242. if dest != "-" {
  243. fmt.Fprintf(o.Out, "Cluster info dumped to %s\n", dest)
  244. }
  245. return nil
  246. }