serve.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package cmd
  2. import (
  3. "context"
  4. "github.com/pkg/errors"
  5. "github.com/sirupsen/logrus"
  6. "github.com/spf13/cobra"
  7. apicontext "github.com/docker/api/context"
  8. containersv1 "github.com/docker/api/protos/containers/v1"
  9. contextsv1 "github.com/docker/api/protos/contexts/v1"
  10. streamsv1 "github.com/docker/api/protos/streams/v1"
  11. "github.com/docker/api/server"
  12. "github.com/docker/api/server/proxy"
  13. )
  14. type serveOpts struct {
  15. address string
  16. }
  17. // ServeCommand returns the command to serve the API
  18. func ServeCommand() *cobra.Command {
  19. // FIXME(chris-crone): Should warn that specified context is ignored
  20. var opts serveOpts
  21. cmd := &cobra.Command{
  22. Use: "serve",
  23. Short: "Start an api server",
  24. RunE: func(cmd *cobra.Command, args []string) error {
  25. return runServe(cmd.Context(), opts)
  26. },
  27. }
  28. cmd.Flags().StringVar(&opts.address, "address", "", "The address to listen to")
  29. return cmd
  30. }
  31. func runServe(ctx context.Context, opts serveOpts) error {
  32. s := server.New(ctx)
  33. listener, err := server.CreateListener(opts.address)
  34. if err != nil {
  35. return errors.Wrap(err, "listen address "+opts.address)
  36. }
  37. // nolint errcheck
  38. defer listener.Close()
  39. p := proxy.New(apicontext.CurrentContext(ctx))
  40. containersv1.RegisterContainersServer(s, p)
  41. streamsv1.RegisterStreamingServer(s, p)
  42. contextsv1.RegisterContextsServer(s, p.ContextsProxy())
  43. go func() {
  44. <-ctx.Done()
  45. logrus.Info("stopping server")
  46. s.Stop()
  47. }()
  48. logrus.WithField("address", opts.address).Info("serving daemon API")
  49. // start the GRPC server to serve on the listener
  50. return s.Serve(listener)
  51. }