create.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. }
  147. var supportedKinds = map[string]string{"web": "", "job": "", "worker": ""}
  148. func createFull(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  149. // check the kind
  150. if _, exists := supportedKinds[args[0]]; !exists {
  151. return fmt.Errorf("%s is not a supported type: specify web, job, or worker", args[0])
  152. }
  153. var err error
  154. fullPath, err := filepath.Abs(localPath)
  155. if err != nil {
  156. return err
  157. }
  158. if os.Getenv("GITHUB_ACTIONS") == "" && source == "local" && fullPath == homedir.HomeDir() {
  159. proceed, err := utils.PromptConfirm("You are deploying your home directory. Do you want to continue?", false)
  160. if err != nil {
  161. return err
  162. }
  163. if !proceed {
  164. return nil
  165. }
  166. }
  167. // read the values if necessary
  168. valuesObj, err := readValuesFile()
  169. if err != nil {
  170. return err
  171. }
  172. color.New(color.FgGreen).Printf("Creating %s release: %s\n", args[0], name)
  173. var buildMethod deploy.DeployBuildType
  174. if method != "" {
  175. buildMethod = deploy.DeployBuildType(method)
  176. } else if dockerfile != "" {
  177. buildMethod = deploy.DeployBuildTypeDocker
  178. }
  179. // add additional env, if they exist
  180. additionalEnv := make(map[string]string)
  181. for _, buildEnv := range buildFlagsEnv {
  182. if strSplArr := strings.SplitN(buildEnv, "=", 2); len(strSplArr) >= 2 {
  183. additionalEnv[strSplArr[0]] = strSplArr[1]
  184. }
  185. }
  186. createAgent := &deploy.CreateAgent{
  187. Client: client,
  188. CreateOpts: &deploy.CreateOpts{
  189. SharedOpts: &deploy.SharedOpts{
  190. ProjectID: cliConf.Project,
  191. ClusterID: cliConf.Cluster,
  192. Namespace: namespace,
  193. LocalPath: fullPath,
  194. LocalDockerfile: dockerfile,
  195. Method: buildMethod,
  196. AdditionalEnv: additionalEnv,
  197. UseCache: useCache,
  198. },
  199. Kind: args[0],
  200. ReleaseName: name,
  201. RegistryURL: registryURL,
  202. },
  203. }
  204. if source == "local" {
  205. if useCache {
  206. regID, imageURL, err := createAgent.GetImageRepoURL(name, namespace)
  207. if err != nil {
  208. return err
  209. }
  210. err = client.CreateRepository(
  211. context.Background(),
  212. cliConf.Project,
  213. regID,
  214. &types.CreateRegistryRepositoryRequest{
  215. ImageRepoURI: imageURL,
  216. },
  217. )
  218. if err != nil {
  219. return err
  220. }
  221. err = config.SetDockerConfig(createAgent.Client)
  222. if err != nil {
  223. return err
  224. }
  225. }
  226. subdomain, err := createAgent.CreateFromDocker(valuesObj, "default", nil, forceBuild)
  227. return handleSubdomainCreate(subdomain, err)
  228. } else if source == "github" {
  229. return createFromGithub(createAgent, valuesObj)
  230. }
  231. subdomain, err := createAgent.CreateFromRegistry(image, valuesObj)
  232. return handleSubdomainCreate(subdomain, err)
  233. }
  234. func handleSubdomainCreate(subdomain string, err error) error {
  235. if err != nil {
  236. return err
  237. }
  238. if subdomain != "" {
  239. color.New(color.FgGreen).Printf("Your web application is ready at: %s\n", subdomain)
  240. } else {
  241. color.New(color.FgGreen).Printf("Application created successfully\n")
  242. }
  243. return nil
  244. }
  245. func createFromGithub(createAgent *deploy.CreateAgent, overrideValues map[string]interface{}) error {
  246. fullPath, err := filepath.Abs(localPath)
  247. if err != nil {
  248. return err
  249. }
  250. _, err = gitutils.GitDirectory(fullPath)
  251. if err != nil {
  252. return err
  253. }
  254. remote, gitBranch, err := gitutils.GetRemoteBranch(fullPath)
  255. if err != nil {
  256. return err
  257. } else if gitBranch == "" {
  258. return fmt.Errorf("git branch not automatically detectable")
  259. }
  260. ok, remoteRepo := gitutils.ParseGithubRemote(remote)
  261. if !ok {
  262. return fmt.Errorf("remote is not a Github repository")
  263. }
  264. subdomain, err := createAgent.CreateFromGithub(&deploy.GithubOpts{
  265. Branch: gitBranch,
  266. Repo: remoteRepo,
  267. }, overrideValues)
  268. return handleSubdomainCreate(subdomain, err)
  269. }
  270. func readValuesFile() (map[string]interface{}, error) {
  271. res := make(map[string]interface{})
  272. if values == "" {
  273. return res, nil
  274. }
  275. valuesFilePath, err := filepath.Abs(values)
  276. if err != nil {
  277. return nil, err
  278. }
  279. if info, err := os.Stat(valuesFilePath); os.IsNotExist(err) || info.IsDir() {
  280. return nil, fmt.Errorf("values file does not exist or is a directory")
  281. }
  282. reader, err := os.Open(valuesFilePath)
  283. if err != nil {
  284. return nil, err
  285. }
  286. bytes, err := ioutil.ReadAll(reader)
  287. if err != nil {
  288. return nil, err
  289. }
  290. err = yaml.Unmarshal(bytes, &res)
  291. if err != nil {
  292. return nil, err
  293. }
  294. return res, nil
  295. }