2
0

config.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. package config
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "github.com/fatih/color"
  11. api "github.com/porter-dev/porter/api/client"
  12. "github.com/porter-dev/porter/cli/cmd/utils"
  13. "github.com/spf13/viper"
  14. "k8s.io/client-go/util/homedir"
  15. )
  16. var home = homedir.HomeDir()
  17. // config is a shared object used by all commands
  18. var config = &CLIConfig{}
  19. // CLIConfig is the set of shared configuration options for the CLI commands.
  20. // This config is used by viper: calling Set() function for any parameter will
  21. // update the corresponding field in the viper config file.
  22. type CLIConfig struct {
  23. // Driver can be either "docker" or "local", and represents which driver is
  24. // used to run an instance of the server.
  25. Driver string `yaml:"driver"`
  26. Host string `yaml:"host"`
  27. Project uint `yaml:"project"`
  28. Cluster uint `yaml:"cluster"`
  29. Token string `yaml:"token"`
  30. Registry uint `yaml:"registry"`
  31. HelmRepo uint `yaml:"helm_repo"`
  32. Kubeconfig string `yaml:"kubeconfig"`
  33. }
  34. // InitAndLoadConfig populates the config object with the following precedence rules:
  35. // 1. flag
  36. // 2. env
  37. // 3. config
  38. // 4. default
  39. //
  40. // It populates the shared config object above
  41. func InitAndLoadConfig() {
  42. initAndLoadConfig(config)
  43. }
  44. func InitAndLoadNewConfig() *CLIConfig {
  45. newConfig := &CLIConfig{}
  46. initAndLoadConfig(newConfig)
  47. return newConfig
  48. }
  49. func initAndLoadConfig(_config *CLIConfig) {
  50. initFlagSet()
  51. // check that the .porter folder exists; create if not
  52. porterDir := filepath.Join(home, ".porter")
  53. if _, err := os.Stat(porterDir); os.IsNotExist(err) {
  54. os.Mkdir(porterDir, 0o700)
  55. } else if err != nil {
  56. color.New(color.FgRed).Fprintf(os.Stderr, "%v\n", err)
  57. os.Exit(1)
  58. }
  59. viper.SetConfigName("porter")
  60. viper.SetConfigType("yaml")
  61. viper.AddConfigPath(porterDir)
  62. // Bind the flagset initialized above
  63. viper.BindPFlags(utils.DriverFlagSet)
  64. viper.BindPFlags(utils.DefaultFlagSet)
  65. viper.BindPFlags(utils.RegistryFlagSet)
  66. viper.BindPFlags(utils.HelmRepoFlagSet)
  67. // Bind the environment variables with prefix "PORTER_"
  68. viper.SetEnvPrefix("PORTER")
  69. viper.BindEnv("host")
  70. viper.BindEnv("project")
  71. viper.BindEnv("cluster")
  72. viper.BindEnv("token")
  73. err := viper.ReadInConfig()
  74. if err != nil {
  75. if _, ok := err.(viper.ConfigFileNotFoundError); ok {
  76. // create blank config file
  77. err := ioutil.WriteFile(filepath.Join(home, ".porter", "porter.yaml"), []byte{}, 0o644)
  78. if err != nil {
  79. color.New(color.FgRed).Fprintf(os.Stderr, "%v\n", err)
  80. os.Exit(1)
  81. }
  82. } else {
  83. // Config file was found but another error was produced
  84. color.New(color.FgRed).Fprintf(os.Stderr, "%v\n", err)
  85. os.Exit(1)
  86. }
  87. }
  88. // unmarshal the config into the shared config struct
  89. viper.Unmarshal(_config)
  90. }
  91. // initFlagSet initializes the shared flags used by multiple commands
  92. func initFlagSet() {
  93. utils.DriverFlagSet.StringVar(
  94. &config.Driver,
  95. "driver",
  96. "local",
  97. "driver to use (local or docker)",
  98. )
  99. utils.DefaultFlagSet.StringVar(
  100. &config.Host,
  101. "host",
  102. "https://dashboard.getporter.dev",
  103. "host URL of Porter instance",
  104. )
  105. utils.DefaultFlagSet.UintVar(
  106. &config.Project,
  107. "project",
  108. 0,
  109. "project ID of Porter project",
  110. )
  111. utils.DefaultFlagSet.UintVar(
  112. &config.Cluster,
  113. "cluster",
  114. 0,
  115. "cluster ID of Porter cluster",
  116. )
  117. utils.DefaultFlagSet.StringVar(
  118. &config.Token,
  119. "token",
  120. "",
  121. "token for Porter authentication",
  122. )
  123. utils.RegistryFlagSet.UintVar(
  124. &config.Registry,
  125. "registry",
  126. 0,
  127. "registry ID of connected Porter registry",
  128. )
  129. utils.HelmRepoFlagSet.UintVar(
  130. &config.HelmRepo,
  131. "helmrepo",
  132. 0,
  133. "helm repo ID of connected Porter Helm repository",
  134. )
  135. }
  136. func GetCLIConfig() *CLIConfig {
  137. if config == nil {
  138. panic("GetCLIConfig() called before initialisation")
  139. }
  140. return config
  141. }
  142. func GetAPIClient() *api.Client {
  143. config := GetCLIConfig()
  144. if token := config.Token; token != "" {
  145. return api.NewClientWithToken(config.Host+"/api", token)
  146. }
  147. return api.NewClient(config.Host+"/api", "cookie.json")
  148. }
  149. func (c *CLIConfig) SetDriver(driver string) error {
  150. viper.Set("driver", driver)
  151. color.New(color.FgGreen).Printf("Set the current driver as %s\n", driver)
  152. err := viper.WriteConfig()
  153. if err != nil {
  154. return err
  155. }
  156. config.Driver = driver
  157. return nil
  158. }
  159. func (c *CLIConfig) SetHost(host string) error {
  160. // a trailing / can lead to errors with the api server
  161. host = strings.TrimRight(host, "/")
  162. viper.Set("host", host)
  163. // let us clear the project ID, cluster ID, and token when we reset a host
  164. viper.Set("project", 0)
  165. viper.Set("cluster", 0)
  166. viper.Set("token", "")
  167. err := viper.WriteConfig()
  168. if err != nil {
  169. return err
  170. }
  171. color.New(color.FgGreen).Printf("Set the current host as %s\n", host)
  172. config.Host = host
  173. config.Project = 0
  174. config.Cluster = 0
  175. config.Token = ""
  176. return nil
  177. }
  178. func (c *CLIConfig) SetProject(projectID uint) error {
  179. viper.Set("project", projectID)
  180. color.New(color.FgGreen).Printf("Set the current project as %d\n", projectID)
  181. if config.Kubeconfig != "" || viper.IsSet("kubeconfig") {
  182. color.New(color.FgYellow).Println("Please change local kubeconfig if needed")
  183. }
  184. err := viper.WriteConfig()
  185. if err != nil {
  186. return err
  187. }
  188. config.Project = projectID
  189. client := GetAPIClient()
  190. if client != nil {
  191. resp, err := client.ListProjectClusters(context.Background(), projectID)
  192. if err == nil {
  193. clusters := *resp
  194. if len(clusters) == 1 {
  195. c.SetCluster(clusters[0].ID)
  196. }
  197. }
  198. }
  199. return nil
  200. }
  201. func (c *CLIConfig) SetCluster(clusterID uint) error {
  202. viper.Set("cluster", clusterID)
  203. color.New(color.FgGreen).Printf("Set the current cluster as %d\n", clusterID)
  204. if config.Kubeconfig != "" || viper.IsSet("kubeconfig") {
  205. color.New(color.FgYellow).Println("Please change local kubeconfig if needed")
  206. }
  207. err := viper.WriteConfig()
  208. if err != nil {
  209. return err
  210. }
  211. config.Cluster = clusterID
  212. return nil
  213. }
  214. func (c *CLIConfig) SetToken(token string) error {
  215. viper.Set("token", token)
  216. err := viper.WriteConfig()
  217. if err != nil {
  218. return err
  219. }
  220. config.Token = token
  221. return nil
  222. }
  223. func (c *CLIConfig) SetRegistry(registryID uint) error {
  224. viper.Set("registry", registryID)
  225. color.New(color.FgGreen).Printf("Set the current registry as %d\n", registryID)
  226. err := viper.WriteConfig()
  227. if err != nil {
  228. return err
  229. }
  230. config.Registry = registryID
  231. return nil
  232. }
  233. func (c *CLIConfig) SetHelmRepo(helmRepoID uint) error {
  234. viper.Set("helm_repo", helmRepoID)
  235. color.New(color.FgGreen).Printf("Set the current Helm repo as %d\n", helmRepoID)
  236. err := viper.WriteConfig()
  237. if err != nil {
  238. return err
  239. }
  240. config.HelmRepo = helmRepoID
  241. return nil
  242. }
  243. func (c *CLIConfig) SetKubeconfig(kubeconfig string) error {
  244. path, err := filepath.Abs(kubeconfig)
  245. if err != nil {
  246. return err
  247. }
  248. if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
  249. return fmt.Errorf("%s does not exist", path)
  250. }
  251. viper.Set("kubeconfig", path)
  252. color.New(color.FgGreen).Printf("Set the path to kubeconfig as %s\n", path)
  253. err = viper.WriteConfig()
  254. if err != nil {
  255. return err
  256. }
  257. config.Kubeconfig = kubeconfig
  258. return nil
  259. }
  260. func ValidateCLIEnvironment() error {
  261. if GetCLIConfig().Token == "" {
  262. return fmt.Errorf("no auth token present, please run 'porter auth login' to authenticate")
  263. }
  264. if GetCLIConfig().Project == 0 {
  265. return fmt.Errorf("no project selected, please run 'porter config set-project' to select a project")
  266. }
  267. if GetCLIConfig().Cluster == 0 {
  268. return fmt.Errorf("no cluster selected, please run 'porter config set-cluster' to select a cluster")
  269. }
  270. return nil
  271. }