logs.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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 cmd
  14. import (
  15. "errors"
  16. "io"
  17. "math"
  18. "os"
  19. "time"
  20. "github.com/renstrom/dedent"
  21. "github.com/spf13/cobra"
  22. "k8s.io/kubernetes/pkg/api"
  23. "k8s.io/kubernetes/pkg/api/meta"
  24. "k8s.io/kubernetes/pkg/api/unversioned"
  25. "k8s.io/kubernetes/pkg/api/validation"
  26. "k8s.io/kubernetes/pkg/client/restclient"
  27. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  28. "k8s.io/kubernetes/pkg/kubectl/resource"
  29. "k8s.io/kubernetes/pkg/runtime"
  30. )
  31. var (
  32. logs_example = dedent.Dedent(`
  33. # Return snapshot logs from pod nginx with only one container
  34. kubectl logs nginx
  35. # Return snapshot of previous terminated ruby container logs from pod web-1
  36. kubectl logs -p -c ruby web-1
  37. # Begin streaming the logs of the ruby container in pod web-1
  38. kubectl logs -f -c ruby web-1
  39. # Display only the most recent 20 lines of output in pod nginx
  40. kubectl logs --tail=20 nginx
  41. # Show all logs from pod nginx written in the last hour
  42. kubectl logs --since=1h nginx`)
  43. )
  44. type LogsOptions struct {
  45. Namespace string
  46. ResourceArg string
  47. Options runtime.Object
  48. Mapper meta.RESTMapper
  49. Typer runtime.ObjectTyper
  50. ClientMapper resource.ClientMapper
  51. Decoder runtime.Decoder
  52. Object runtime.Object
  53. LogsForObject func(object, options runtime.Object) (*restclient.Request, error)
  54. Out io.Writer
  55. }
  56. // NewCmdLog creates a new pod logs command
  57. func NewCmdLogs(f *cmdutil.Factory, out io.Writer) *cobra.Command {
  58. o := &LogsOptions{}
  59. cmd := &cobra.Command{
  60. Use: "logs [-f] [-p] POD [-c CONTAINER]",
  61. Short: "Print the logs for a container in a pod",
  62. Long: "Print the logs for a container in a pod. If the pod has only one container, the container name is optional.",
  63. Example: logs_example,
  64. PreRun: func(cmd *cobra.Command, args []string) {
  65. if len(os.Args) > 1 && os.Args[1] == "log" {
  66. printDeprecationWarning("logs", "log")
  67. }
  68. },
  69. Run: func(cmd *cobra.Command, args []string) {
  70. cmdutil.CheckErr(o.Complete(f, out, cmd, args))
  71. if err := o.Validate(); err != nil {
  72. cmdutil.CheckErr(cmdutil.UsageError(cmd, err.Error()))
  73. }
  74. _, err := o.RunLogs()
  75. cmdutil.CheckErr(err)
  76. },
  77. Aliases: []string{"log"},
  78. }
  79. cmd.Flags().BoolP("follow", "f", false, "Specify if the logs should be streamed.")
  80. cmd.Flags().Bool("timestamps", false, "Include timestamps on each line in the log output")
  81. cmd.Flags().Int64("limit-bytes", 0, "Maximum bytes of logs to return. Defaults to no limit.")
  82. cmd.Flags().BoolP("previous", "p", false, "If true, print the logs for the previous instance of the container in a pod if it exists.")
  83. cmd.Flags().Int64("tail", -1, "Lines of recent log file to display. Defaults to -1, showing all log lines.")
  84. cmd.Flags().String("since-time", "", "Only return logs after a specific date (RFC3339). Defaults to all logs. Only one of since-time / since may be used.")
  85. cmd.Flags().Duration("since", 0, "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.")
  86. cmd.Flags().StringP("container", "c", "", "Print the logs of this container")
  87. cmd.Flags().Bool("interactive", false, "If true, prompt the user for input when required.")
  88. cmd.Flags().MarkDeprecated("interactive", "This flag is no longer respected and there is no replacement.")
  89. cmdutil.AddInclude3rdPartyFlags(cmd)
  90. return cmd
  91. }
  92. func (o *LogsOptions) Complete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error {
  93. containerName := cmdutil.GetFlagString(cmd, "container")
  94. switch len(args) {
  95. case 0:
  96. return cmdutil.UsageError(cmd, "POD is required for logs")
  97. case 1:
  98. o.ResourceArg = args[0]
  99. case 2:
  100. if cmd.Flag("container").Changed {
  101. return cmdutil.UsageError(cmd, "only one of -c, [CONTAINER] arg is allowed")
  102. }
  103. o.ResourceArg = args[0]
  104. containerName = args[1]
  105. default:
  106. return cmdutil.UsageError(cmd, "logs POD [-c CONTAINER]")
  107. }
  108. var err error
  109. o.Namespace, _, err = f.DefaultNamespace()
  110. if err != nil {
  111. return err
  112. }
  113. logOptions := &api.PodLogOptions{
  114. Container: containerName,
  115. Follow: cmdutil.GetFlagBool(cmd, "follow"),
  116. Previous: cmdutil.GetFlagBool(cmd, "previous"),
  117. Timestamps: cmdutil.GetFlagBool(cmd, "timestamps"),
  118. }
  119. if sinceTime := cmdutil.GetFlagString(cmd, "since-time"); len(sinceTime) > 0 {
  120. t, err := api.ParseRFC3339(sinceTime, unversioned.Now)
  121. if err != nil {
  122. return err
  123. }
  124. logOptions.SinceTime = &t
  125. }
  126. if limit := cmdutil.GetFlagInt64(cmd, "limit-bytes"); limit != 0 {
  127. logOptions.LimitBytes = &limit
  128. }
  129. if tail := cmdutil.GetFlagInt64(cmd, "tail"); tail != -1 {
  130. logOptions.TailLines = &tail
  131. }
  132. if sinceSeconds := cmdutil.GetFlagDuration(cmd, "since"); sinceSeconds != 0 {
  133. // round up to the nearest second
  134. sec := int64(math.Ceil(float64(sinceSeconds) / float64(time.Second)))
  135. logOptions.SinceSeconds = &sec
  136. }
  137. o.Options = logOptions
  138. o.LogsForObject = f.LogsForObject
  139. o.ClientMapper = resource.ClientMapperFunc(f.ClientForMapping)
  140. o.Out = out
  141. mapper, typer := f.Object(cmdutil.GetIncludeThirdPartyAPIs(cmd))
  142. decoder := f.Decoder(true)
  143. if o.Object == nil {
  144. infos, err := resource.NewBuilder(mapper, typer, o.ClientMapper, decoder).
  145. NamespaceParam(o.Namespace).DefaultNamespace().
  146. ResourceNames("pods", o.ResourceArg).
  147. SingleResourceType().
  148. Do().Infos()
  149. if err != nil {
  150. return err
  151. }
  152. if len(infos) != 1 {
  153. return errors.New("expected a resource")
  154. }
  155. o.Object = infos[0].Object
  156. }
  157. return nil
  158. }
  159. func (o LogsOptions) Validate() error {
  160. if len(o.ResourceArg) == 0 {
  161. return errors.New("a pod must be specified")
  162. }
  163. logsOptions, ok := o.Options.(*api.PodLogOptions)
  164. if !ok {
  165. return errors.New("unexpected logs options object")
  166. }
  167. if errs := validation.ValidatePodLogOptions(logsOptions); len(errs) > 0 {
  168. return errs.ToAggregate()
  169. }
  170. return nil
  171. }
  172. // RunLogs retrieves a pod log
  173. func (o LogsOptions) RunLogs() (int64, error) {
  174. req, err := o.LogsForObject(o.Object, o.Options)
  175. if err != nil {
  176. return 0, err
  177. }
  178. readCloser, err := req.Stream()
  179. if err != nil {
  180. return 0, err
  181. }
  182. defer readCloser.Close()
  183. return io.Copy(o.Out, readCloser)
  184. }