store.go 9.0 KB

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