create.go 7.5 KB

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