create.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. v2 "github.com/porter-dev/porter/cli/cmd/v2"
  10. "github.com/fatih/color"
  11. api "github.com/porter-dev/porter/api/client"
  12. "github.com/porter-dev/porter/api/types"
  13. "github.com/porter-dev/porter/cli/cmd/config"
  14. "github.com/porter-dev/porter/cli/cmd/deploy"
  15. "github.com/porter-dev/porter/cli/cmd/gitutils"
  16. "github.com/porter-dev/porter/cli/cmd/utils"
  17. "github.com/spf13/cobra"
  18. "k8s.io/client-go/util/homedir"
  19. "sigs.k8s.io/yaml"
  20. )
  21. // createCmd represents the "porter create" base command when called
  22. // without any subcommands
  23. var createCmd = &cobra.Command{
  24. Use: "create [kind]",
  25. Args: cobra.ExactArgs(1),
  26. Short: "Creates a new application with name given by the --app flag.",
  27. Long: fmt.Sprintf(`
  28. %s
  29. Creates a new application with name given by the --app flag and a "kind", which can be one of
  30. web, worker, or job. For example:
  31. %s
  32. To modify the default configuration of the application, you can pass a values.yaml file in via the
  33. --values flag.
  34. %s
  35. To read more about the configuration options, go here:
  36. https://docs.getporter.dev/docs/deploying-from-the-cli#common-configuration-options
  37. This command will automatically build from a local path, and will create a new Docker image in your
  38. default Docker registry. The path can be configured via the --path flag. For example:
  39. %s
  40. To connect the application to Github, so that the application rebuilds and redeploys on each push
  41. to a Github branch, you can specify "--source github". If your local branch is set to track changes
  42. from an upstream remote branch, Porter will try to use the connected remote and remote branch as the
  43. Github repository to link to. Otherwise, Porter will use the remote given by origin. For example:
  44. %s
  45. To deploy an application from a Docker registry, use "--source registry" and pass the image in via the
  46. --image flag. The image flag must be of the form repository:tag. For example:
  47. %s
  48. `,
  49. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter create\":"),
  50. color.New(color.FgGreen, color.Bold).Sprintf("porter create web --app example-app"),
  51. color.New(color.FgGreen, color.Bold).Sprintf("porter create web --app example-app --values values.yaml"),
  52. color.New(color.FgGreen, color.Bold).Sprintf("porter create web --app example-app --path ./path/to/app"),
  53. color.New(color.FgGreen, color.Bold).Sprintf("porter create web --app example-app --source github"),
  54. color.New(color.FgGreen, color.Bold).Sprintf("porter create web --app example-app --source registry --image gcr.io/snowflake-12345/example-app:latest"),
  55. ),
  56. Run: func(cmd *cobra.Command, args []string) {
  57. err := checkLoginAndRun(cmd.Context(), args, createFull)
  58. if err != nil {
  59. os.Exit(1)
  60. }
  61. },
  62. }
  63. var (
  64. name string
  65. values string
  66. source string
  67. image string
  68. registryURL string
  69. forceBuild bool
  70. )
  71. func init() {
  72. rootCmd.AddCommand(createCmd)
  73. createCmd.PersistentFlags().StringVar(
  74. &name,
  75. "app",
  76. "",
  77. "name of the new application/job/worker.",
  78. )
  79. createCmd.MarkPersistentFlagRequired("app")
  80. createCmd.PersistentFlags().StringVarP(
  81. &localPath,
  82. "path",
  83. "p",
  84. "",
  85. "if local build, the path to the build directory",
  86. )
  87. createCmd.PersistentFlags().StringVar(
  88. &namespace,
  89. "namespace",
  90. "default",
  91. "namespace of the application",
  92. )
  93. createCmd.PersistentFlags().StringVarP(
  94. &values,
  95. "values",
  96. "v",
  97. "",
  98. "filepath to a values.yaml file",
  99. )
  100. createCmd.PersistentFlags().StringVar(
  101. &dockerfile,
  102. "dockerfile",
  103. "",
  104. "the path to the dockerfile",
  105. )
  106. createCmd.PersistentFlags().StringArrayVarP(
  107. &buildFlagsEnv,
  108. "env",
  109. "e",
  110. []string{},
  111. "Build-time environment variable, in the form 'VAR=VALUE'. These are not available at image runtime.",
  112. )
  113. createCmd.PersistentFlags().StringVar(
  114. &method,
  115. "method",
  116. "",
  117. "the build method to use (\"docker\" or \"pack\")",
  118. )
  119. createCmd.PersistentFlags().StringVar(
  120. &source,
  121. "source",
  122. "local",
  123. "the type of source (\"local\", \"github\", or \"registry\")",
  124. )
  125. createCmd.PersistentFlags().StringVar(
  126. &image,
  127. "image",
  128. "",
  129. "if the source is \"registry\", the image to use, in repository:tag format",
  130. )
  131. createCmd.PersistentFlags().StringVar(
  132. &registryURL,
  133. "registry-url",
  134. "",
  135. "the registry URL to use (must exist in \"porter registries list\")",
  136. )
  137. createCmd.PersistentFlags().BoolVar(
  138. &forceBuild,
  139. "force-build",
  140. false,
  141. "set this to force build an image",
  142. )
  143. createCmd.PersistentFlags().BoolVar(
  144. &useCache,
  145. "use-cache",
  146. false,
  147. "Whether to use cache (currently in beta)",
  148. )
  149. createCmd.PersistentFlags().MarkDeprecated("force-build", "--force-build is deprecated")
  150. }
  151. var supportedKinds = map[string]string{"web": "", "job": "", "worker": ""}
  152. func createFull(ctx context.Context, _ *types.GetAuthenticatedUserResponse, client api.Client, cliConf config.CLIConfig, args []string) error {
  153. project, err := client.GetProject(ctx, cliConf.Project)
  154. if err != nil {
  155. return fmt.Errorf("could not retrieve project from Porter API. Please contact support@porter.run")
  156. }
  157. if project.ValidateApplyV2 {
  158. err = v2.CreateFull(ctx)
  159. if err != nil {
  160. return err
  161. }
  162. return nil
  163. }
  164. // check the kind
  165. if _, exists := supportedKinds[args[0]]; !exists {
  166. return fmt.Errorf("%s is not a supported type: specify web, job, or worker", args[0])
  167. }
  168. fullPath, err := filepath.Abs(localPath)
  169. if err != nil {
  170. return err
  171. }
  172. if os.Getenv("GITHUB_ACTIONS") == "" && source == "local" && fullPath == homedir.HomeDir() {
  173. proceed, err := utils.PromptConfirm("You are deploying your home directory. Do you want to continue?", false)
  174. if err != nil {
  175. return err
  176. }
  177. if !proceed {
  178. return nil
  179. }
  180. }
  181. // read the values if necessary
  182. valuesObj, err := readValuesFile()
  183. if err != nil {
  184. return err
  185. }
  186. color.New(color.FgGreen).Printf("Creating %s release: %s\n", args[0], name)
  187. var buildMethod deploy.DeployBuildType
  188. if method != "" {
  189. buildMethod = deploy.DeployBuildType(method)
  190. } else if dockerfile != "" {
  191. buildMethod = deploy.DeployBuildTypeDocker
  192. }
  193. // add additional env, if they exist
  194. additionalEnv := make(map[string]string)
  195. for _, buildEnv := range buildFlagsEnv {
  196. if strSplArr := strings.SplitN(buildEnv, "=", 2); len(strSplArr) >= 2 {
  197. additionalEnv[strSplArr[0]] = strSplArr[1]
  198. }
  199. }
  200. createAgent := &deploy.CreateAgent{
  201. Client: client,
  202. CreateOpts: &deploy.CreateOpts{
  203. SharedOpts: &deploy.SharedOpts{
  204. ProjectID: cliConf.Project,
  205. ClusterID: cliConf.Cluster,
  206. Namespace: namespace,
  207. LocalPath: fullPath,
  208. LocalDockerfile: dockerfile,
  209. Method: buildMethod,
  210. AdditionalEnv: additionalEnv,
  211. UseCache: useCache,
  212. },
  213. Kind: args[0],
  214. ReleaseName: name,
  215. RegistryURL: registryURL,
  216. },
  217. }
  218. if source == "local" {
  219. if useCache {
  220. regID, imageURL, err := createAgent.GetImageRepoURL(ctx, name, namespace)
  221. if err != nil {
  222. return err
  223. }
  224. err = client.CreateRepository(
  225. ctx,
  226. cliConf.Project,
  227. regID,
  228. &types.CreateRegistryRepositoryRequest{
  229. ImageRepoURI: imageURL,
  230. },
  231. )
  232. if err != nil {
  233. return err
  234. }
  235. err = config.SetDockerConfig(ctx, createAgent.Client, project.ID)
  236. if err != nil {
  237. return err
  238. }
  239. }
  240. subdomain, err := createAgent.CreateFromDocker(ctx, valuesObj, "default", nil)
  241. return handleSubdomainCreate(subdomain, err)
  242. } else if source == "github" {
  243. return createFromGithub(ctx, createAgent, valuesObj)
  244. }
  245. subdomain, err := createAgent.CreateFromRegistry(ctx, image, valuesObj)
  246. return handleSubdomainCreate(subdomain, err)
  247. }
  248. func handleSubdomainCreate(subdomain string, err error) error {
  249. if err != nil {
  250. return err
  251. }
  252. if subdomain != "" {
  253. color.New(color.FgGreen).Printf("Your web application is ready at: %s\n", subdomain)
  254. } else {
  255. color.New(color.FgGreen).Printf("Application created successfully\n")
  256. }
  257. return nil
  258. }
  259. func createFromGithub(ctx context.Context, createAgent *deploy.CreateAgent, overrideValues map[string]interface{}) error {
  260. fullPath, err := filepath.Abs(localPath)
  261. if err != nil {
  262. return err
  263. }
  264. _, err = gitutils.GitDirectory(fullPath)
  265. if err != nil {
  266. return err
  267. }
  268. remote, gitBranch, err := gitutils.GetRemoteBranch(fullPath)
  269. if err != nil {
  270. return err
  271. } else if gitBranch == "" {
  272. return fmt.Errorf("git branch not automatically detectable")
  273. }
  274. ok, remoteRepo := gitutils.ParseGithubRemote(remote)
  275. if !ok {
  276. return fmt.Errorf("remote is not a Github repository")
  277. }
  278. subdomain, err := createAgent.CreateFromGithub(
  279. ctx,
  280. &deploy.GithubOpts{
  281. Branch: gitBranch,
  282. Repo: remoteRepo,
  283. }, overrideValues)
  284. return handleSubdomainCreate(subdomain, err)
  285. }
  286. func readValuesFile() (map[string]interface{}, error) {
  287. res := make(map[string]interface{})
  288. if values == "" {
  289. return res, nil
  290. }
  291. valuesFilePath, err := filepath.Abs(values)
  292. if err != nil {
  293. return nil, err
  294. }
  295. if info, err := os.Stat(valuesFilePath); os.IsNotExist(err) || info.IsDir() {
  296. return nil, fmt.Errorf("values file does not exist or is a directory")
  297. }
  298. reader, err := os.Open(valuesFilePath)
  299. if err != nil {
  300. return nil, err
  301. }
  302. bytes, err := ioutil.ReadAll(reader)
  303. if err != nil {
  304. return nil, err
  305. }
  306. err = yaml.Unmarshal(bytes, &res)
  307. if err != nil {
  308. return nil, err
  309. }
  310. return res, nil
  311. }