2
0

config.go 8.1 KB

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