storedefault.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 TypedContext
  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 dockerGefaultContext() (*Metadata, error) {
  29. cmd := exec.Command("docker", "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. Endpoints: map[string]Endpoint{
  48. "docker": {
  49. Host: defaultCtx.Endpoints.Docker.Host,
  50. },
  51. "kubernetes": {
  52. Host: defaultCtx.Endpoints.Kubernetes.Host,
  53. DefaultNamespace: defaultCtx.Endpoints.Kubernetes.DefaultNamespace,
  54. },
  55. },
  56. Metadata: TypedContext{
  57. Description: "Current DOCKER_HOST based configuration",
  58. Type: "docker",
  59. StackOrchestrator: defaultCtx.Metadata.StackOrchestrator,
  60. Data: defaultCtx.Metadata,
  61. },
  62. }
  63. return &meta, nil
  64. }