store.go 9.2 KB

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