yaml.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. package v2
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  8. "github.com/porter-dev/porter/internal/telemetry"
  9. "gopkg.in/yaml.v2"
  10. )
  11. // AppProtoWithEnv is a struct containing a PorterApp proto object and its environment variables
  12. type AppProtoWithEnv struct {
  13. AppProto *porterv1.PorterApp
  14. EnvVariables map[string]string
  15. }
  16. // AppWithPreviewOverrides is a porter app definition with its preview app definition, if it exists
  17. type AppWithPreviewOverrides struct {
  18. AppProtoWithEnv
  19. PreviewApp *AppProtoWithEnv
  20. }
  21. // AppProtoFromYaml converts a Porter YAML file into a PorterApp proto object
  22. func AppProtoFromYaml(ctx context.Context, porterYamlBytes []byte) (AppWithPreviewOverrides, error) {
  23. ctx, span := telemetry.NewSpan(ctx, "v2-app-proto-from-yaml")
  24. defer span.End()
  25. var out AppWithPreviewOverrides
  26. if porterYamlBytes == nil {
  27. return out, telemetry.Error(ctx, span, nil, "porter yaml is nil")
  28. }
  29. porterYaml := &PorterYAML{}
  30. err := yaml.Unmarshal(porterYamlBytes, porterYaml)
  31. if err != nil {
  32. return out, telemetry.Error(ctx, span, err, "error unmarshaling porter yaml")
  33. }
  34. appProto, envVariables, err := ProtoFromApp(ctx, porterYaml.PorterApp)
  35. if err != nil {
  36. return out, telemetry.Error(ctx, span, err, "error converting porter yaml to proto")
  37. }
  38. out.AppProto = appProto
  39. out.EnvVariables = envVariables
  40. if porterYaml.Previews != nil {
  41. previewAppProto, previewEnvVariables, err := ProtoFromApp(ctx, *porterYaml.Previews)
  42. if err != nil {
  43. return out, telemetry.Error(ctx, span, err, "error converting preview porter yaml to proto")
  44. }
  45. out.PreviewApp = &AppProtoWithEnv{
  46. AppProto: previewAppProto,
  47. EnvVariables: previewEnvVariables,
  48. }
  49. }
  50. return out, nil
  51. }
  52. // ServiceType is the type of a service in a Porter YAML file
  53. type ServiceType string
  54. const (
  55. // ServiceType_Web is type for web services specified in Porter YAML
  56. ServiceType_Web ServiceType = "web"
  57. // ServiceType_Worker is type for worker services specified in Porter YAML
  58. ServiceType_Worker ServiceType = "worker"
  59. // ServiceType_Job is type for job services specified in Porter YAML
  60. ServiceType_Job ServiceType = "job"
  61. )
  62. // EnvGroup is a struct containing the name and version of an environment group
  63. type EnvGroup struct {
  64. Name string `yaml:"name"`
  65. Version int `yaml:"version"`
  66. }
  67. // PorterApp represents all the possible fields in a Porter YAML file
  68. type PorterApp struct {
  69. Version string `yaml:"version,omitempty"`
  70. Name string `yaml:"name"`
  71. Services []Service `yaml:"services"`
  72. Image *Image `yaml:"image,omitempty"`
  73. Build *Build `yaml:"build,omitempty"`
  74. Env map[string]string `yaml:"env,omitempty"`
  75. Predeploy *Service `yaml:"predeploy,omitempty"`
  76. EnvGroups []EnvGroup `yaml:"envGroups,omitempty"`
  77. }
  78. // PorterYAML represents all the possible fields in a Porter YAML file
  79. type PorterYAML struct {
  80. PorterApp `yaml:",inline"`
  81. Previews *PorterApp `yaml:"previews,omitempty"`
  82. }
  83. // Build represents the build settings for a Porter app
  84. type Build struct {
  85. Context string `yaml:"context" validate:"dir"`
  86. Method string `yaml:"method" validate:"required,oneof=pack docker registry"`
  87. Builder string `yaml:"builder" validate:"required_if=Method pack"`
  88. Buildpacks []string `yaml:"buildpacks"`
  89. Dockerfile string `yaml:"dockerfile" validate:"required_if=Method docker"`
  90. CommitSHA string `yaml:"commitSha"`
  91. }
  92. // Image is the repository and tag for an app's build image
  93. type Image struct {
  94. Repository string `yaml:"repository"`
  95. Tag string `yaml:"tag"`
  96. }
  97. // Service represents a single service in a porter app
  98. type Service struct {
  99. Name string `yaml:"name,omitempty"`
  100. Run *string `yaml:"run,omitempty"`
  101. Type ServiceType `yaml:"type,omitempty" validate:"required, oneof=web worker job"`
  102. Instances int `yaml:"instances,omitempty"`
  103. CpuCores float32 `yaml:"cpuCores,omitempty"`
  104. RamMegabytes int `yaml:"ramMegabytes,omitempty"`
  105. SmartOptimization *bool `yaml:"smartOptimization,omitempty"`
  106. Port int `yaml:"port,omitempty"`
  107. Autoscaling *AutoScaling `yaml:"autoscaling,omitempty" validate:"excluded_if=Type job"`
  108. Domains []Domains `yaml:"domains,omitempty" validate:"excluded_unless=Type web"`
  109. HealthCheck *HealthCheck `yaml:"healthCheck,omitempty" validate:"excluded_unless=Type web"`
  110. AllowConcurrent *bool `yaml:"allowConcurrent,omitempty" validate:"excluded_unless=Type job"`
  111. Cron string `yaml:"cron,omitempty" validate:"excluded_unless=Type job"`
  112. SuspendCron *bool `yaml:"suspendCron,omitempty" validate:"excluded_unless=Type job"`
  113. TimeoutSeconds int `yaml:"timeoutSeconds,omitempty" validate:"excluded_unless=Type job"`
  114. Private *bool `yaml:"private,omitempty" validate:"excluded_unless=Type web"`
  115. IngressAnnotations map[string]string `yaml:"ingressAnnotations,omitempty" validate:"excluded_unless=Type web"`
  116. }
  117. // AutoScaling represents the autoscaling settings for web services
  118. type AutoScaling struct {
  119. Enabled bool `yaml:"enabled"`
  120. MinInstances int `yaml:"minInstances"`
  121. MaxInstances int `yaml:"maxInstances"`
  122. CpuThresholdPercent int `yaml:"cpuThresholdPercent"`
  123. MemoryThresholdPercent int `yaml:"memoryThresholdPercent"`
  124. }
  125. // Domains are the custom domains for a web service
  126. type Domains struct {
  127. Name string `yaml:"name"`
  128. }
  129. // HealthCheck is the health check settings for a web service
  130. type HealthCheck struct {
  131. Enabled bool `yaml:"enabled"`
  132. HttpPath string `yaml:"httpPath"`
  133. }
  134. // ProtoFromApp converts a PorterApp type to a base PorterApp proto type and returns env variables
  135. func ProtoFromApp(ctx context.Context, porterApp PorterApp) (*porterv1.PorterApp, map[string]string, error) {
  136. ctx, span := telemetry.NewSpan(ctx, "build-app-proto")
  137. defer span.End()
  138. appProto := &porterv1.PorterApp{
  139. Name: porterApp.Name,
  140. }
  141. if porterApp.Build != nil {
  142. appProto.Build = &porterv1.Build{
  143. Context: porterApp.Build.Context,
  144. Method: porterApp.Build.Method,
  145. Builder: porterApp.Build.Builder,
  146. Buildpacks: porterApp.Build.Buildpacks,
  147. Dockerfile: porterApp.Build.Dockerfile,
  148. CommitSha: porterApp.Build.CommitSHA,
  149. }
  150. }
  151. if porterApp.Image != nil {
  152. appProto.Image = &porterv1.AppImage{
  153. Repository: porterApp.Image.Repository,
  154. Tag: porterApp.Image.Tag,
  155. }
  156. }
  157. if porterApp.Services == nil {
  158. return appProto, nil, telemetry.Error(ctx, span, nil, "porter yaml is missing services")
  159. }
  160. // service map is only needed for backwards compatibility at this time
  161. serviceMap := make(map[string]*porterv1.Service)
  162. var services []*porterv1.Service
  163. for _, service := range porterApp.Services {
  164. serviceType := protoEnumFromType(service.Name, service)
  165. serviceProto, err := serviceProtoFromConfig(service, serviceType)
  166. if err != nil {
  167. return appProto, nil, telemetry.Error(ctx, span, err, "error casting service config")
  168. }
  169. if service.Name == "" {
  170. return appProto, nil, telemetry.Error(ctx, span, nil, "service found with no name")
  171. }
  172. services = append(services, serviceProto)
  173. serviceMap[service.Name] = serviceProto
  174. }
  175. appProto.ServiceList = services
  176. appProto.Services = serviceMap // nolint:staticcheck // temporarily using deprecated field for backwards compatibility
  177. if porterApp.Predeploy != nil {
  178. predeployProto, err := serviceProtoFromConfig(*porterApp.Predeploy, porterv1.ServiceType_SERVICE_TYPE_JOB)
  179. if err != nil {
  180. return appProto, nil, telemetry.Error(ctx, span, err, "error casting predeploy config")
  181. }
  182. appProto.Predeploy = predeployProto
  183. }
  184. envGroups := make([]*porterv1.EnvGroup, 0)
  185. if porterApp.EnvGroups != nil {
  186. for _, envGroup := range porterApp.EnvGroups {
  187. envGroups = append(envGroups, &porterv1.EnvGroup{
  188. Name: envGroup.Name,
  189. Version: int64(envGroup.Version),
  190. })
  191. }
  192. }
  193. appProto.EnvGroups = envGroups
  194. return appProto, porterApp.Env, nil
  195. }
  196. func protoEnumFromType(name string, service Service) porterv1.ServiceType {
  197. serviceType := porterv1.ServiceType_SERVICE_TYPE_WORKER
  198. if strings.Contains(name, "web") {
  199. serviceType = porterv1.ServiceType_SERVICE_TYPE_WEB
  200. }
  201. if strings.Contains(name, "wkr") || strings.Contains(name, "worker") {
  202. serviceType = porterv1.ServiceType_SERVICE_TYPE_WORKER
  203. }
  204. if strings.Contains(name, "job") {
  205. serviceType = porterv1.ServiceType_SERVICE_TYPE_JOB
  206. }
  207. switch service.Type {
  208. case "web":
  209. serviceType = porterv1.ServiceType_SERVICE_TYPE_WEB
  210. case "worker":
  211. serviceType = porterv1.ServiceType_SERVICE_TYPE_WORKER
  212. case "job":
  213. serviceType = porterv1.ServiceType_SERVICE_TYPE_JOB
  214. }
  215. return serviceType
  216. }
  217. func serviceProtoFromConfig(service Service, serviceType porterv1.ServiceType) (*porterv1.Service, error) {
  218. serviceProto := &porterv1.Service{
  219. Name: service.Name,
  220. RunOptional: service.Run,
  221. Instances: int32(service.Instances),
  222. CpuCores: service.CpuCores,
  223. RamMegabytes: int32(service.RamMegabytes),
  224. Port: int32(service.Port),
  225. SmartOptimization: service.SmartOptimization,
  226. Type: serviceType,
  227. }
  228. switch serviceType {
  229. default:
  230. return nil, fmt.Errorf("invalid service type '%s'", serviceType)
  231. case porterv1.ServiceType_SERVICE_TYPE_UNSPECIFIED:
  232. return nil, errors.New("Service type unspecified")
  233. case porterv1.ServiceType_SERVICE_TYPE_WEB:
  234. webConfig := &porterv1.WebServiceConfig{}
  235. var autoscaling *porterv1.Autoscaling
  236. if service.Autoscaling != nil {
  237. autoscaling = &porterv1.Autoscaling{
  238. Enabled: service.Autoscaling.Enabled,
  239. MinInstances: int32(service.Autoscaling.MinInstances),
  240. MaxInstances: int32(service.Autoscaling.MaxInstances),
  241. CpuThresholdPercent: int32(service.Autoscaling.CpuThresholdPercent),
  242. MemoryThresholdPercent: int32(service.Autoscaling.MemoryThresholdPercent),
  243. }
  244. }
  245. webConfig.Autoscaling = autoscaling
  246. var healthCheck *porterv1.HealthCheck
  247. if service.HealthCheck != nil {
  248. healthCheck = &porterv1.HealthCheck{
  249. Enabled: service.HealthCheck.Enabled,
  250. HttpPath: service.HealthCheck.HttpPath,
  251. }
  252. }
  253. webConfig.HealthCheck = healthCheck
  254. domains := make([]*porterv1.Domain, 0)
  255. for _, domain := range service.Domains {
  256. domains = append(domains, &porterv1.Domain{
  257. Name: domain.Name,
  258. })
  259. }
  260. webConfig.Domains = domains
  261. webConfig.IngressAnnotations = service.IngressAnnotations
  262. if service.Private != nil {
  263. webConfig.Private = service.Private
  264. }
  265. serviceProto.Config = &porterv1.Service_WebConfig{
  266. WebConfig: webConfig,
  267. }
  268. case porterv1.ServiceType_SERVICE_TYPE_WORKER:
  269. workerConfig := &porterv1.WorkerServiceConfig{}
  270. var autoscaling *porterv1.Autoscaling
  271. if service.Autoscaling != nil {
  272. autoscaling = &porterv1.Autoscaling{
  273. Enabled: service.Autoscaling.Enabled,
  274. MinInstances: int32(service.Autoscaling.MinInstances),
  275. MaxInstances: int32(service.Autoscaling.MaxInstances),
  276. CpuThresholdPercent: int32(service.Autoscaling.CpuThresholdPercent),
  277. MemoryThresholdPercent: int32(service.Autoscaling.MemoryThresholdPercent),
  278. }
  279. }
  280. workerConfig.Autoscaling = autoscaling
  281. serviceProto.Config = &porterv1.Service_WorkerConfig{
  282. WorkerConfig: workerConfig,
  283. }
  284. case porterv1.ServiceType_SERVICE_TYPE_JOB:
  285. jobConfig := &porterv1.JobServiceConfig{
  286. AllowConcurrentOptional: service.AllowConcurrent,
  287. Cron: service.Cron,
  288. }
  289. if service.SuspendCron != nil {
  290. jobConfig.SuspendCron = service.SuspendCron
  291. }
  292. if service.TimeoutSeconds != 0 {
  293. jobConfig.TimeoutSeconds = int64(service.TimeoutSeconds)
  294. }
  295. serviceProto.Config = &porterv1.Service_JobConfig{
  296. JobConfig: jobConfig,
  297. }
  298. }
  299. return serviceProto, nil
  300. }
  301. // AppFromProto converts a PorterApp proto object into a PorterApp struct
  302. func AppFromProto(appProto *porterv1.PorterApp) (PorterApp, error) {
  303. porterApp := PorterApp{
  304. Version: "v2",
  305. Name: appProto.Name,
  306. }
  307. if appProto.Build != nil {
  308. porterApp.Build = &Build{
  309. Context: appProto.Build.Context,
  310. Method: appProto.Build.Method,
  311. Builder: appProto.Build.Builder,
  312. Buildpacks: appProto.Build.Buildpacks,
  313. Dockerfile: appProto.Build.Dockerfile,
  314. CommitSHA: appProto.Build.CommitSha,
  315. }
  316. }
  317. if appProto.Image != nil {
  318. porterApp.Image = &Image{
  319. Repository: appProto.Image.Repository,
  320. Tag: appProto.Image.Tag,
  321. }
  322. }
  323. uniqueServices := uniqueServices(appProto.Services, appProto.ServiceList) // nolint:staticcheck // temporarily using deprecated field for backwards compatibility
  324. for _, service := range uniqueServices {
  325. appService, err := appServiceFromProto(service)
  326. if err != nil {
  327. return porterApp, err
  328. }
  329. porterApp.Services = append(porterApp.Services, appService)
  330. }
  331. if appProto.Predeploy != nil {
  332. appPredeploy, err := appServiceFromProto(appProto.Predeploy)
  333. if err != nil {
  334. return porterApp, err
  335. }
  336. porterApp.Predeploy = &appPredeploy
  337. }
  338. porterApp.EnvGroups = make([]EnvGroup, 0)
  339. for _, envGroup := range appProto.EnvGroups {
  340. porterApp.EnvGroups = append(porterApp.EnvGroups, EnvGroup{
  341. Name: envGroup.Name,
  342. Version: int(envGroup.Version),
  343. })
  344. }
  345. return porterApp, nil
  346. }
  347. func appServiceFromProto(service *porterv1.Service) (Service, error) {
  348. appService := Service{
  349. Name: service.Name,
  350. Run: service.RunOptional,
  351. Instances: int(service.Instances),
  352. CpuCores: service.CpuCores,
  353. RamMegabytes: int(service.RamMegabytes),
  354. Port: int(service.Port),
  355. SmartOptimization: service.SmartOptimization,
  356. }
  357. switch service.Type {
  358. default:
  359. return appService, fmt.Errorf("invalid service type '%s'", service.Type)
  360. case porterv1.ServiceType_SERVICE_TYPE_UNSPECIFIED:
  361. return appService, errors.New("Service type unspecified")
  362. case porterv1.ServiceType_SERVICE_TYPE_WEB:
  363. webConfig := service.GetWebConfig()
  364. appService.Type = "web"
  365. var autoscaling *AutoScaling
  366. if webConfig.Autoscaling != nil {
  367. autoscaling = &AutoScaling{
  368. Enabled: webConfig.Autoscaling.Enabled,
  369. MinInstances: int(webConfig.Autoscaling.MinInstances),
  370. MaxInstances: int(webConfig.Autoscaling.MaxInstances),
  371. CpuThresholdPercent: int(webConfig.Autoscaling.CpuThresholdPercent),
  372. MemoryThresholdPercent: int(webConfig.Autoscaling.MemoryThresholdPercent),
  373. }
  374. }
  375. appService.Autoscaling = autoscaling
  376. var healthCheck *HealthCheck
  377. if webConfig.HealthCheck != nil {
  378. healthCheck = &HealthCheck{
  379. Enabled: webConfig.HealthCheck.Enabled,
  380. HttpPath: webConfig.HealthCheck.HttpPath,
  381. }
  382. }
  383. appService.HealthCheck = healthCheck
  384. domains := make([]Domains, 0)
  385. for _, domain := range webConfig.Domains {
  386. domains = append(domains, Domains{
  387. Name: domain.Name,
  388. })
  389. }
  390. appService.Domains = domains
  391. appService.IngressAnnotations = webConfig.IngressAnnotations
  392. if webConfig.Private != nil {
  393. appService.Private = webConfig.Private
  394. }
  395. case porterv1.ServiceType_SERVICE_TYPE_WORKER:
  396. workerConfig := service.GetWorkerConfig()
  397. appService.Type = "worker"
  398. var autoscaling *AutoScaling
  399. if workerConfig.Autoscaling != nil {
  400. autoscaling = &AutoScaling{
  401. Enabled: workerConfig.Autoscaling.Enabled,
  402. MinInstances: int(workerConfig.Autoscaling.MinInstances),
  403. MaxInstances: int(workerConfig.Autoscaling.MaxInstances),
  404. CpuThresholdPercent: int(workerConfig.Autoscaling.CpuThresholdPercent),
  405. MemoryThresholdPercent: int(workerConfig.Autoscaling.MemoryThresholdPercent),
  406. }
  407. }
  408. appService.Autoscaling = autoscaling
  409. case porterv1.ServiceType_SERVICE_TYPE_JOB:
  410. jobConfig := service.GetJobConfig()
  411. appService.Type = "job"
  412. appService.AllowConcurrent = jobConfig.AllowConcurrentOptional
  413. appService.Cron = jobConfig.Cron
  414. appService.SuspendCron = jobConfig.SuspendCron
  415. appService.TimeoutSeconds = int(jobConfig.TimeoutSeconds)
  416. }
  417. return appService, nil
  418. }
  419. func uniqueServices(serviceMap map[string]*porterv1.Service, serviceList []*porterv1.Service) []*porterv1.Service {
  420. if serviceList != nil {
  421. return serviceList
  422. }
  423. // deduplicate services by name, favoring whatever was defined first
  424. uniqueServices := make(map[string]*porterv1.Service)
  425. for name, service := range serviceMap {
  426. service.Name = name
  427. uniqueServices[service.Name] = service
  428. }
  429. mergedServiceList := make([]*porterv1.Service, 0)
  430. for _, service := range uniqueServices {
  431. mergedServiceList = append(mergedServiceList, service)
  432. }
  433. return mergedServiceList
  434. }