create.go 8.7 KB

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