events.go 2.0 KB

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