contextStore.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package docker
  2. import (
  3. "fmt"
  4. "github.com/docker/cli/cli/command"
  5. cliconfig "github.com/docker/cli/cli/config"
  6. "github.com/docker/cli/cli/context/store"
  7. "github.com/mitchellh/mapstructure"
  8. "github.com/spf13/cobra"
  9. )
  10. const contextType = "aws"
  11. type TypeContext struct {
  12. Type string
  13. }
  14. func getter() interface{} {
  15. return &TypeContext{}
  16. }
  17. type AwsContext struct {
  18. Profile string
  19. Cluster string
  20. Region string
  21. }
  22. func NewContext(name string, awsContext *AwsContext) error {
  23. _, err := NewContextWithStore(name, awsContext, cliconfig.ContextStoreDir())
  24. return err
  25. }
  26. func NewContextWithStore(name string, awsContext *AwsContext, contextDirectory string) (store.Store, error) {
  27. contextStore := initContextStore(contextDirectory)
  28. endpoints := map[string]interface{}{
  29. "aws": awsContext,
  30. "docker": awsContext,
  31. }
  32. metadata := store.Metadata{
  33. Name: name,
  34. Endpoints: endpoints,
  35. Metadata: TypeContext{Type: contextType},
  36. }
  37. return contextStore, contextStore.CreateOrUpdate(metadata)
  38. }
  39. func initContextStore(contextDir string) store.Store {
  40. config := store.NewConfig(getter)
  41. return store.New(contextDir, config)
  42. }
  43. func checkAwsContextExists(contextName string) (*AwsContext, error) {
  44. if contextName == command.DefaultContextName {
  45. return nil, fmt.Errorf("can't use \"%s\" with ECS command because it is not an AWS context", contextName)
  46. }
  47. contextStore := initContextStore(cliconfig.ContextStoreDir())
  48. metadata, err := contextStore.GetMetadata(contextName)
  49. if err != nil {
  50. return nil, err
  51. }
  52. endpoint := metadata.Endpoints["aws"]
  53. awsContext := AwsContext{}
  54. err = mapstructure.Decode(endpoint, &awsContext)
  55. if err != nil {
  56. return nil, err
  57. }
  58. if awsContext == (AwsContext{}) {
  59. return nil, fmt.Errorf("can't use \"%s\" with ECS command because it is not an AWS context", contextName)
  60. }
  61. return &awsContext, nil
  62. }
  63. type ContextFunc func(ctx AwsContext, args []string) error
  64. func WithAwsContext(dockerCli command.Cli, f ContextFunc) func(cmd *cobra.Command, args []string) error {
  65. return func(cmd *cobra.Command, args []string) error {
  66. ctx, err := GetAwsContext(dockerCli)
  67. if err != nil {
  68. return err
  69. }
  70. return f(*ctx, args)
  71. }
  72. }
  73. func GetAwsContext(dockerCli command.Cli) (*AwsContext, error) {
  74. contextName := dockerCli.CurrentContext()
  75. return checkAwsContextExists(contextName)
  76. }