events.go 2.0 KB

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