config.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/briandowns/spinner"
  12. "github.com/fatih/color"
  13. api "github.com/porter-dev/porter/api/client"
  14. "github.com/porter-dev/porter/api/types"
  15. "github.com/porter-dev/porter/cli/cmd/utils"
  16. "github.com/spf13/cobra"
  17. "github.com/spf13/viper"
  18. flag "github.com/spf13/pflag"
  19. )
  20. // shared sets of flags used by multiple commands
  21. var driverFlagSet = flag.NewFlagSet("driver", flag.ExitOnError)
  22. var defaultFlagSet = flag.NewFlagSet("shared", flag.ExitOnError) // used by all commands
  23. var registryFlagSet = flag.NewFlagSet("registry", flag.ExitOnError)
  24. var helmRepoFlagSet = flag.NewFlagSet("helmrepo", flag.ExitOnError)
  25. // config is a shared object used by all commands
  26. var config = &CLIConfig{}
  27. // CLIConfig is the set of shared configuration options for the CLI commands.
  28. // This config is used by viper: calling Set() function for any parameter will
  29. // update the corresponding field in the viper config file.
  30. type CLIConfig struct {
  31. // Driver can be either "docker" or "local", and represents which driver is
  32. // used to run an instance of the server.
  33. Driver string `yaml:"driver"`
  34. Host string `yaml:"host"`
  35. Project uint `yaml:"project"`
  36. Cluster uint `yaml:"cluster"`
  37. Token string `yaml:"token"`
  38. Registry uint `yaml:"registry"`
  39. HelmRepo uint `yaml:"helm_repo"`
  40. }
  41. // InitAndLoadConfig populates the config object with the following precedence rules:
  42. // 1. flag
  43. // 2. env
  44. // 3. config
  45. // 4. default
  46. //
  47. // It populates the shared config object above
  48. func InitAndLoadConfig() {
  49. initAndLoadConfig(config)
  50. }
  51. func InitAndLoadNewConfig() *CLIConfig {
  52. newConfig := &CLIConfig{}
  53. initAndLoadConfig(newConfig)
  54. return newConfig
  55. }
  56. func initAndLoadConfig(_config *CLIConfig) {
  57. initFlagSet()
  58. // check that the .porter folder exists; create if not
  59. porterDir := filepath.Join(home, ".porter")
  60. if _, err := os.Stat(porterDir); os.IsNotExist(err) {
  61. os.Mkdir(porterDir, 0700)
  62. } else if err != nil {
  63. color.New(color.FgRed).Printf("%v\n", err)
  64. os.Exit(1)
  65. }
  66. viper.SetConfigName("porter")
  67. viper.SetConfigType("yaml")
  68. viper.AddConfigPath(porterDir)
  69. // Bind the flagset initialized above
  70. viper.BindPFlags(driverFlagSet)
  71. viper.BindPFlags(defaultFlagSet)
  72. viper.BindPFlags(registryFlagSet)
  73. viper.BindPFlags(helmRepoFlagSet)
  74. // Bind the environment variables with prefix "PORTER_"
  75. viper.SetEnvPrefix("PORTER")
  76. viper.BindEnv("host")
  77. viper.BindEnv("project")
  78. viper.BindEnv("cluster")
  79. viper.BindEnv("token")
  80. err := viper.ReadInConfig()
  81. if err != nil {
  82. if _, ok := err.(viper.ConfigFileNotFoundError); ok {
  83. // create blank config file
  84. err := ioutil.WriteFile(filepath.Join(home, ".porter", "porter.yaml"), []byte{}, 0644)
  85. if err != nil {
  86. color.New(color.FgRed).Printf("%v\n", err)
  87. os.Exit(1)
  88. }
  89. } else {
  90. // Config file was found but another error was produced
  91. color.New(color.FgRed).Printf("%v\n", err)
  92. os.Exit(1)
  93. }
  94. }
  95. // unmarshal the config into the shared config struct
  96. viper.Unmarshal(_config)
  97. }
  98. // initFlagSet initializes the shared flags used by multiple commands
  99. func initFlagSet() {
  100. driverFlagSet.StringVar(
  101. &config.Driver,
  102. "driver",
  103. "local",
  104. "driver to use (local or docker)",
  105. )
  106. defaultFlagSet.StringVar(
  107. &config.Host,
  108. "host",
  109. "https://dashboard.getporter.dev",
  110. "host URL of Porter instance",
  111. )
  112. defaultFlagSet.UintVar(
  113. &config.Project,
  114. "project",
  115. 0,
  116. "project ID of Porter project",
  117. )
  118. defaultFlagSet.UintVar(
  119. &config.Cluster,
  120. "cluster",
  121. 0,
  122. "cluster ID of Porter cluster",
  123. )
  124. defaultFlagSet.StringVar(
  125. &config.Token,
  126. "token",
  127. "",
  128. "token for Porter authentication",
  129. )
  130. registryFlagSet.UintVar(
  131. &config.Registry,
  132. "registry",
  133. 0,
  134. "registry ID of connected Porter registry",
  135. )
  136. helmRepoFlagSet.UintVar(
  137. &config.HelmRepo,
  138. "helmrepo",
  139. 0,
  140. "helm repo ID of connected Porter Helm repository",
  141. )
  142. }
  143. func (c *CLIConfig) SetDriver(driver string) error {
  144. viper.Set("driver", driver)
  145. color.New(color.FgGreen).Printf("Set the current driver as %s\n", driver)
  146. err := viper.WriteConfig()
  147. if err != nil {
  148. return err
  149. }
  150. config.Driver = driver
  151. return nil
  152. }
  153. func (c *CLIConfig) SetHost(host string) error {
  154. // a trailing / can lead to errors with the api server
  155. host = strings.TrimRight(host, "/")
  156. viper.Set("host", host)
  157. color.New(color.FgGreen).Printf("Set the current host as %s\n", host)
  158. err := viper.WriteConfig()
  159. if err != nil {
  160. return err
  161. }
  162. config.Host = host
  163. return nil
  164. }
  165. func (c *CLIConfig) SetProject(projectID uint) error {
  166. viper.Set("project", projectID)
  167. color.New(color.FgGreen).Printf("Set the current project as %d\n", projectID)
  168. err := viper.WriteConfig()
  169. if err != nil {
  170. return err
  171. }
  172. config.Project = projectID
  173. return nil
  174. }
  175. func (c *CLIConfig) SetCluster(clusterID uint) error {
  176. viper.Set("cluster", clusterID)
  177. color.New(color.FgGreen).Printf("Set the current cluster as %d\n", clusterID)
  178. err := viper.WriteConfig()
  179. if err != nil {
  180. return err
  181. }
  182. config.Cluster = clusterID
  183. return nil
  184. }
  185. func (c *CLIConfig) SetToken(token string) error {
  186. viper.Set("token", token)
  187. err := viper.WriteConfig()
  188. if err != nil {
  189. return err
  190. }
  191. config.Token = token
  192. return nil
  193. }
  194. func (c *CLIConfig) SetRegistry(registryID uint) error {
  195. viper.Set("registry", registryID)
  196. color.New(color.FgGreen).Printf("Set the current registry as %d\n", registryID)
  197. err := viper.WriteConfig()
  198. if err != nil {
  199. return err
  200. }
  201. config.Registry = registryID
  202. return nil
  203. }
  204. func (c *CLIConfig) SetHelmRepo(helmRepoID uint) error {
  205. viper.Set("helm_repo", helmRepoID)
  206. color.New(color.FgGreen).Printf("Set the current Helm repo as %d\n", helmRepoID)
  207. err := viper.WriteConfig()
  208. if err != nil {
  209. return err
  210. }
  211. config.HelmRepo = helmRepoID
  212. return nil
  213. }
  214. var configCmd = &cobra.Command{
  215. Use: "config",
  216. Short: "Commands that control local configuration settings",
  217. Run: func(cmd *cobra.Command, args []string) {
  218. if err := printConfig(); err != nil {
  219. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  220. os.Exit(1)
  221. }
  222. },
  223. }
  224. var configSetProjectCmd = &cobra.Command{
  225. Use: "set-project [id]",
  226. Args: cobra.MaximumNArgs(1),
  227. Short: "Saves the project id in the default configuration",
  228. Run: func(cmd *cobra.Command, args []string) {
  229. if len(args) == 0 {
  230. err := checkLoginAndRun(args, listAndSetProject)
  231. if err != nil {
  232. os.Exit(1)
  233. }
  234. } else {
  235. projID, err := strconv.ParseUint(args[0], 10, 64)
  236. if err != nil {
  237. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  238. os.Exit(1)
  239. }
  240. err = config.SetProject(uint(projID))
  241. if err != nil {
  242. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  243. os.Exit(1)
  244. }
  245. }
  246. },
  247. }
  248. var configSetClusterCmd = &cobra.Command{
  249. Use: "set-cluster [id]",
  250. Args: cobra.MaximumNArgs(1),
  251. Short: "Saves the cluster id in the default configuration",
  252. Run: func(cmd *cobra.Command, args []string) {
  253. if len(args) == 0 {
  254. err := checkLoginAndRun(args, listAndSetCluster)
  255. if err != nil {
  256. os.Exit(1)
  257. }
  258. } else {
  259. clusterID, err := strconv.ParseUint(args[0], 10, 64)
  260. if err != nil {
  261. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  262. os.Exit(1)
  263. }
  264. err = config.SetCluster(uint(clusterID))
  265. if err != nil {
  266. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  267. os.Exit(1)
  268. }
  269. }
  270. },
  271. }
  272. var configSetRegistryCmd = &cobra.Command{
  273. Use: "set-registry [id]",
  274. Args: cobra.MaximumNArgs(1),
  275. Short: "Saves the registry id in the default configuration",
  276. Run: func(cmd *cobra.Command, args []string) {
  277. if len(args) == 0 {
  278. err := checkLoginAndRun(args, listAndSetRegistry)
  279. if err != nil {
  280. os.Exit(1)
  281. }
  282. } else {
  283. registryID, err := strconv.ParseUint(args[0], 10, 64)
  284. if err != nil {
  285. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  286. os.Exit(1)
  287. }
  288. err = config.SetRegistry(uint(registryID))
  289. if err != nil {
  290. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  291. os.Exit(1)
  292. }
  293. }
  294. },
  295. }
  296. var configSetHelmRepoCmd = &cobra.Command{
  297. Use: "set-helmrepo [id]",
  298. Args: cobra.ExactArgs(1),
  299. Short: "Saves the helm repo id in the default configuration",
  300. Run: func(cmd *cobra.Command, args []string) {
  301. hrID, err := strconv.ParseUint(args[0], 10, 64)
  302. if err != nil {
  303. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  304. os.Exit(1)
  305. }
  306. err = config.SetHelmRepo(uint(hrID))
  307. if err != nil {
  308. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  309. os.Exit(1)
  310. }
  311. },
  312. }
  313. var configSetHostCmd = &cobra.Command{
  314. Use: "set-host [host]",
  315. Args: cobra.ExactArgs(1),
  316. Short: "Saves the host in the default configuration",
  317. Run: func(cmd *cobra.Command, args []string) {
  318. err := config.SetHost(args[0])
  319. if err != nil {
  320. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  321. os.Exit(1)
  322. }
  323. },
  324. }
  325. func init() {
  326. rootCmd.AddCommand(configCmd)
  327. configCmd.AddCommand(configSetProjectCmd)
  328. configCmd.AddCommand(configSetClusterCmd)
  329. configCmd.AddCommand(configSetHostCmd)
  330. configCmd.AddCommand(configSetRegistryCmd)
  331. configCmd.AddCommand(configSetHelmRepoCmd)
  332. }
  333. func printConfig() error {
  334. config, err := ioutil.ReadFile(filepath.Join(home, ".porter", "porter.yaml"))
  335. if err != nil {
  336. return err
  337. }
  338. fmt.Println(string(config))
  339. return nil
  340. }
  341. func listAndSetProject(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  342. s := spinner.New(spinner.CharSets[9], 100*time.Millisecond)
  343. s.Color("cyan")
  344. s.Suffix = " Loading list of projects"
  345. s.Start()
  346. resp, err := client.ListUserProjects(context.Background())
  347. s.Stop()
  348. if err != nil {
  349. return err
  350. }
  351. var projID uint64
  352. if len(*resp) > 1 {
  353. // only give the option to select when more than one option exists
  354. projName, err := utils.PromptSelect("Select a project with ID", func() []string {
  355. var names []string
  356. for _, proj := range *resp {
  357. names = append(names, fmt.Sprintf("%s - %d", proj.Name, proj.ID))
  358. }
  359. return names
  360. }())
  361. if err != nil {
  362. return err
  363. }
  364. projID, _ = strconv.ParseUint(strings.Split(projName, " - ")[1], 10, 64)
  365. } else {
  366. projID = uint64((*resp)[0].ID)
  367. }
  368. config.SetProject(uint(projID))
  369. return nil
  370. }
  371. func listAndSetCluster(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  372. s := spinner.New(spinner.CharSets[9], 100*time.Millisecond)
  373. s.Color("cyan")
  374. s.Suffix = " Loading list of clusters"
  375. s.Start()
  376. resp, err := client.ListProjectClusters(context.Background(), config.Project)
  377. s.Stop()
  378. if err != nil {
  379. return err
  380. }
  381. var clusterID uint64
  382. if len(*resp) > 1 {
  383. clusterName, err := utils.PromptSelect("Select a cluster with ID", func() []string {
  384. var names []string
  385. for _, cluster := range *resp {
  386. names = append(names, fmt.Sprintf("%s - %d", cluster.Name, cluster.ID))
  387. }
  388. return names
  389. }())
  390. if err != nil {
  391. return err
  392. }
  393. clusterID, _ = strconv.ParseUint(strings.Split(clusterName, " - ")[1], 10, 64)
  394. } else {
  395. clusterID = uint64((*resp)[0].ID)
  396. }
  397. config.SetCluster(uint(clusterID))
  398. return nil
  399. }
  400. func listAndSetRegistry(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  401. s := spinner.New(spinner.CharSets[9], 100*time.Millisecond)
  402. s.Color("cyan")
  403. s.Suffix = " Loading list of registries"
  404. s.Start()
  405. resp, err := client.ListRegistries(context.Background(), config.Project)
  406. s.Stop()
  407. if err != nil {
  408. return err
  409. }
  410. var regID uint64
  411. if len(*resp) > 1 {
  412. regName, err := utils.PromptSelect("Select a registry with ID", func() []string {
  413. var names []string
  414. for _, cluster := range *resp {
  415. names = append(names, fmt.Sprintf("%s - %d", cluster.Name, cluster.ID))
  416. }
  417. return names
  418. }())
  419. if err != nil {
  420. return err
  421. }
  422. regID, _ = strconv.ParseUint(strings.Split(regName, " - ")[1], 10, 64)
  423. } else {
  424. regID = uint64((*resp)[0].ID)
  425. }
  426. config.SetRegistry(uint(regID))
  427. return nil
  428. }