create.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. var forceBuild bool
  64. func init() {
  65. rootCmd.AddCommand(createCmd)
  66. createCmd.PersistentFlags().StringVar(
  67. &name,
  68. "app",
  69. "",
  70. "name of the new application/job/worker.",
  71. )
  72. createCmd.MarkPersistentFlagRequired("app")
  73. createCmd.PersistentFlags().StringVarP(
  74. &localPath,
  75. "path",
  76. "p",
  77. "",
  78. "if local build, the path to the build directory",
  79. )
  80. createCmd.PersistentFlags().StringVar(
  81. &namespace,
  82. "namespace",
  83. "default",
  84. "namespace of the application",
  85. )
  86. createCmd.PersistentFlags().StringVarP(
  87. &values,
  88. "values",
  89. "v",
  90. "",
  91. "filepath to a values.yaml file",
  92. )
  93. createCmd.PersistentFlags().StringVar(
  94. &dockerfile,
  95. "dockerfile",
  96. "",
  97. "the path to the dockerfile",
  98. )
  99. createCmd.PersistentFlags().StringArrayVarP(
  100. &buildFlagsEnv,
  101. "env",
  102. "e",
  103. []string{},
  104. "Build-time environment variable, in the form 'VAR=VALUE'. These are not available at image runtime.",
  105. )
  106. createCmd.PersistentFlags().StringVar(
  107. &method,
  108. "method",
  109. "",
  110. "the build method to use (\"docker\" or \"pack\")",
  111. )
  112. createCmd.PersistentFlags().StringVar(
  113. &source,
  114. "source",
  115. "local",
  116. "the type of source (\"local\", \"github\", or \"registry\")",
  117. )
  118. createCmd.PersistentFlags().StringVar(
  119. &image,
  120. "image",
  121. "",
  122. "if the source is \"registry\", the image to use, in repository:tag format",
  123. )
  124. createCmd.PersistentFlags().StringVar(
  125. &registryURL,
  126. "registry-url",
  127. "",
  128. "the registry URL to use (must exist in \"porter registries list\")",
  129. )
  130. createCmd.PersistentFlags().BoolVar(
  131. &forceBuild,
  132. "force-build",
  133. false,
  134. "set this to force build an image",
  135. )
  136. }
  137. var supportedKinds = map[string]string{"web": "", "job": "", "worker": ""}
  138. func createFull(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  139. // check the kind
  140. if _, exists := supportedKinds[args[0]]; !exists {
  141. return fmt.Errorf("%s is not a supported type: specify web, job, or worker", args[0])
  142. }
  143. var err error
  144. // read the values if necessary
  145. valuesObj, err := readValuesFile()
  146. if err != nil {
  147. return err
  148. }
  149. color.New(color.FgGreen).Printf("Creating %s release: %s\n", args[0], name)
  150. fullPath, err := filepath.Abs(localPath)
  151. if err != nil {
  152. return err
  153. }
  154. var buildMethod deploy.DeployBuildType
  155. if method != "" {
  156. buildMethod = deploy.DeployBuildType(method)
  157. } else if dockerfile != "" {
  158. buildMethod = deploy.DeployBuildTypeDocker
  159. }
  160. // add additional env, if they exist
  161. additionalEnv := make(map[string]string)
  162. for _, buildEnv := range buildFlagsEnv {
  163. if strSplArr := strings.SplitN(buildEnv, "=", 2); len(strSplArr) >= 2 {
  164. additionalEnv[strSplArr[0]] = strSplArr[1]
  165. }
  166. }
  167. createAgent := &deploy.CreateAgent{
  168. Client: client,
  169. CreateOpts: &deploy.CreateOpts{
  170. SharedOpts: &deploy.SharedOpts{
  171. ProjectID: config.Project,
  172. ClusterID: config.Cluster,
  173. Namespace: namespace,
  174. LocalPath: fullPath,
  175. LocalDockerfile: dockerfile,
  176. Method: buildMethod,
  177. AdditionalEnv: additionalEnv,
  178. },
  179. Kind: args[0],
  180. ReleaseName: name,
  181. RegistryURL: registryURL,
  182. },
  183. }
  184. if source == "local" {
  185. subdomain, err := createAgent.CreateFromDocker(valuesObj, "default", nil, forceBuild)
  186. return handleSubdomainCreate(subdomain, err)
  187. } else if source == "github" {
  188. return createFromGithub(createAgent, valuesObj)
  189. }
  190. subdomain, err := createAgent.CreateFromRegistry(image, valuesObj)
  191. return handleSubdomainCreate(subdomain, err)
  192. }
  193. func handleSubdomainCreate(subdomain string, err error) error {
  194. if err != nil {
  195. return err
  196. }
  197. if subdomain != "" {
  198. color.New(color.FgGreen).Printf("Your web application is ready at: %s\n", subdomain)
  199. } else {
  200. color.New(color.FgGreen).Printf("Application created successfully\n")
  201. }
  202. return nil
  203. }
  204. func createFromGithub(createAgent *deploy.CreateAgent, overrideValues map[string]interface{}) error {
  205. fullPath, err := filepath.Abs(localPath)
  206. if err != nil {
  207. return err
  208. }
  209. _, err = gitutils.GitDirectory(fullPath)
  210. if err != nil {
  211. return err
  212. }
  213. remote, gitBranch, err := gitutils.GetRemoteBranch(fullPath)
  214. if err != nil {
  215. return err
  216. } else if gitBranch == "" {
  217. return fmt.Errorf("git branch not automatically detectable")
  218. }
  219. ok, remoteRepo := gitutils.ParseGithubRemote(remote)
  220. if !ok {
  221. return fmt.Errorf("remote is not a Github repository")
  222. }
  223. subdomain, err := createAgent.CreateFromGithub(&deploy.GithubOpts{
  224. Branch: gitBranch,
  225. Repo: remoteRepo,
  226. }, overrideValues)
  227. return handleSubdomainCreate(subdomain, err)
  228. }
  229. func readValuesFile() (map[string]interface{}, error) {
  230. res := make(map[string]interface{})
  231. if values == "" {
  232. return res, nil
  233. }
  234. valuesFilePath, err := filepath.Abs(values)
  235. if err != nil {
  236. return nil, err
  237. }
  238. if info, err := os.Stat(valuesFilePath); os.IsNotExist(err) || info.IsDir() {
  239. return nil, fmt.Errorf("values file does not exist or is a directory")
  240. }
  241. reader, err := os.Open(valuesFilePath)
  242. if err != nil {
  243. return nil, err
  244. }
  245. bytes, err := ioutil.ReadAll(reader)
  246. if err != nil {
  247. return nil, err
  248. }
  249. err = yaml.Unmarshal(bytes, &res)
  250. if err != nil {
  251. return nil, err
  252. }
  253. return res, nil
  254. }