create.go 7.0 KB

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