events.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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/client"
  19. "github.com/docker/compose-cli/api/compose"
  20. "github.com/spf13/cobra"
  21. )
  22. type eventsOpts struct {
  23. *composeOptions
  24. json bool
  25. }
  26. func eventsCommand(p *projectOptions) *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: func(cmd *cobra.Command, args []string) error {
  36. return runEvents(cmd.Context(), opts, args)
  37. },
  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, opts eventsOpts, services []string) error {
  43. c, err := client.New(ctx)
  44. if err != nil {
  45. return err
  46. }
  47. project, err := opts.toProjectName()
  48. if err != nil {
  49. return err
  50. }
  51. return c.ComposeService().Events(ctx, project, compose.EventsOptions{
  52. Services: services,
  53. Consumer: func(event compose.Event) error {
  54. if opts.json {
  55. marshal, err := json.Marshal(map[string]interface{}{
  56. "time": event.Timestamp,
  57. "type": "container",
  58. "service": event.Service,
  59. "id": event.Container,
  60. "action": event.Status,
  61. "attributes": event.Attributes,
  62. })
  63. if err != nil {
  64. return err
  65. }
  66. fmt.Println(string(marshal))
  67. } else {
  68. fmt.Println(event)
  69. }
  70. return nil
  71. },
  72. })
  73. }