yaml.go 17 KB

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