serve.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 cmd
  14. import (
  15. "context"
  16. "github.com/pkg/errors"
  17. "github.com/sirupsen/logrus"
  18. "github.com/spf13/cobra"
  19. "github.com/docker/compose-cli/cli/server"
  20. composev1 "github.com/docker/compose-cli/cli/server/protos/compose/v1"
  21. containersv1 "github.com/docker/compose-cli/cli/server/protos/containers/v1"
  22. contextsv1 "github.com/docker/compose-cli/cli/server/protos/contexts/v1"
  23. streamsv1 "github.com/docker/compose-cli/cli/server/protos/streams/v1"
  24. volumesv1 "github.com/docker/compose-cli/cli/server/protos/volumes/v1"
  25. "github.com/docker/compose-cli/cli/server/proxy"
  26. )
  27. type serveOpts struct {
  28. address string
  29. }
  30. // ServeCommand returns the command to serve the API
  31. func ServeCommand() *cobra.Command {
  32. // FIXME(chris-crone): Should warn that specified context is ignored
  33. var opts serveOpts
  34. cmd := &cobra.Command{
  35. Use: "serve",
  36. Short: "Start an api server",
  37. RunE: func(cmd *cobra.Command, args []string) error {
  38. return runServe(cmd.Context(), opts)
  39. },
  40. }
  41. cmd.Flags().StringVar(&opts.address, "address", "", "The address to listen to")
  42. return cmd
  43. }
  44. func runServe(ctx context.Context, opts serveOpts) error {
  45. s := server.New(ctx)
  46. listener, err := server.CreateListener(opts.address)
  47. if err != nil {
  48. return errors.Wrap(err, "listen address "+opts.address)
  49. }
  50. // nolint errcheck
  51. defer listener.Close()
  52. p := proxy.New(ctx)
  53. composev1.RegisterComposeServer(s, p)
  54. containersv1.RegisterContainersServer(s, p)
  55. contextsv1.RegisterContextsServer(s, p.ContextsProxy())
  56. streamsv1.RegisterStreamingServer(s, p)
  57. volumesv1.RegisterVolumesServer(s, p)
  58. go func() {
  59. <-ctx.Done()
  60. logrus.Info("stopping server")
  61. s.Stop()
  62. }()
  63. logrus.WithField("address", opts.address).Info("serving daemon API")
  64. // start the GRPC server to serve on the listener
  65. return s.Serve(listener)
  66. }