store.go 8.5 KB

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