storedefault.go 2.0 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 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() (*DockerContext, error) {
  29. // ensure we run this using default context, in current context has been damaged / removed in store
  30. cmd := exec.Command("com.docker.cli", "--context", "default", "context", "inspect", "default")
  31. var stdout bytes.Buffer
  32. cmd.Stdout = &stdout
  33. err := cmd.Run()
  34. if err != nil {
  35. return nil, err
  36. }
  37. var ctx []defaultContext
  38. err = json.Unmarshal(stdout.Bytes(), &ctx)
  39. if err != nil {
  40. return nil, err
  41. }
  42. if len(ctx) != 1 {
  43. return nil, errors.New("found more than one default context")
  44. }
  45. defaultCtx := ctx[0]
  46. meta := DockerContext{
  47. Name: "default",
  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. Type: DefaultContextType,
  59. Description: "Current DOCKER_HOST based configuration",
  60. StackOrchestrator: defaultCtx.Metadata.StackOrchestrator,
  61. },
  62. }
  63. return &meta, nil
  64. }