store.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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, getter func() interface{}) (*Metadata, error)
  63. // GetType returns the type of the context (docker, aci etc)
  64. GetType(meta *Metadata) string
  65. // Create creates a new context, it returns an error if a context with the
  66. // same name exists already.
  67. Create(name string, data TypedContext) error
  68. // List returns the list of created contexts
  69. List() ([]*Metadata, error)
  70. // Remove removes a context by name from the context store
  71. Remove(name string) error
  72. }
  73. type store struct {
  74. root string
  75. }
  76. // Opt is a functional option for the store
  77. type Opt func(*store)
  78. // WithRoot sets a new root to the store
  79. func WithRoot(root string) Opt {
  80. return func(s *store) {
  81. s.root = root
  82. }
  83. }
  84. // New returns a configured context store with $HOME/.docker as root
  85. func New(opts ...Opt) (Store, error) {
  86. home, err := os.UserHomeDir()
  87. if err != nil {
  88. return nil, err
  89. }
  90. root := filepath.Join(home, configDir)
  91. if err := createDirIfNotExist(root); err != nil {
  92. return nil, err
  93. }
  94. s := &store{
  95. root: root,
  96. }
  97. for _, opt := range opts {
  98. opt(s)
  99. }
  100. m := filepath.Join(s.root, contextsDir, metadataDir)
  101. if err := createDirIfNotExist(m); err != nil {
  102. return nil, err
  103. }
  104. return s, nil
  105. }
  106. // Get returns the context with the given name
  107. func (s *store) Get(name string, getter func() interface{}) (*Metadata, error) {
  108. meta := filepath.Join(s.root, contextsDir, metadataDir, contextDirOf(name), metaFile)
  109. m, err := read(meta, getter)
  110. if os.IsNotExist(err) {
  111. return nil, errors.Wrap(errdefs.ErrNotFound, objectName(name))
  112. } else if err != nil {
  113. return nil, err
  114. }
  115. return m, nil
  116. }
  117. func read(meta string, getter func() interface{}) (*Metadata, error) {
  118. bytes, err := ioutil.ReadFile(meta)
  119. if err != nil {
  120. return nil, err
  121. }
  122. var um untypedMetadata
  123. if err := marshalTyped(bytes, &um); err != nil {
  124. return nil, err
  125. }
  126. var uc untypedContext
  127. if err := marshalTyped(um.Metadata, &uc); err != nil {
  128. return nil, err
  129. }
  130. if uc.Type == "" {
  131. uc.Type = "docker"
  132. }
  133. var data interface{}
  134. if uc.Data != nil {
  135. data, err = parse(uc.Data, getter)
  136. if err != nil {
  137. return nil, err
  138. }
  139. }
  140. return &Metadata{
  141. Name: um.Name,
  142. Endpoints: um.Endpoints,
  143. Metadata: TypedContext{
  144. StackOrchestrator: uc.StackOrchestrator,
  145. Description: uc.Description,
  146. Type: uc.Type,
  147. Data: data,
  148. },
  149. }, nil
  150. }
  151. func marshalTyped(in []byte, val interface{}) error {
  152. return json.Unmarshal(in, val)
  153. }
  154. func parse(payload []byte, getter func() interface{}) (interface{}, error) {
  155. if getter == nil {
  156. var res map[string]interface{}
  157. if err := json.Unmarshal(payload, &res); err != nil {
  158. return nil, err
  159. }
  160. return res, nil
  161. }
  162. typed := getter()
  163. if err := json.Unmarshal(payload, &typed); err != nil {
  164. return nil, err
  165. }
  166. return reflect.ValueOf(typed).Elem().Interface(), nil
  167. }
  168. func (s *store) GetType(meta *Metadata) string {
  169. for k := range meta.Endpoints {
  170. if k != dockerEndpointKey {
  171. return k
  172. }
  173. }
  174. return dockerEndpointKey
  175. }
  176. func (s *store) Create(name string, data TypedContext) error {
  177. if name == DefaultContextName {
  178. return errors.Wrap(errdefs.ErrAlreadyExists, objectName(name))
  179. }
  180. dir := contextDirOf(name)
  181. metaDir := filepath.Join(s.root, contextsDir, metadataDir, dir)
  182. if _, err := os.Stat(metaDir); !os.IsNotExist(err) {
  183. return errors.Wrap(errdefs.ErrAlreadyExists, objectName(name))
  184. }
  185. err := os.Mkdir(metaDir, 0755)
  186. if err != nil {
  187. return err
  188. }
  189. if data.Data == nil {
  190. data.Data = dummyContext{}
  191. }
  192. meta := Metadata{
  193. Name: name,
  194. Metadata: data,
  195. Endpoints: map[string]Endpoint{
  196. (dockerEndpointKey): {},
  197. (data.Type): {},
  198. },
  199. }
  200. bytes, err := json.Marshal(&meta)
  201. if err != nil {
  202. return err
  203. }
  204. return ioutil.WriteFile(filepath.Join(metaDir, metaFile), bytes, 0644)
  205. }
  206. func (s *store) List() ([]*Metadata, error) {
  207. root := filepath.Join(s.root, contextsDir, metadataDir)
  208. c, err := ioutil.ReadDir(root)
  209. if err != nil {
  210. return nil, err
  211. }
  212. var result []*Metadata
  213. for _, fi := range c {
  214. if fi.IsDir() {
  215. meta := filepath.Join(root, fi.Name(), metaFile)
  216. r, err := read(meta, nil)
  217. if err != nil {
  218. return nil, err
  219. }
  220. result = append(result, r)
  221. }
  222. }
  223. dockerDefault, err := dockerGefaultContext()
  224. if err != nil {
  225. return nil, err
  226. }
  227. result = append(result, dockerDefault)
  228. return result, nil
  229. }
  230. func (s *store) Remove(name string) error {
  231. if name == DefaultContextName {
  232. return errors.Wrap(errdefs.ErrForbidden, objectName(name))
  233. }
  234. dir := filepath.Join(s.root, contextsDir, metadataDir, contextDirOf(name))
  235. // Check if directory exists because os.RemoveAll returns nil if it doesn't
  236. if _, err := os.Stat(dir); os.IsNotExist(err) {
  237. return errors.Wrap(errdefs.ErrNotFound, objectName(name))
  238. }
  239. if err := os.RemoveAll(dir); err != nil {
  240. return errors.Wrapf(errdefs.ErrUnknown, "unable to remove %s: %s", objectName(name), err)
  241. }
  242. return nil
  243. }
  244. func contextDirOf(name string) string {
  245. return digest.FromString(name).Encoded()
  246. }
  247. func objectName(name string) string {
  248. return fmt.Sprintf("context %q", name)
  249. }
  250. func createDirIfNotExist(dir string) error {
  251. if _, err := os.Stat(dir); os.IsNotExist(err) {
  252. if err = os.MkdirAll(dir, 0755); err != nil {
  253. return err
  254. }
  255. }
  256. return nil
  257. }
  258. type dummyContext struct{}
  259. // Endpoint holds the Docker or the Kubernetes endpoint
  260. type Endpoint struct {
  261. Host string `json:",omitempty"`
  262. DefaultNamespace string `json:",omitempty"`
  263. }
  264. // Metadata represents the docker context metadata
  265. type Metadata struct {
  266. Name string `json:",omitempty"`
  267. Metadata TypedContext `json:",omitempty"`
  268. Endpoints map[string]Endpoint `json:",omitempty"`
  269. }
  270. type untypedMetadata struct {
  271. Name string `json:",omitempty"`
  272. Metadata json.RawMessage `json:",omitempty"`
  273. Endpoints map[string]Endpoint `json:",omitempty"`
  274. }
  275. type untypedContext struct {
  276. StackOrchestrator string `json:",omitempty"`
  277. Type string `json:",omitempty"`
  278. Description string `json:",omitempty"`
  279. Data json.RawMessage `json:",omitempty"`
  280. }
  281. // TypedContext is a context with a type (moby, aci, etc...)
  282. type TypedContext struct {
  283. StackOrchestrator string `json:",omitempty"`
  284. Type string `json:",omitempty"`
  285. Description string `json:",omitempty"`
  286. Data interface{} `json:",omitempty"`
  287. }
  288. // AciContext is the context for ACI
  289. type AciContext struct {
  290. SubscriptionID string `json:",omitempty"`
  291. Location string `json:",omitempty"`
  292. ResourceGroup string `json:",omitempty"`
  293. }