create.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. package cmd
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "path/filepath"
  7. "github.com/fatih/color"
  8. "github.com/porter-dev/porter/cli/cmd/api"
  9. "github.com/porter-dev/porter/cli/cmd/deploy"
  10. "github.com/porter-dev/porter/cli/cmd/gitutils"
  11. "github.com/spf13/cobra"
  12. "sigs.k8s.io/yaml"
  13. )
  14. // createCmd represents the "porter create" base command when called
  15. // without any subcommands
  16. var createCmd = &cobra.Command{
  17. Use: "create [kind]",
  18. Args: cobra.ExactArgs(1),
  19. Short: "Creates a new application with name given by the --app flag.",
  20. Long: fmt.Sprintf(`
  21. %s
  22. Creates a new application with name given by the --app flag and a "kind", which can be one of
  23. web, worker, or job. For example:
  24. %s
  25. To modify the default configuration of the application, you can pass a values.yaml file in via the
  26. --values flag.
  27. %s
  28. To read more about the configuration options, go here:
  29. https://docs.getporter.dev/docs/deploying-from-the-cli#common-configuration-options
  30. This command will automatically build from a local path, and will create a new Docker image in your
  31. default Docker registry. The path can be configured via the --path flag. For example:
  32. %s
  33. To connect the application to Github, so that the application rebuilds and redeploys on each push
  34. to a Github branch, you can specify "--source github". If your local branch is set to track changes
  35. from an upstream remote branch, Porter will try to use the connected remote and remote branch as the
  36. Github repository to link to. Otherwise, Porter will use the remote given by origin. For example:
  37. %s
  38. To deploy an application from a Docker registry, use "--source registry" and pass the image in via the
  39. --image flag. The image flag must be of the form repository:tag. For example:
  40. %s
  41. `,
  42. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter create\":"),
  43. color.New(color.FgGreen, color.Bold).Sprintf("porter create web --app example-app"),
  44. color.New(color.FgGreen, color.Bold).Sprintf("porter create web --app example-app --values values.yaml"),
  45. color.New(color.FgGreen, color.Bold).Sprintf("porter create web --app example-app --path ./path/to/app"),
  46. color.New(color.FgGreen, color.Bold).Sprintf("porter create web --app example-app --source github"),
  47. color.New(color.FgGreen, color.Bold).Sprintf("porter create web --app example-app --source registry --image gcr.io/snowflake-12345/example-app:latest"),
  48. ),
  49. Run: func(cmd *cobra.Command, args []string) {
  50. err := checkLoginAndRun(args, createFull)
  51. if err != nil {
  52. os.Exit(1)
  53. }
  54. },
  55. }
  56. var name string
  57. var values string
  58. var source string
  59. var image string
  60. var registryURL string
  61. func init() {
  62. rootCmd.AddCommand(createCmd)
  63. createCmd.PersistentFlags().StringVar(
  64. &name,
  65. "app",
  66. "",
  67. "name of the new application/job/worker.",
  68. )
  69. createCmd.MarkPersistentFlagRequired("app")
  70. createCmd.PersistentFlags().StringVarP(
  71. &localPath,
  72. "path",
  73. "p",
  74. ".",
  75. "if local build, the path to the build directory",
  76. )
  77. createCmd.PersistentFlags().StringVar(
  78. &namespace,
  79. "namespace",
  80. "default",
  81. "namespace of the application",
  82. )
  83. createCmd.PersistentFlags().StringVarP(
  84. &values,
  85. "values",
  86. "v",
  87. "",
  88. "filepath to a values.yaml file",
  89. )
  90. createCmd.PersistentFlags().StringVar(
  91. &dockerfile,
  92. "dockerfile",
  93. "",
  94. "the path to the dockerfile",
  95. )
  96. createCmd.PersistentFlags().StringVar(
  97. &method,
  98. "method",
  99. "",
  100. "the build method to use (\"docker\" or \"pack\")",
  101. )
  102. createCmd.PersistentFlags().StringVar(
  103. &source,
  104. "source",
  105. "local",
  106. "the type of source (\"local\", \"github\", or \"registry\")",
  107. )
  108. createCmd.PersistentFlags().StringVar(
  109. &image,
  110. "image",
  111. "",
  112. "if the source is \"registry\", the image to use, in repository:tag format",
  113. )
  114. createCmd.PersistentFlags().StringVar(
  115. &registryURL,
  116. "registry-url",
  117. "",
  118. "the registry URL to use (must exist in \"porter registries list\")",
  119. )
  120. }
  121. var supportedKinds = map[string]string{"web": "", "job": "", "worker": ""}
  122. func createFull(resp *api.AuthCheckResponse, client *api.Client, args []string) error {
  123. // check the kind
  124. if _, exists := supportedKinds[args[0]]; !exists {
  125. return fmt.Errorf("%s is not a supported type: specify web, job, or worker", args[0])
  126. }
  127. // read the values if necessary
  128. valuesObj, err := readValuesFile()
  129. if err != nil {
  130. return err
  131. }
  132. color.New(color.FgGreen).Printf("Creating %s release: %s\n", args[0], name)
  133. fullPath, err := filepath.Abs(localPath)
  134. if err != nil {
  135. return err
  136. }
  137. var buildMethod deploy.DeployBuildType
  138. if method != "" {
  139. buildMethod = deploy.DeployBuildType(method)
  140. } else if dockerfile != "" {
  141. buildMethod = deploy.DeployBuildTypeDocker
  142. }
  143. createAgent := &deploy.CreateAgent{
  144. Client: client,
  145. CreateOpts: &deploy.CreateOpts{
  146. SharedOpts: &deploy.SharedOpts{
  147. ProjectID: config.Project,
  148. ClusterID: config.Cluster,
  149. Namespace: namespace,
  150. LocalPath: fullPath,
  151. LocalDockerfile: dockerfile,
  152. Method: buildMethod,
  153. },
  154. Kind: args[0],
  155. ReleaseName: name,
  156. RegistryURL: registryURL,
  157. },
  158. }
  159. if source == "local" {
  160. subdomain, err := createAgent.CreateFromDocker(valuesObj)
  161. return handleSubdomainCreate(subdomain, err)
  162. } else if source == "github" {
  163. return createFromGithub(createAgent, valuesObj)
  164. }
  165. subdomain, err := createAgent.CreateFromRegistry(image, valuesObj)
  166. return handleSubdomainCreate(subdomain, err)
  167. }
  168. func handleSubdomainCreate(subdomain string, err error) error {
  169. if err != nil {
  170. return err
  171. }
  172. if subdomain != "" {
  173. color.New(color.FgGreen).Printf("Your web application is ready at: %s\n", subdomain)
  174. } else {
  175. color.New(color.FgGreen).Printf("Application created successfully\n")
  176. }
  177. return nil
  178. }
  179. func createFromGithub(createAgent *deploy.CreateAgent, overrideValues map[string]interface{}) error {
  180. fullPath, err := filepath.Abs(localPath)
  181. if err != nil {
  182. return err
  183. }
  184. _, err = gitutils.GitDirectory(fullPath)
  185. if err != nil {
  186. return err
  187. }
  188. remote, gitBranch, err := gitutils.GetRemoteBranch(fullPath)
  189. if err != nil {
  190. return err
  191. } else if gitBranch == "" {
  192. return fmt.Errorf("git branch not automatically detectable")
  193. }
  194. ok, remoteRepo := gitutils.ParseGithubRemote(remote)
  195. if !ok {
  196. return fmt.Errorf("remote is not a Github repository")
  197. }
  198. subdomain, err := createAgent.CreateFromGithub(&deploy.GithubOpts{
  199. Branch: gitBranch,
  200. Repo: remoteRepo,
  201. }, overrideValues)
  202. return handleSubdomainCreate(subdomain, err)
  203. }
  204. func readValuesFile() (map[string]interface{}, error) {
  205. res := make(map[string]interface{})
  206. if values == "" {
  207. return res, nil
  208. }
  209. valuesFilePath, err := filepath.Abs(values)
  210. if err != nil {
  211. return nil, err
  212. }
  213. if info, err := os.Stat(valuesFilePath); os.IsNotExist(err) || info.IsDir() {
  214. return nil, fmt.Errorf("values file does not exist or is a directory")
  215. }
  216. reader, err := os.Open(valuesFilePath)
  217. if err != nil {
  218. return nil, err
  219. }
  220. bytes, err := ioutil.ReadAll(reader)
  221. if err != nil {
  222. return nil, err
  223. }
  224. err = yaml.Unmarshal(bytes, &res)
  225. if err != nil {
  226. return nil, err
  227. }
  228. return res, nil
  229. }