serve.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. var opts serveOpts
  19. cmd := &cobra.Command{
  20. Use: "serve",
  21. Short: "Start an api server",
  22. RunE: func(cmd *cobra.Command, args []string) error {
  23. return runServe(cmd.Context(), opts)
  24. },
  25. }
  26. cmd.Flags().StringVar(&opts.address, "address", "", "The address to listen to")
  27. return cmd
  28. }
  29. func runServe(ctx context.Context, opts serveOpts) error {
  30. s := server.New()
  31. listener, err := server.CreateListener(opts.address)
  32. if err != nil {
  33. return errors.Wrap(err, "listen address "+opts.address)
  34. }
  35. // nolint errcheck
  36. defer listener.Close()
  37. p := proxy.NewContainerAPI()
  38. containersv1.RegisterContainersServer(s, p)
  39. cliv1.RegisterCliServer(s, &cliServer{
  40. ctx,
  41. })
  42. go func() {
  43. <-ctx.Done()
  44. logrus.Info("stopping server")
  45. s.Stop()
  46. }()
  47. logrus.WithField("address", opts.address).Info("serving daemon API")
  48. // start the GRPC server to serve on the listener
  49. return s.Serve(listener)
  50. }
  51. type cliServer struct {
  52. ctx context.Context
  53. }
  54. func (cs *cliServer) Contexts(ctx context.Context, request *cliv1.ContextsRequest) (*cliv1.ContextsResponse, error) {
  55. s, err := store.New()
  56. if err != nil {
  57. logrus.Error(err)
  58. return &cliv1.ContextsResponse{}, err
  59. }
  60. contexts, err := s.List()
  61. if err != nil {
  62. logrus.Error(err)
  63. return &cliv1.ContextsResponse{}, err
  64. }
  65. result := &cliv1.ContextsResponse{}
  66. for _, c := range contexts {
  67. result.Contexts = append(result.Contexts, &cliv1.Context{
  68. Name: c.Name,
  69. ContextType: c.Metadata.Type,
  70. })
  71. }
  72. return result, nil
  73. }