2
0

create.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. var err error
  137. // read the values if necessary
  138. valuesObj, err := readValuesFile()
  139. if err != nil {
  140. return err
  141. }
  142. color.New(color.FgGreen).Printf("Creating %s release: %s\n", args[0], name)
  143. fullPath, err := filepath.Abs(localPath)
  144. if err != nil {
  145. return err
  146. }
  147. var buildMethod deploy.DeployBuildType
  148. if method != "" {
  149. buildMethod = deploy.DeployBuildType(method)
  150. } else if dockerfile != "" {
  151. buildMethod = deploy.DeployBuildTypeDocker
  152. }
  153. // add additional env, if they exist
  154. additionalEnv := make(map[string]string)
  155. for _, buildEnv := range buildFlagsEnv {
  156. if strSplArr := strings.SplitN(buildEnv, "=", 2); len(strSplArr) >= 2 {
  157. additionalEnv[strSplArr[0]] = strSplArr[1]
  158. }
  159. }
  160. createAgent := &deploy.CreateAgent{
  161. Client: client,
  162. CreateOpts: &deploy.CreateOpts{
  163. SharedOpts: &deploy.SharedOpts{
  164. ProjectID: config.Project,
  165. ClusterID: config.Cluster,
  166. Namespace: namespace,
  167. LocalPath: fullPath,
  168. LocalDockerfile: dockerfile,
  169. Method: buildMethod,
  170. AdditionalEnv: additionalEnv,
  171. },
  172. Kind: args[0],
  173. ReleaseName: name,
  174. RegistryURL: registryURL,
  175. },
  176. }
  177. if source == "local" {
  178. subdomain, err := createAgent.CreateFromDocker(valuesObj, "default", nil)
  179. return handleSubdomainCreate(subdomain, err)
  180. } else if source == "github" {
  181. return createFromGithub(createAgent, valuesObj)
  182. }
  183. subdomain, err := createAgent.CreateFromRegistry(image, valuesObj)
  184. return handleSubdomainCreate(subdomain, err)
  185. }
  186. func handleSubdomainCreate(subdomain string, err error) error {
  187. if err != nil {
  188. return err
  189. }
  190. if subdomain != "" {
  191. color.New(color.FgGreen).Printf("Your web application is ready at: %s\n", subdomain)
  192. } else {
  193. color.New(color.FgGreen).Printf("Application created successfully\n")
  194. }
  195. return nil
  196. }
  197. func createFromGithub(createAgent *deploy.CreateAgent, overrideValues map[string]interface{}) error {
  198. fullPath, err := filepath.Abs(localPath)
  199. if err != nil {
  200. return err
  201. }
  202. _, err = gitutils.GitDirectory(fullPath)
  203. if err != nil {
  204. return err
  205. }
  206. remote, gitBranch, err := gitutils.GetRemoteBranch(fullPath)
  207. if err != nil {
  208. return err
  209. } else if gitBranch == "" {
  210. return fmt.Errorf("git branch not automatically detectable")
  211. }
  212. ok, remoteRepo := gitutils.ParseGithubRemote(remote)
  213. if !ok {
  214. return fmt.Errorf("remote is not a Github repository")
  215. }
  216. subdomain, err := createAgent.CreateFromGithub(&deploy.GithubOpts{
  217. Branch: gitBranch,
  218. Repo: remoteRepo,
  219. }, overrideValues)
  220. return handleSubdomainCreate(subdomain, err)
  221. }
  222. func readValuesFile() (map[string]interface{}, error) {
  223. res := make(map[string]interface{})
  224. if values == "" {
  225. return res, nil
  226. }
  227. valuesFilePath, err := filepath.Abs(values)
  228. if err != nil {
  229. return nil, err
  230. }
  231. if info, err := os.Stat(valuesFilePath); os.IsNotExist(err) || info.IsDir() {
  232. return nil, fmt.Errorf("values file does not exist or is a directory")
  233. }
  234. reader, err := os.Open(valuesFilePath)
  235. if err != nil {
  236. return nil, err
  237. }
  238. bytes, err := ioutil.ReadAll(reader)
  239. if err != nil {
  240. return nil, err
  241. }
  242. err = yaml.Unmarshal(bytes, &res)
  243. if err != nil {
  244. return nil, err
  245. }
  246. return res, nil
  247. }