store.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package store
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "io/ioutil"
  18. "os"
  19. "path/filepath"
  20. "reflect"
  21. "github.com/opencontainers/go-digest"
  22. "github.com/pkg/errors"
  23. "github.com/docker/compose-cli/api/errdefs"
  24. )
  25. const (
  26. // DefaultContextName is an automatically generated local context
  27. DefaultContextName = "default"
  28. // DefaultContextType is the type for all moby contexts (not associated with cli backend)
  29. DefaultContextType = "moby"
  30. // AwsContextType is the type for aws contexts (currently a CLI plugin, not associated with cli backend)
  31. // to be removed with the cli plugin
  32. AwsContextType = "aws"
  33. // EcsContextType is the endpoint key in the context endpoints for an ECS
  34. // backend
  35. EcsContextType = "ecs"
  36. // EcsLocalSimulationContextType is the endpoint key in the context endpoints for an ECS backend
  37. // running local simulation endpoints
  38. EcsLocalSimulationContextType = "ecs-local"
  39. // AciContextType is the endpoint key in the context endpoints for an ACI
  40. // backend
  41. AciContextType = "aci"
  42. // LocalContextType is the endpoint key in the context endpoints for a new
  43. // local backend
  44. LocalContextType = "local"
  45. // KubeContextType is the endpoint key in the context endpoints for a new
  46. // kube backend
  47. KubeContextType = "kube"
  48. )
  49. const (
  50. dockerEndpointKey = "docker"
  51. contextsDir = "contexts"
  52. metadataDir = "meta"
  53. metaFile = "meta.json"
  54. )
  55. var instance Store
  56. // WithContextStore adds the store to the context
  57. func WithContextStore(store Store) {
  58. instance = store
  59. }
  60. // Instance returns the store from the context
  61. func Instance() Store {
  62. return instance
  63. }
  64. // Store is the context store
  65. type Store interface {
  66. // Get returns the context with name, it returns an error if the context
  67. // doesn't exist
  68. Get(name string) (*DockerContext, error)
  69. // GetEndpoint sets the `v` parameter to the value of the endpoint for a
  70. // particular context type
  71. GetEndpoint(name string, v interface{}) error
  72. // Create creates a new context, it returns an error if a context with the
  73. // same name exists already.
  74. Create(name string, contextType string, description string, data interface{}) error
  75. // List returns the list of created contexts
  76. List() ([]*DockerContext, error)
  77. // Remove removes a context by name from the context store
  78. Remove(name string) error
  79. // ContextExists checks if a context already exists
  80. ContextExists(name string) bool
  81. }
  82. // Endpoint holds the Docker or the Kubernetes endpoint, they both have the
  83. // `Host` property, only kubernetes will have the `DefaultNamespace`
  84. type Endpoint struct {
  85. Host string `json:",omitempty"`
  86. DefaultNamespace string `json:",omitempty"`
  87. }
  88. type store struct {
  89. root string
  90. }
  91. // New returns a configured context store with specified root dir (eg. $HOME/.docker) as root
  92. func New(rootDir string) (Store, error) {
  93. s := &store{
  94. root: rootDir,
  95. }
  96. m := filepath.Join(s.root, contextsDir, metadataDir)
  97. if err := createDirIfNotExist(m); err != nil {
  98. return nil, err
  99. }
  100. return s, nil
  101. }
  102. // Get returns the context with the given name
  103. func (s *store) Get(name string) (*DockerContext, error) {
  104. if name == "default" {
  105. return dockerDefaultContext()
  106. }
  107. meta := filepath.Join(s.root, contextsDir, metadataDir, contextDirOf(name), metaFile)
  108. m, err := read(meta)
  109. if os.IsNotExist(err) {
  110. return nil, errors.Wrap(errdefs.ErrNotFound, objectName(name))
  111. } else if err != nil {
  112. return nil, err
  113. }
  114. return m, nil
  115. }
  116. func (s *store) GetEndpoint(name string, data interface{}) error {
  117. meta, err := s.Get(name)
  118. if err != nil {
  119. return err
  120. }
  121. contextType := meta.Type()
  122. if _, ok := meta.Endpoints[contextType]; !ok {
  123. return errors.Wrapf(errdefs.ErrNotFound, "endpoint of type %q", contextType)
  124. }
  125. dstPtrValue := reflect.ValueOf(data)
  126. dstValue := reflect.Indirect(dstPtrValue)
  127. val := reflect.ValueOf(meta.Endpoints[contextType])
  128. valIndirect := reflect.Indirect(val)
  129. if dstValue.Type() != valIndirect.Type() {
  130. return errdefs.ErrWrongContextType
  131. }
  132. dstValue.Set(valIndirect)
  133. return nil
  134. }
  135. func read(meta string) (*DockerContext, error) {
  136. bytes, err := ioutil.ReadFile(meta)
  137. if err != nil {
  138. return nil, err
  139. }
  140. var metadata DockerContext
  141. if err := json.Unmarshal(bytes, &metadata); err != nil {
  142. return nil, err
  143. }
  144. metadata.Endpoints, err = toTypedEndpoints(metadata.Endpoints)
  145. if err != nil {
  146. return nil, err
  147. }
  148. return &metadata, nil
  149. }
  150. func toTypedEndpoints(endpoints map[string]interface{}) (map[string]interface{}, error) {
  151. result := map[string]interface{}{}
  152. for k, v := range endpoints {
  153. bytes, err := json.Marshal(v)
  154. if err != nil {
  155. return nil, err
  156. }
  157. typeGetters := getters()
  158. typeGetter, ok := typeGetters[k]
  159. if !ok {
  160. typeGetter = func() interface{} {
  161. return &Endpoint{}
  162. }
  163. }
  164. val := typeGetter()
  165. err = json.Unmarshal(bytes, &val)
  166. if err != nil {
  167. return nil, err
  168. }
  169. result[k] = val
  170. }
  171. return result, nil
  172. }
  173. func (s *store) ContextExists(name string) bool {
  174. if name == DefaultContextName {
  175. return true
  176. }
  177. dir := contextDirOf(name)
  178. metaDir := filepath.Join(s.root, contextsDir, metadataDir, dir)
  179. if _, err := os.Stat(metaDir); !os.IsNotExist(err) {
  180. return true
  181. }
  182. return false
  183. }
  184. func (s *store) Create(name string, contextType string, description string, data interface{}) error {
  185. if s.ContextExists(name) {
  186. return errors.Wrap(errdefs.ErrAlreadyExists, objectName(name))
  187. }
  188. dir := contextDirOf(name)
  189. metaDir := filepath.Join(s.root, contextsDir, metadataDir, dir)
  190. err := os.Mkdir(metaDir, 0755)
  191. if err != nil {
  192. return err
  193. }
  194. meta := DockerContext{
  195. Name: name,
  196. Metadata: ContextMetadata{
  197. Type: contextType,
  198. Description: description,
  199. },
  200. Endpoints: map[string]interface{}{
  201. (dockerEndpointKey): data,
  202. (contextType): data,
  203. },
  204. }
  205. bytes, err := json.Marshal(&meta)
  206. if err != nil {
  207. return err
  208. }
  209. return ioutil.WriteFile(filepath.Join(metaDir, metaFile), bytes, 0644)
  210. }
  211. func (s *store) List() ([]*DockerContext, error) {
  212. root := filepath.Join(s.root, contextsDir, metadataDir)
  213. c, err := ioutil.ReadDir(root)
  214. if err != nil {
  215. return nil, err
  216. }
  217. var result []*DockerContext
  218. for _, fi := range c {
  219. if fi.IsDir() {
  220. meta := filepath.Join(root, fi.Name(), metaFile)
  221. r, err := read(meta)
  222. if err != nil {
  223. return nil, err
  224. }
  225. result = append(result, r)
  226. }
  227. }
  228. // The default context is not stored in the store, it is in-memory only
  229. // so we need a special case for it.
  230. dockerDefault, err := dockerDefaultContext()
  231. if err != nil {
  232. return nil, err
  233. }
  234. result = append(result, dockerDefault)
  235. return result, nil
  236. }
  237. func (s *store) Remove(name string) error {
  238. if name == DefaultContextName {
  239. return errors.Wrap(errdefs.ErrForbidden, objectName(name))
  240. }
  241. dir := filepath.Join(s.root, contextsDir, metadataDir, contextDirOf(name))
  242. // Check if directory exists because os.RemoveAll returns nil if it doesn't
  243. if _, err := os.Stat(dir); os.IsNotExist(err) {
  244. return errors.Wrap(errdefs.ErrNotFound, objectName(name))
  245. }
  246. if err := os.RemoveAll(dir); err != nil {
  247. return errors.Wrapf(errdefs.ErrUnknown, "unable to remove %s: %s", objectName(name), err)
  248. }
  249. return nil
  250. }
  251. func contextDirOf(name string) string {
  252. return digest.FromString(name).Encoded()
  253. }
  254. func objectName(name string) string {
  255. return fmt.Sprintf("context %q", name)
  256. }
  257. func createDirIfNotExist(dir string) error {
  258. if _, err := os.Stat(dir); os.IsNotExist(err) {
  259. if err = os.MkdirAll(dir, 0755); err != nil {
  260. return err
  261. }
  262. }
  263. return nil
  264. }
  265. // Different context types managed by the store.
  266. // TODO(rumpl): we should make this extensible in the future if we want to
  267. // be able to manage other contexts.
  268. func getters() map[string]func() interface{} {
  269. return map[string]func() interface{}{
  270. AciContextType: func() interface{} {
  271. return &AciContext{}
  272. },
  273. EcsContextType: func() interface{} {
  274. return &EcsContext{}
  275. },
  276. LocalContextType: func() interface{} {
  277. return &LocalContext{}
  278. },
  279. KubeContextType: func() interface{} {
  280. return &KubeContext{}
  281. },
  282. }
  283. }