create.go 8.7 KB

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