store.go 8.5 KB

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