events.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. Copyright 2020 Docker Compose CLI 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 compose
  14. import (
  15. "context"
  16. "encoding/json"
  17. "fmt"
  18. "github.com/docker/cli/cli/command"
  19. "github.com/docker/compose/v2/pkg/api"
  20. "github.com/spf13/cobra"
  21. )
  22. type eventsOpts struct {
  23. *composeOptions
  24. json bool
  25. }
  26. func eventsCommand(p *ProjectOptions, dockerCli command.Cli, backend api.Service) *cobra.Command {
  27. opts := eventsOpts{
  28. composeOptions: &composeOptions{
  29. ProjectOptions: p,
  30. },
  31. }
  32. cmd := &cobra.Command{
  33. Use: "events [OPTIONS] [SERVICE...]",
  34. Short: "Receive real time events from containers.",
  35. RunE: Adapt(func(ctx context.Context, args []string) error {
  36. return runEvents(ctx, dockerCli, backend, opts, args)
  37. }),
  38. ValidArgsFunction: completeServiceNames(dockerCli, p),
  39. }
  40. cmd.Flags().BoolVar(&opts.json, "json", false, "Output events as a stream of json objects")
  41. return cmd
  42. }
  43. func runEvents(ctx context.Context, dockerCli command.Cli, backend api.Service, opts eventsOpts, services []string) error {
  44. name, err := opts.toProjectName(dockerCli)
  45. if err != nil {
  46. return err
  47. }
  48. return backend.Events(ctx, name, api.EventsOptions{
  49. Services: services,
  50. Consumer: func(event api.Event) error {
  51. if opts.json {
  52. marshal, err := json.Marshal(map[string]interface{}{
  53. "time": event.Timestamp,
  54. "type": "container",
  55. "service": event.Service,
  56. "id": event.Container,
  57. "action": event.Status,
  58. "attributes": event.Attributes,
  59. })
  60. if err != nil {
  61. return err
  62. }
  63. fmt.Fprintln(dockerCli.Out(), string(marshal))
  64. } else {
  65. fmt.Fprintln(dockerCli.Out(), event)
  66. }
  67. return nil
  68. },
  69. })
  70. }