serve.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package cmd
  2. import (
  3. "context"
  4. "net"
  5. "github.com/pkg/errors"
  6. "github.com/sirupsen/logrus"
  7. cliv1 "github.com/docker/api/cli/v1"
  8. containersv1 "github.com/docker/api/containers/v1"
  9. "github.com/docker/api/context/store"
  10. "github.com/docker/api/server"
  11. "github.com/docker/api/server/proxy"
  12. "github.com/spf13/cobra"
  13. )
  14. type serveOpts struct {
  15. address string
  16. }
  17. // ServeCommand returns the command to serve the API
  18. func ServeCommand() *cobra.Command {
  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()
  32. listener, err := net.Listen("unix", opts.address)
  33. if err != nil {
  34. return errors.Wrap(err, "listen unix socket")
  35. }
  36. // nolint
  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, err := store.New()
  57. if err != nil {
  58. logrus.Error(err)
  59. return &cliv1.ContextsResponse{}, err
  60. }
  61. contexts, err := s.List()
  62. if err != nil {
  63. logrus.Error(err)
  64. return &cliv1.ContextsResponse{}, err
  65. }
  66. result := &cliv1.ContextsResponse{}
  67. for _, c := range contexts {
  68. result.Contexts = append(result.Contexts, &cliv1.Context{
  69. Name: c.Name,
  70. ContextType: c.Metadata.Type,
  71. })
  72. }
  73. return result, nil
  74. }