store.go 8.4 KB

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