store.go 8.6 KB

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