storedefault.go 2.0 KB

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