storedefault.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package store
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "os/exec"
  6. "github.com/pkg/errors"
  7. )
  8. // Represents a context as created by the docker cli
  9. type defaultContext struct {
  10. Metadata ContextMetadata
  11. Endpoints endpoints
  12. }
  13. // Normally (in docker/cli code), the endpoints are mapped as map[string]interface{}
  14. // but docker cli contexts always have a "docker" and "kubernetes" key so we
  15. // create real types for those to no have to juggle around with interfaces.
  16. type endpoints struct {
  17. Docker endpoint `json:"docker,omitempty"`
  18. Kubernetes endpoint `json:"kubernetes,omitempty"`
  19. }
  20. // Both "docker" and "kubernetes" endpoints in the docker cli created contexts
  21. // have a "Host", only kubernetes has the "DefaultNamespace", we put both of
  22. // those here for easier manipulation and to not have to create two distinct
  23. // structs
  24. type endpoint struct {
  25. Host string
  26. DefaultNamespace string
  27. }
  28. func dockerDefaultContext() (*Metadata, error) {
  29. cmd := exec.Command("docker-classic", "context", "inspect", "default")
  30. var stdout bytes.Buffer
  31. cmd.Stdout = &stdout
  32. err := cmd.Run()
  33. if err != nil {
  34. return nil, err
  35. }
  36. var ctx []defaultContext
  37. err = json.Unmarshal(stdout.Bytes(), &ctx)
  38. if err != nil {
  39. return nil, err
  40. }
  41. if len(ctx) != 1 {
  42. return nil, errors.New("found more than one default context")
  43. }
  44. defaultCtx := ctx[0]
  45. meta := Metadata{
  46. Name: "default",
  47. Type: "docker",
  48. Endpoints: map[string]interface{}{
  49. "docker": Endpoint{
  50. Host: defaultCtx.Endpoints.Docker.Host,
  51. },
  52. "kubernetes": Endpoint{
  53. Host: defaultCtx.Endpoints.Kubernetes.Host,
  54. DefaultNamespace: defaultCtx.Endpoints.Kubernetes.DefaultNamespace,
  55. },
  56. },
  57. Metadata: ContextMetadata{
  58. Description: "Current DOCKER_HOST based configuration",
  59. StackOrchestrator: defaultCtx.Metadata.StackOrchestrator,
  60. },
  61. }
  62. return &meta, nil
  63. }