serve.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package cmd
  2. import (
  3. "context"
  4. "github.com/pkg/errors"
  5. "github.com/sirupsen/logrus"
  6. "github.com/docker/api/context/store"
  7. containersv1 "github.com/docker/api/protos/containers/v1"
  8. contextsv1 "github.com/docker/api/protos/contexts/v1"
  9. "github.com/docker/api/server"
  10. "github.com/docker/api/server/proxy"
  11. "github.com/spf13/cobra"
  12. )
  13. type serveOpts struct {
  14. address string
  15. }
  16. // ServeCommand returns the command to serve the API
  17. func ServeCommand() *cobra.Command {
  18. // FIXME(chris-crone): Should warn that specified context is ignored
  19. var opts serveOpts
  20. cmd := &cobra.Command{
  21. Use: "serve",
  22. Short: "Start an api server",
  23. RunE: func(cmd *cobra.Command, args []string) error {
  24. return runServe(cmd.Context(), opts)
  25. },
  26. }
  27. cmd.Flags().StringVar(&opts.address, "address", "", "The address to listen to")
  28. return cmd
  29. }
  30. func runServe(ctx context.Context, opts serveOpts) error {
  31. s := server.New(ctx)
  32. listener, err := server.CreateListener(opts.address)
  33. if err != nil {
  34. return errors.Wrap(err, "listen address "+opts.address)
  35. }
  36. // nolint errcheck
  37. defer listener.Close()
  38. p := proxy.NewContainerAPI()
  39. containersv1.RegisterContainersServer(s, p)
  40. contextsv1.RegisterContextsServer(s, &cliServer{})
  41. go func() {
  42. <-ctx.Done()
  43. logrus.Info("stopping server")
  44. s.Stop()
  45. }()
  46. logrus.WithField("address", opts.address).Info("serving daemon API")
  47. // start the GRPC server to serve on the listener
  48. return s.Serve(listener)
  49. }
  50. type cliServer struct {
  51. }
  52. func (cs *cliServer) List(ctx context.Context, request *contextsv1.ListRequest) (*contextsv1.ListResponse, error) {
  53. s := store.ContextStore(ctx)
  54. contexts, err := s.List()
  55. if err != nil {
  56. logrus.Error(err)
  57. return &contextsv1.ListResponse{}, err
  58. }
  59. result := &contextsv1.ListResponse{}
  60. for _, c := range contexts {
  61. result.Contexts = append(result.Contexts, &contextsv1.Context{
  62. Name: c.Name,
  63. ContextType: c.Type,
  64. })
  65. }
  66. return result, nil
  67. }