serve.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package cmd
  2. import (
  3. "context"
  4. "github.com/pkg/errors"
  5. "github.com/sirupsen/logrus"
  6. cliv1 "github.com/docker/api/cli/v1"
  7. containersv1 "github.com/docker/api/containers/v1"
  8. "github.com/docker/api/context/store"
  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. cliv1.RegisterCliServer(s, &cliServer{
  41. ctx,
  42. })
  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. }
  52. type cliServer struct {
  53. ctx context.Context
  54. }
  55. func (cs *cliServer) Contexts(ctx context.Context, request *cliv1.ContextsRequest) (*cliv1.ContextsResponse, error) {
  56. s := store.ContextStore(ctx)
  57. contexts, err := s.List()
  58. if err != nil {
  59. logrus.Error(err)
  60. return &cliv1.ContextsResponse{}, err
  61. }
  62. result := &cliv1.ContextsResponse{}
  63. for _, c := range contexts {
  64. result.Contexts = append(result.Contexts, &cliv1.Context{
  65. Name: c.Name,
  66. ContextType: c.Metadata.Type,
  67. })
  68. }
  69. return result, nil
  70. }