create.go 8.0 KB

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