store.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. // AciContextType is the endpoint key in the context endpoints for an ACI
  32. // backend
  33. AciContextType = "aci"
  34. // LocalContextType is the endpoint key in the context endpoints for a new
  35. // local backend
  36. LocalContextType = "local"
  37. // ExampleContextType is the endpoint key in the context endpoints for an
  38. // example backend
  39. ExampleContextType = "example"
  40. )
  41. const (
  42. dockerEndpointKey = "docker"
  43. configDir = ".docker"
  44. contextsDir = "contexts"
  45. metadataDir = "meta"
  46. metaFile = "meta.json"
  47. )
  48. type contextStoreKey struct{}
  49. // WithContextStore adds the store to the context
  50. func WithContextStore(ctx context.Context, store Store) context.Context {
  51. return context.WithValue(ctx, contextStoreKey{}, store)
  52. }
  53. // ContextStore returns the store from the context
  54. func ContextStore(ctx context.Context) Store {
  55. s, _ := ctx.Value(contextStoreKey{}).(Store)
  56. return s
  57. }
  58. // Store is the context store
  59. type Store interface {
  60. // Get returns the context with name, it returns an error if the context
  61. // doesn't exist
  62. Get(name string) (*DockerContext, error)
  63. // GetEndpoint sets the `v` parameter to the value of the endpoint for a
  64. // particular context type
  65. GetEndpoint(name string, v interface{}) error
  66. // Create creates a new context, it returns an error if a context with the
  67. // same name exists already.
  68. Create(name string, contextType string, description string, data interface{}) error
  69. // List returns the list of created contexts
  70. List() ([]*DockerContext, error)
  71. // Remove removes a context by name from the context store
  72. Remove(name string) error
  73. }
  74. // Endpoint holds the Docker or the Kubernetes endpoint, they both have the
  75. // `Host` property, only kubernetes will have the `DefaultNamespace`
  76. type Endpoint struct {
  77. Host string `json:",omitempty"`
  78. DefaultNamespace string `json:",omitempty"`
  79. }
  80. type store struct {
  81. root string
  82. }
  83. // Opt is a functional option for the store
  84. type Opt func(*store)
  85. // WithRoot sets a new root to the store
  86. func WithRoot(root string) Opt {
  87. return func(s *store) {
  88. s.root = root
  89. }
  90. }
  91. // New returns a configured context store with $HOME/.docker as root
  92. func New(opts ...Opt) (Store, error) {
  93. home, err := os.UserHomeDir()
  94. if err != nil {
  95. return nil, err
  96. }
  97. root := filepath.Join(home, configDir)
  98. if err := createDirIfNotExist(root); err != nil {
  99. return nil, err
  100. }
  101. s := &store{
  102. root: root,
  103. }
  104. for _, opt := range opts {
  105. opt(s)
  106. }
  107. m := filepath.Join(s.root, contextsDir, metadataDir)
  108. if err := createDirIfNotExist(m); err != nil {
  109. return nil, err
  110. }
  111. return s, nil
  112. }
  113. // Get returns the context with the given name
  114. func (s *store) Get(name string) (*DockerContext, error) {
  115. meta := filepath.Join(s.root, contextsDir, metadataDir, contextDirOf(name), metaFile)
  116. m, err := read(meta)
  117. if os.IsNotExist(err) {
  118. return nil, errors.Wrap(errdefs.ErrNotFound, objectName(name))
  119. } else if err != nil {
  120. return nil, err
  121. }
  122. return m, nil
  123. }
  124. func (s *store) GetEndpoint(name string, data interface{}) error {
  125. meta, err := s.Get(name)
  126. if err != nil {
  127. return err
  128. }
  129. contextType := meta.Type()
  130. if _, ok := meta.Endpoints[contextType]; !ok {
  131. return errors.Wrapf(errdefs.ErrNotFound, "endpoint of type %q", contextType)
  132. }
  133. dstPtrValue := reflect.ValueOf(data)
  134. dstValue := reflect.Indirect(dstPtrValue)
  135. val := reflect.ValueOf(meta.Endpoints[contextType])
  136. valIndirect := reflect.Indirect(val)
  137. if dstValue.Type() != valIndirect.Type() {
  138. return errdefs.ErrWrongContextType
  139. }
  140. dstValue.Set(valIndirect)
  141. return nil
  142. }
  143. func read(meta string) (*DockerContext, error) {
  144. bytes, err := ioutil.ReadFile(meta)
  145. if err != nil {
  146. return nil, err
  147. }
  148. var metadata DockerContext
  149. if err := json.Unmarshal(bytes, &metadata); err != nil {
  150. return nil, err
  151. }
  152. metadata.Endpoints, err = toTypedEndpoints(metadata.Endpoints)
  153. if err != nil {
  154. return nil, err
  155. }
  156. return &metadata, nil
  157. }
  158. func toTypedEndpoints(endpoints map[string]interface{}) (map[string]interface{}, error) {
  159. result := map[string]interface{}{}
  160. for k, v := range endpoints {
  161. bytes, err := json.Marshal(v)
  162. if err != nil {
  163. return nil, err
  164. }
  165. typeGetters := getters()
  166. typeGetter, ok := typeGetters[k]
  167. if !ok {
  168. typeGetter = func() interface{} {
  169. return &Endpoint{}
  170. }
  171. }
  172. val := typeGetter()
  173. err = json.Unmarshal(bytes, &val)
  174. if err != nil {
  175. return nil, err
  176. }
  177. result[k] = val
  178. }
  179. return result, nil
  180. }
  181. func (s *store) Create(name string, contextType string, description string, data interface{}) error {
  182. if name == DefaultContextName {
  183. return errors.Wrap(errdefs.ErrAlreadyExists, objectName(name))
  184. }
  185. dir := contextDirOf(name)
  186. metaDir := filepath.Join(s.root, contextsDir, metadataDir, dir)
  187. if _, err := os.Stat(metaDir); !os.IsNotExist(err) {
  188. return errors.Wrap(errdefs.ErrAlreadyExists, objectName(name))
  189. }
  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. "aci": func() interface{} {
  271. return &AciContext{}
  272. },
  273. "local": func() interface{} {
  274. return &LocalContext{}
  275. },
  276. "example": func() interface{} {
  277. return &ExampleContext{}
  278. },
  279. }
  280. }