store.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. s := &store{
  91. root: filepath.Join(home, configDir),
  92. }
  93. if _, err := os.Stat(s.root); os.IsNotExist(err) {
  94. if err = os.Mkdir(s.root, 0755); err != nil {
  95. return nil, err
  96. }
  97. }
  98. for _, opt := range opts {
  99. opt(s)
  100. }
  101. cd := filepath.Join(s.root, contextsDir)
  102. if _, err := os.Stat(cd); os.IsNotExist(err) {
  103. if err = os.Mkdir(cd, 0755); err != nil {
  104. return nil, err
  105. }
  106. }
  107. m := filepath.Join(cd, metadataDir)
  108. if _, err := os.Stat(m); os.IsNotExist(err) {
  109. if err = os.Mkdir(m, 0755); err != nil {
  110. return nil, err
  111. }
  112. }
  113. return s, nil
  114. }
  115. // Get returns the context with the given name
  116. func (s *store) Get(name string, getter func() interface{}) (*Metadata, error) {
  117. meta := filepath.Join(s.root, contextsDir, metadataDir, contextdirOf(name), metaFile)
  118. m, err := read(meta, getter)
  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 read(meta string, getter func() interface{}) (*Metadata, error) {
  127. bytes, err := ioutil.ReadFile(meta)
  128. if err != nil {
  129. return nil, err
  130. }
  131. var um untypedMetadata
  132. if err := json.Unmarshal(bytes, &um); err != nil {
  133. return nil, err
  134. }
  135. var uc untypedContext
  136. if err := json.Unmarshal(um.Metadata, &uc); err != nil {
  137. return nil, err
  138. }
  139. data, err := parse(uc.Data, getter)
  140. if err != nil {
  141. return nil, err
  142. }
  143. return &Metadata{
  144. Name: um.Name,
  145. Endpoints: um.Endpoints,
  146. Metadata: TypedContext{
  147. Description: uc.Description,
  148. Type: uc.Type,
  149. Data: data,
  150. },
  151. }, nil
  152. }
  153. func parse(payload []byte, getter func() interface{}) (interface{}, error) {
  154. if getter == nil {
  155. var res map[string]interface{}
  156. if err := json.Unmarshal(payload, &res); err != nil {
  157. return nil, err
  158. }
  159. return res, nil
  160. }
  161. typed := getter()
  162. if err := json.Unmarshal(payload, &typed); err != nil {
  163. return nil, err
  164. }
  165. return reflect.ValueOf(typed).Elem().Interface(), nil
  166. }
  167. func (s *store) GetType(meta *Metadata) string {
  168. for k := range meta.Endpoints {
  169. if k != dockerEndpointKey {
  170. return k
  171. }
  172. }
  173. return dockerEndpointKey
  174. }
  175. func (s *store) Create(name string, data TypedContext) error {
  176. if name == DefaultContextName {
  177. return errors.Wrap(errdefs.ErrAlreadyExists, objectName(name))
  178. }
  179. dir := contextdirOf(name)
  180. metaDir := filepath.Join(s.root, contextsDir, metadataDir, dir)
  181. if _, err := os.Stat(metaDir); !os.IsNotExist(err) {
  182. return errors.Wrap(errdefs.ErrAlreadyExists, objectName(name))
  183. }
  184. err := os.Mkdir(metaDir, 0755)
  185. if err != nil {
  186. return err
  187. }
  188. if data.Data == nil {
  189. data.Data = dummyContext{}
  190. }
  191. meta := Metadata{
  192. Name: name,
  193. Metadata: data,
  194. Endpoints: map[string]interface{}{
  195. (dockerEndpointKey): dummyContext{},
  196. (data.Type): dummyContext{},
  197. },
  198. }
  199. bytes, err := json.Marshal(&meta)
  200. if err != nil {
  201. return err
  202. }
  203. return ioutil.WriteFile(filepath.Join(metaDir, metaFile), bytes, 0644)
  204. }
  205. func (s *store) List() ([]*Metadata, error) {
  206. root := filepath.Join(s.root, contextsDir, metadataDir)
  207. c, err := ioutil.ReadDir(root)
  208. if err != nil {
  209. return nil, err
  210. }
  211. var result []*Metadata
  212. for _, fi := range c {
  213. if fi.IsDir() {
  214. meta := filepath.Join(root, fi.Name(), metaFile)
  215. r, err := read(meta, nil)
  216. if err != nil {
  217. return nil, err
  218. }
  219. result = append(result, r)
  220. }
  221. }
  222. return result, nil
  223. }
  224. func (s *store) Remove(name string) error {
  225. if name == DefaultContextName {
  226. return errors.Wrap(errdefs.ErrForbidden, objectName(name))
  227. }
  228. dir := filepath.Join(s.root, contextsDir, metadataDir, contextdirOf(name))
  229. // Check if directory exists because os.RemoveAll returns nil if it doesn't
  230. if _, err := os.Stat(dir); os.IsNotExist(err) {
  231. return errors.Wrap(errdefs.ErrNotFound, objectName(name))
  232. }
  233. if err := os.RemoveAll(dir); err != nil {
  234. return errors.Wrapf(errdefs.ErrUnknown, "unable to remove %s: %s", objectName(name), err)
  235. }
  236. return nil
  237. }
  238. func contextdirOf(name string) string {
  239. return digest.FromString(name).Encoded()
  240. }
  241. func objectName(name string) string {
  242. return fmt.Sprintf("context %q", name)
  243. }
  244. type dummyContext struct{}
  245. // Metadata represents the docker context metadata
  246. type Metadata struct {
  247. Name string `json:",omitempty"`
  248. Metadata TypedContext `json:",omitempty"`
  249. Endpoints map[string]interface{} `json:",omitempty"`
  250. }
  251. type untypedMetadata struct {
  252. Name string `json:",omitempty"`
  253. Metadata json.RawMessage `json:",omitempty"`
  254. Endpoints map[string]interface{} `json:",omitempty"`
  255. }
  256. type untypedContext struct {
  257. Data json.RawMessage `json:",omitempty"`
  258. Description string `json:",omitempty"`
  259. Type string `json:",omitempty"`
  260. }
  261. // TypedContext is a context with a type (moby, aci, etc...)
  262. type TypedContext struct {
  263. Type string `json:",omitempty"`
  264. Description string `json:",omitempty"`
  265. Data interface{} `json:",omitempty"`
  266. }
  267. // AciContext is the context for ACI
  268. type AciContext struct {
  269. SubscriptionID string `json:",omitempty"`
  270. Location string `json:",omitempty"`
  271. ResourceGroup string `json:",omitempty"`
  272. }