logs.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. /*
  2. Copyright 2014 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 logs
  14. import (
  15. "bufio"
  16. "errors"
  17. "fmt"
  18. "io"
  19. "os"
  20. "sync"
  21. "time"
  22. "github.com/spf13/cobra"
  23. corev1 "k8s.io/api/core/v1"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. "k8s.io/apimachinery/pkg/runtime"
  26. "k8s.io/cli-runtime/pkg/genericclioptions"
  27. "k8s.io/client-go/rest"
  28. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  29. "k8s.io/kubernetes/pkg/kubectl/polymorphichelpers"
  30. "k8s.io/kubernetes/pkg/kubectl/scheme"
  31. "k8s.io/kubernetes/pkg/kubectl/util"
  32. "k8s.io/kubernetes/pkg/kubectl/util/i18n"
  33. "k8s.io/kubernetes/pkg/kubectl/util/templates"
  34. )
  35. const (
  36. logsUsageStr = "logs [-f] [-p] (POD | TYPE/NAME) [-c CONTAINER]"
  37. )
  38. var (
  39. logsExample = templates.Examples(i18n.T(`
  40. # Return snapshot logs from pod nginx with only one container
  41. kubectl logs nginx
  42. # Return snapshot logs from pod nginx with multi containers
  43. kubectl logs nginx --all-containers=true
  44. # Return snapshot logs from all containers in pods defined by label app=nginx
  45. kubectl logs -lapp=nginx --all-containers=true
  46. # Return snapshot of previous terminated ruby container logs from pod web-1
  47. kubectl logs -p -c ruby web-1
  48. # Begin streaming the logs of the ruby container in pod web-1
  49. kubectl logs -f -c ruby web-1
  50. # Begin streaming the logs from all containers in pods defined by label app=nginx
  51. kubectl logs -f -lapp=nginx --all-containers=true
  52. # Display only the most recent 20 lines of output in pod nginx
  53. kubectl logs --tail=20 nginx
  54. # Show all logs from pod nginx written in the last hour
  55. kubectl logs --since=1h nginx
  56. # Return snapshot logs from first container of a job named hello
  57. kubectl logs job/hello
  58. # Return snapshot logs from container nginx-1 of a deployment named nginx
  59. kubectl logs deployment/nginx -c nginx-1`))
  60. selectorTail int64 = 10
  61. logsUsageErrStr = fmt.Sprintf("expected '%s'.\nPOD or TYPE/NAME is a required argument for the logs command", logsUsageStr)
  62. )
  63. const (
  64. defaultPodLogsTimeout = 20 * time.Second
  65. )
  66. type LogsOptions struct {
  67. Namespace string
  68. ResourceArg string
  69. AllContainers bool
  70. Options runtime.Object
  71. Resources []string
  72. ConsumeRequestFn func(rest.ResponseWrapper, io.Writer) error
  73. // PodLogOptions
  74. SinceTime string
  75. SinceSeconds time.Duration
  76. Follow bool
  77. Previous bool
  78. Timestamps bool
  79. IgnoreLogErrors bool
  80. LimitBytes int64
  81. Tail int64
  82. Container string
  83. // whether or not a container name was given via --container
  84. ContainerNameSpecified bool
  85. Selector string
  86. MaxFollowConcurency int
  87. Object runtime.Object
  88. GetPodTimeout time.Duration
  89. RESTClientGetter genericclioptions.RESTClientGetter
  90. LogsForObject polymorphichelpers.LogsForObjectFunc
  91. genericclioptions.IOStreams
  92. }
  93. func NewLogsOptions(streams genericclioptions.IOStreams, allContainers bool) *LogsOptions {
  94. return &LogsOptions{
  95. IOStreams: streams,
  96. AllContainers: allContainers,
  97. Tail: -1,
  98. MaxFollowConcurency: 5,
  99. }
  100. }
  101. // NewCmdLogs creates a new pod logs command
  102. func NewCmdLogs(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
  103. o := NewLogsOptions(streams, false)
  104. cmd := &cobra.Command{
  105. Use: logsUsageStr,
  106. DisableFlagsInUseLine: true,
  107. Short: i18n.T("Print the logs for a container in a pod"),
  108. Long: "Print the logs for a container in a pod or specified resource. If the pod has only one container, the container name is optional.",
  109. Example: logsExample,
  110. PreRun: func(cmd *cobra.Command, args []string) {
  111. if len(os.Args) > 1 && os.Args[1] == "log" {
  112. fmt.Fprintf(o.ErrOut, "%s is DEPRECATED and will be removed in a future version. Use %s instead.\n", "log", "logs")
  113. }
  114. },
  115. Run: func(cmd *cobra.Command, args []string) {
  116. cmdutil.CheckErr(o.Complete(f, cmd, args))
  117. cmdutil.CheckErr(o.Validate())
  118. cmdutil.CheckErr(o.RunLogs())
  119. },
  120. Aliases: []string{"log"},
  121. }
  122. cmd.Flags().BoolVar(&o.AllContainers, "all-containers", o.AllContainers, "Get all containers' logs in the pod(s).")
  123. cmd.Flags().BoolVarP(&o.Follow, "follow", "f", o.Follow, "Specify if the logs should be streamed.")
  124. cmd.Flags().BoolVar(&o.Timestamps, "timestamps", o.Timestamps, "Include timestamps on each line in the log output")
  125. cmd.Flags().Int64Var(&o.LimitBytes, "limit-bytes", o.LimitBytes, "Maximum bytes of logs to return. Defaults to no limit.")
  126. cmd.Flags().BoolVarP(&o.Previous, "previous", "p", o.Previous, "If true, print the logs for the previous instance of the container in a pod if it exists.")
  127. cmd.Flags().Int64Var(&o.Tail, "tail", o.Tail, "Lines of recent log file to display. Defaults to -1 with no selector, showing all log lines otherwise 10, if a selector is provided.")
  128. cmd.Flags().BoolVar(&o.IgnoreLogErrors, "ignore-errors", o.IgnoreLogErrors, "If watching / following pod logs, allow for any errors that occur to be non-fatal")
  129. cmd.Flags().StringVar(&o.SinceTime, "since-time", o.SinceTime, i18n.T("Only return logs after a specific date (RFC3339). Defaults to all logs. Only one of since-time / since may be used."))
  130. cmd.Flags().DurationVar(&o.SinceSeconds, "since", o.SinceSeconds, "Only return logs newer than a relative duration like 5s, 2m, or 3h. Defaults to all logs. Only one of since-time / since may be used.")
  131. cmd.Flags().StringVarP(&o.Container, "container", "c", o.Container, "Print the logs of this container")
  132. cmdutil.AddPodRunningTimeoutFlag(cmd, defaultPodLogsTimeout)
  133. cmd.Flags().StringVarP(&o.Selector, "selector", "l", o.Selector, "Selector (label query) to filter on.")
  134. cmd.Flags().IntVar(&o.MaxFollowConcurency, "max-log-requests", o.MaxFollowConcurency, "Specify maximum number of concurrent logs to follow when using by a selector. Defaults to 5.")
  135. return cmd
  136. }
  137. func (o *LogsOptions) ToLogOptions() (*corev1.PodLogOptions, error) {
  138. logOptions := &corev1.PodLogOptions{
  139. Container: o.Container,
  140. Follow: o.Follow,
  141. Previous: o.Previous,
  142. Timestamps: o.Timestamps,
  143. }
  144. if len(o.SinceTime) > 0 {
  145. t, err := util.ParseRFC3339(o.SinceTime, metav1.Now)
  146. if err != nil {
  147. return nil, err
  148. }
  149. logOptions.SinceTime = &t
  150. }
  151. if o.LimitBytes != 0 {
  152. logOptions.LimitBytes = &o.LimitBytes
  153. }
  154. if o.SinceSeconds != 0 {
  155. // round up to the nearest second
  156. sec := int64(o.SinceSeconds.Round(time.Second).Seconds())
  157. logOptions.SinceSeconds = &sec
  158. }
  159. if len(o.Selector) > 0 && o.Tail == -1 {
  160. logOptions.TailLines = &selectorTail
  161. } else if o.Tail != -1 {
  162. logOptions.TailLines = &o.Tail
  163. }
  164. return logOptions, nil
  165. }
  166. func (o *LogsOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
  167. o.ContainerNameSpecified = cmd.Flag("container").Changed
  168. o.Resources = args
  169. switch len(args) {
  170. case 0:
  171. if len(o.Selector) == 0 {
  172. return cmdutil.UsageErrorf(cmd, "%s", logsUsageErrStr)
  173. }
  174. case 1:
  175. o.ResourceArg = args[0]
  176. if len(o.Selector) != 0 {
  177. return cmdutil.UsageErrorf(cmd, "only a selector (-l) or a POD name is allowed")
  178. }
  179. case 2:
  180. o.ResourceArg = args[0]
  181. o.Container = args[1]
  182. default:
  183. return cmdutil.UsageErrorf(cmd, "%s", logsUsageErrStr)
  184. }
  185. var err error
  186. o.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()
  187. if err != nil {
  188. return err
  189. }
  190. o.ConsumeRequestFn = DefaultConsumeRequest
  191. o.GetPodTimeout, err = cmdutil.GetPodRunningTimeoutFlag(cmd)
  192. if err != nil {
  193. return err
  194. }
  195. o.Options, err = o.ToLogOptions()
  196. if err != nil {
  197. return err
  198. }
  199. o.RESTClientGetter = f
  200. o.LogsForObject = polymorphichelpers.LogsForObjectFn
  201. if o.Object == nil {
  202. builder := f.NewBuilder().
  203. WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
  204. NamespaceParam(o.Namespace).DefaultNamespace().
  205. SingleResourceType()
  206. if o.ResourceArg != "" {
  207. builder.ResourceNames("pods", o.ResourceArg)
  208. }
  209. if o.Selector != "" {
  210. builder.ResourceTypes("pods").LabelSelectorParam(o.Selector)
  211. }
  212. infos, err := builder.Do().Infos()
  213. if err != nil {
  214. return err
  215. }
  216. if o.Selector == "" && len(infos) != 1 {
  217. return errors.New("expected a resource")
  218. }
  219. o.Object = infos[0].Object
  220. }
  221. return nil
  222. }
  223. func (o LogsOptions) Validate() error {
  224. if len(o.SinceTime) > 0 && o.SinceSeconds != 0 {
  225. return fmt.Errorf("at most one of `sinceTime` or `sinceSeconds` may be specified")
  226. }
  227. logsOptions, ok := o.Options.(*corev1.PodLogOptions)
  228. if !ok {
  229. return errors.New("unexpected logs options object")
  230. }
  231. if o.AllContainers && len(logsOptions.Container) > 0 {
  232. return fmt.Errorf("--all-containers=true should not be specified with container name %s", logsOptions.Container)
  233. }
  234. if o.ContainerNameSpecified && len(o.Resources) == 2 {
  235. return fmt.Errorf("only one of -c or an inline [CONTAINER] arg is allowed")
  236. }
  237. if o.LimitBytes < 0 {
  238. return fmt.Errorf("--limit-bytes must be greater than 0")
  239. }
  240. if logsOptions.SinceSeconds != nil && *logsOptions.SinceSeconds < int64(0) {
  241. return fmt.Errorf("--since must be greater than 0")
  242. }
  243. if logsOptions.TailLines != nil && *logsOptions.TailLines < 0 {
  244. return fmt.Errorf("TailLines must be greater than or equal to 0")
  245. }
  246. return nil
  247. }
  248. // RunLogs retrieves a pod log
  249. func (o LogsOptions) RunLogs() error {
  250. requests, err := o.LogsForObject(o.RESTClientGetter, o.Object, o.Options, o.GetPodTimeout, o.AllContainers)
  251. if err != nil {
  252. return err
  253. }
  254. if o.Follow && len(requests) > 1 {
  255. if len(requests) > o.MaxFollowConcurency {
  256. return fmt.Errorf(
  257. "you are attempting to follow %d log streams, but maximum allowed concurency is %d, use --max-log-requests to increase the limit",
  258. len(requests), o.MaxFollowConcurency,
  259. )
  260. }
  261. return o.parallelConsumeRequest(requests)
  262. }
  263. return o.sequentialConsumeRequest(requests)
  264. }
  265. func (o LogsOptions) parallelConsumeRequest(requests []rest.ResponseWrapper) error {
  266. reader, writer := io.Pipe()
  267. wg := &sync.WaitGroup{}
  268. wg.Add(len(requests))
  269. for _, request := range requests {
  270. go func(request rest.ResponseWrapper) {
  271. if err := o.ConsumeRequestFn(request, writer); err != nil {
  272. if !o.IgnoreLogErrors {
  273. writer.CloseWithError(err)
  274. // It's important to return here to propagate the error via the pipe
  275. return
  276. }
  277. fmt.Fprintf(writer, "error: %v\n", err)
  278. }
  279. wg.Done()
  280. }(request)
  281. }
  282. go func() {
  283. wg.Wait()
  284. writer.Close()
  285. }()
  286. _, err := io.Copy(o.Out, reader)
  287. return err
  288. }
  289. func (o LogsOptions) sequentialConsumeRequest(requests []rest.ResponseWrapper) error {
  290. for _, request := range requests {
  291. if err := o.ConsumeRequestFn(request, o.Out); err != nil {
  292. return err
  293. }
  294. }
  295. return nil
  296. }
  297. // DefaultConsumeRequest reads the data from request and writes into
  298. // the out writer. It buffers data from requests until the newline or io.EOF
  299. // occurs in the data, so it doesn't interleave logs sub-line
  300. // when running concurrently.
  301. //
  302. // A successful read returns err == nil, not err == io.EOF.
  303. // Because the function is defined to read from request until io.EOF, it does
  304. // not treat an io.EOF as an error to be reported.
  305. func DefaultConsumeRequest(request rest.ResponseWrapper, out io.Writer) error {
  306. readCloser, err := request.Stream()
  307. if err != nil {
  308. return err
  309. }
  310. defer readCloser.Close()
  311. r := bufio.NewReader(readCloser)
  312. for {
  313. bytes, err := r.ReadBytes('\n')
  314. if _, err := out.Write(bytes); err != nil {
  315. return err
  316. }
  317. if err != nil {
  318. if err != io.EOF {
  319. return err
  320. }
  321. return nil
  322. }
  323. }
  324. }