store.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. /*
  2. Copyright (c) 2020 Docker Inc.
  3. Permission is hereby granted, free of charge, to any person
  4. obtaining a copy of this software and associated documentation
  5. files (the "Software"), to deal in the Software without
  6. restriction, including without limitation the rights to use, copy,
  7. modify, merge, publish, distribute, sublicense, and/or sell copies
  8. of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be
  11. included in all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  13. EXPRESS OR IMPLIED,
  14. INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  16. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  17. HOLDERS BE LIABLE FOR ANY CLAIM,
  18. DAMAGES OR OTHER LIABILITY,
  19. WHETHER IN AN ACTION OF CONTRACT,
  20. TORT OR OTHERWISE,
  21. ARISING FROM, OUT OF OR IN CONNECTION WITH
  22. THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. */
  24. package store
  25. import (
  26. "context"
  27. "encoding/json"
  28. "fmt"
  29. "io/ioutil"
  30. "os"
  31. "path/filepath"
  32. "reflect"
  33. "github.com/opencontainers/go-digest"
  34. "github.com/pkg/errors"
  35. "github.com/docker/api/errdefs"
  36. )
  37. const (
  38. // DefaultContextName is an automatically generated local context
  39. DefaultContextName = "default"
  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. const (
  81. // AciContextType is the endpoint key in the context endpoints for an ACI
  82. // backend
  83. AciContextType = "aci"
  84. // MobyContextType is the endpoint key in the context endpoints for a moby
  85. // backend
  86. MobyContextType = "moby"
  87. // ExampleContextType is the endpoint key in the context endpoints for an
  88. // example backend
  89. ExampleContextType = "example"
  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. meta := filepath.Join(s.root, contextsDir, metadataDir, contextDirOf(name), metaFile)
  127. m, err := read(meta)
  128. if os.IsNotExist(err) {
  129. return nil, errors.Wrap(errdefs.ErrNotFound, objectName(name))
  130. } else if err != nil {
  131. return nil, err
  132. }
  133. return m, nil
  134. }
  135. func (s *store) GetEndpoint(name string, data interface{}) error {
  136. meta, err := s.Get(name)
  137. if err != nil {
  138. return err
  139. }
  140. contextType := meta.Type()
  141. if _, ok := meta.Endpoints[contextType]; !ok {
  142. return errors.Wrapf(errdefs.ErrNotFound, "endpoint of type %q", contextType)
  143. }
  144. dstPtrValue := reflect.ValueOf(data)
  145. dstValue := reflect.Indirect(dstPtrValue)
  146. val := reflect.ValueOf(meta.Endpoints[contextType])
  147. valIndirect := reflect.Indirect(val)
  148. if dstValue.Type() != valIndirect.Type() {
  149. return errdefs.ErrWrongContextType
  150. }
  151. dstValue.Set(valIndirect)
  152. return nil
  153. }
  154. func read(meta string) (*DockerContext, error) {
  155. bytes, err := ioutil.ReadFile(meta)
  156. if err != nil {
  157. return nil, err
  158. }
  159. var metadata DockerContext
  160. if err := json.Unmarshal(bytes, &metadata); err != nil {
  161. return nil, err
  162. }
  163. metadata.Endpoints, err = toTypedEndpoints(metadata.Endpoints)
  164. if err != nil {
  165. return nil, err
  166. }
  167. return &metadata, nil
  168. }
  169. func toTypedEndpoints(endpoints map[string]interface{}) (map[string]interface{}, error) {
  170. result := map[string]interface{}{}
  171. for k, v := range endpoints {
  172. bytes, err := json.Marshal(v)
  173. if err != nil {
  174. return nil, err
  175. }
  176. typeGetters := getters()
  177. typeGetter, ok := typeGetters[k]
  178. if !ok {
  179. typeGetter = func() interface{} {
  180. return &Endpoint{}
  181. }
  182. }
  183. val := typeGetter()
  184. err = json.Unmarshal(bytes, &val)
  185. if err != nil {
  186. return nil, err
  187. }
  188. result[k] = val
  189. }
  190. return result, nil
  191. }
  192. func (s *store) Create(name string, contextType string, description string, data interface{}) error {
  193. if name == DefaultContextName {
  194. return errors.Wrap(errdefs.ErrAlreadyExists, objectName(name))
  195. }
  196. dir := contextDirOf(name)
  197. metaDir := filepath.Join(s.root, contextsDir, metadataDir, dir)
  198. if _, err := os.Stat(metaDir); !os.IsNotExist(err) {
  199. return errors.Wrap(errdefs.ErrAlreadyExists, objectName(name))
  200. }
  201. err := os.Mkdir(metaDir, 0755)
  202. if err != nil {
  203. return err
  204. }
  205. meta := DockerContext{
  206. Name: name,
  207. Metadata: ContextMetadata{
  208. Type: contextType,
  209. Description: description,
  210. },
  211. Endpoints: map[string]interface{}{
  212. (dockerEndpointKey): data,
  213. (contextType): data,
  214. },
  215. }
  216. bytes, err := json.Marshal(&meta)
  217. if err != nil {
  218. return err
  219. }
  220. return ioutil.WriteFile(filepath.Join(metaDir, metaFile), bytes, 0644)
  221. }
  222. func (s *store) List() ([]*DockerContext, error) {
  223. root := filepath.Join(s.root, contextsDir, metadataDir)
  224. c, err := ioutil.ReadDir(root)
  225. if err != nil {
  226. return nil, err
  227. }
  228. var result []*DockerContext
  229. for _, fi := range c {
  230. if fi.IsDir() {
  231. meta := filepath.Join(root, fi.Name(), metaFile)
  232. r, err := read(meta)
  233. if err != nil {
  234. return nil, err
  235. }
  236. result = append(result, r)
  237. }
  238. }
  239. // The default context is not stored in the store, it is in-memory only
  240. // so we need a special case for it.
  241. dockerDefault, err := dockerDefaultContext()
  242. if err != nil {
  243. return nil, err
  244. }
  245. result = append(result, dockerDefault)
  246. return result, nil
  247. }
  248. func (s *store) Remove(name string) error {
  249. if name == DefaultContextName {
  250. return errors.Wrap(errdefs.ErrForbidden, objectName(name))
  251. }
  252. dir := filepath.Join(s.root, contextsDir, metadataDir, contextDirOf(name))
  253. // Check if directory exists because os.RemoveAll returns nil if it doesn't
  254. if _, err := os.Stat(dir); os.IsNotExist(err) {
  255. return errors.Wrap(errdefs.ErrNotFound, objectName(name))
  256. }
  257. if err := os.RemoveAll(dir); err != nil {
  258. return errors.Wrapf(errdefs.ErrUnknown, "unable to remove %s: %s", objectName(name), err)
  259. }
  260. return nil
  261. }
  262. func contextDirOf(name string) string {
  263. return digest.FromString(name).Encoded()
  264. }
  265. func objectName(name string) string {
  266. return fmt.Sprintf("context %q", name)
  267. }
  268. func createDirIfNotExist(dir string) error {
  269. if _, err := os.Stat(dir); os.IsNotExist(err) {
  270. if err = os.MkdirAll(dir, 0755); err != nil {
  271. return err
  272. }
  273. }
  274. return nil
  275. }
  276. // Different context types managed by the store.
  277. // TODO(rumpl): we should make this extensible in the future if we want to
  278. // be able to manage other contexts.
  279. func getters() map[string]func() interface{} {
  280. return map[string]func() interface{}{
  281. "aci": func() interface{} {
  282. return &AciContext{}
  283. },
  284. "moby": func() interface{} {
  285. return &MobyContext{}
  286. },
  287. "example": func() interface{} {
  288. return &ExampleContext{}
  289. },
  290. }
  291. }