create.go 9.1 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(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(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  153. ctx := context.Background()
  154. project, err := client.GetProject(ctx, cliConf.Project)
  155. if err != nil {
  156. return fmt.Errorf("could not retrieve project from Porter API. Please contact support@porter.run")
  157. }
  158. if project.ValidateApplyV2 {
  159. err = v2.CreateFull(ctx)
  160. if err != nil {
  161. return err
  162. }
  163. return nil
  164. }
  165. // check the kind
  166. if _, exists := supportedKinds[args[0]]; !exists {
  167. return fmt.Errorf("%s is not a supported type: specify web, job, or worker", args[0])
  168. }
  169. fullPath, err := filepath.Abs(localPath)
  170. if err != nil {
  171. return err
  172. }
  173. if os.Getenv("GITHUB_ACTIONS") == "" && source == "local" && fullPath == homedir.HomeDir() {
  174. proceed, err := utils.PromptConfirm("You are deploying your home directory. Do you want to continue?", false)
  175. if err != nil {
  176. return err
  177. }
  178. if !proceed {
  179. return nil
  180. }
  181. }
  182. // read the values if necessary
  183. valuesObj, err := readValuesFile()
  184. if err != nil {
  185. return err
  186. }
  187. color.New(color.FgGreen).Printf("Creating %s release: %s\n", args[0], name)
  188. var buildMethod deploy.DeployBuildType
  189. if method != "" {
  190. buildMethod = deploy.DeployBuildType(method)
  191. } else if dockerfile != "" {
  192. buildMethod = deploy.DeployBuildTypeDocker
  193. }
  194. // add additional env, if they exist
  195. additionalEnv := make(map[string]string)
  196. for _, buildEnv := range buildFlagsEnv {
  197. if strSplArr := strings.SplitN(buildEnv, "=", 2); len(strSplArr) >= 2 {
  198. additionalEnv[strSplArr[0]] = strSplArr[1]
  199. }
  200. }
  201. createAgent := &deploy.CreateAgent{
  202. Client: client,
  203. CreateOpts: &deploy.CreateOpts{
  204. SharedOpts: &deploy.SharedOpts{
  205. ProjectID: cliConf.Project,
  206. ClusterID: cliConf.Cluster,
  207. Namespace: namespace,
  208. LocalPath: fullPath,
  209. LocalDockerfile: dockerfile,
  210. Method: buildMethod,
  211. AdditionalEnv: additionalEnv,
  212. UseCache: useCache,
  213. },
  214. Kind: args[0],
  215. ReleaseName: name,
  216. RegistryURL: registryURL,
  217. },
  218. }
  219. if source == "local" {
  220. if useCache {
  221. regID, imageURL, err := createAgent.GetImageRepoURL(name, namespace)
  222. if err != nil {
  223. return err
  224. }
  225. err = client.CreateRepository(
  226. context.Background(),
  227. cliConf.Project,
  228. regID,
  229. &types.CreateRegistryRepositoryRequest{
  230. ImageRepoURI: imageURL,
  231. },
  232. )
  233. if err != nil {
  234. return err
  235. }
  236. err = config.SetDockerConfig(createAgent.Client)
  237. if err != nil {
  238. return err
  239. }
  240. }
  241. subdomain, err := createAgent.CreateFromDocker(valuesObj, "default", nil)
  242. return handleSubdomainCreate(subdomain, err)
  243. } else if source == "github" {
  244. return createFromGithub(createAgent, valuesObj)
  245. }
  246. subdomain, err := createAgent.CreateFromRegistry(image, valuesObj)
  247. return handleSubdomainCreate(subdomain, err)
  248. }
  249. func handleSubdomainCreate(subdomain string, err error) error {
  250. if err != nil {
  251. return err
  252. }
  253. if subdomain != "" {
  254. color.New(color.FgGreen).Printf("Your web application is ready at: %s\n", subdomain)
  255. } else {
  256. color.New(color.FgGreen).Printf("Application created successfully\n")
  257. }
  258. return nil
  259. }
  260. func createFromGithub(createAgent *deploy.CreateAgent, overrideValues map[string]interface{}) error {
  261. fullPath, err := filepath.Abs(localPath)
  262. if err != nil {
  263. return err
  264. }
  265. _, err = gitutils.GitDirectory(fullPath)
  266. if err != nil {
  267. return err
  268. }
  269. remote, gitBranch, err := gitutils.GetRemoteBranch(fullPath)
  270. if err != nil {
  271. return err
  272. } else if gitBranch == "" {
  273. return fmt.Errorf("git branch not automatically detectable")
  274. }
  275. ok, remoteRepo := gitutils.ParseGithubRemote(remote)
  276. if !ok {
  277. return fmt.Errorf("remote is not a Github repository")
  278. }
  279. subdomain, err := createAgent.CreateFromGithub(&deploy.GithubOpts{
  280. Branch: gitBranch,
  281. Repo: remoteRepo,
  282. }, overrideValues)
  283. return handleSubdomainCreate(subdomain, err)
  284. }
  285. func readValuesFile() (map[string]interface{}, error) {
  286. res := make(map[string]interface{})
  287. if values == "" {
  288. return res, nil
  289. }
  290. valuesFilePath, err := filepath.Abs(values)
  291. if err != nil {
  292. return nil, err
  293. }
  294. if info, err := os.Stat(valuesFilePath); os.IsNotExist(err) || info.IsDir() {
  295. return nil, fmt.Errorf("values file does not exist or is a directory")
  296. }
  297. reader, err := os.Open(valuesFilePath)
  298. if err != nil {
  299. return nil, err
  300. }
  301. bytes, err := ioutil.ReadAll(reader)
  302. if err != nil {
  303. return nil, err
  304. }
  305. err = yaml.Unmarshal(bytes, &res)
  306. if err != nil {
  307. return nil, err
  308. }
  309. return res, nil
  310. }