yaml.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. package v1
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "math"
  7. "sort"
  8. "strconv"
  9. "strings"
  10. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  11. "github.com/porter-dev/porter/internal/telemetry"
  12. "gopkg.in/yaml.v2"
  13. )
  14. // AppProtoFromYaml converts an old version Porter YAML file into a PorterApp proto object
  15. func AppProtoFromYaml(ctx context.Context, porterYamlBytes []byte) (*porterv1.PorterApp, map[string]string, error) {
  16. ctx, span := telemetry.NewSpan(ctx, "v1-app-proto-from-yaml")
  17. defer span.End()
  18. if porterYamlBytes == nil {
  19. return nil, nil, telemetry.Error(ctx, span, nil, "porter yaml is nil")
  20. }
  21. porterYaml := &PorterYAML{}
  22. err := yaml.Unmarshal(porterYamlBytes, porterYaml)
  23. if err != nil {
  24. return nil, nil, telemetry.Error(ctx, span, err, "error unmarshaling porter yaml")
  25. }
  26. appProto := &porterv1.PorterApp{}
  27. if porterYaml.Build != nil {
  28. appProto.Build = &porterv1.Build{
  29. Context: porterYaml.Build.Context,
  30. Method: porterYaml.Build.Method,
  31. Builder: porterYaml.Build.Builder,
  32. Buildpacks: porterYaml.Build.Buildpacks,
  33. Dockerfile: porterYaml.Build.Dockerfile,
  34. }
  35. }
  36. if porterYaml.Build != nil && porterYaml.Build.Image != "" {
  37. imageSpl := strings.Split(porterYaml.Build.Image, ":")
  38. if len(imageSpl) == 2 {
  39. appProto.Image = &porterv1.AppImage{
  40. Repository: imageSpl[0],
  41. Tag: imageSpl[1],
  42. }
  43. } else {
  44. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "image", Value: porterYaml.Build.Image})
  45. return nil, nil, telemetry.Error(ctx, span, err, "error parsing image")
  46. }
  47. }
  48. if porterYaml.Apps != nil && porterYaml.Services != nil {
  49. return nil, nil, telemetry.Error(ctx, span, nil, "'apps' and 'services' are synonymous but both were defined")
  50. }
  51. var services map[string]Service
  52. if porterYaml.Apps != nil {
  53. services = porterYaml.Apps
  54. }
  55. if porterYaml.Services != nil {
  56. services = porterYaml.Services
  57. }
  58. if services == nil {
  59. return nil, nil, telemetry.Error(ctx, span, nil, "porter yaml is missing services")
  60. }
  61. var serviceList []*porterv1.Service
  62. for name, service := range services {
  63. serviceType := protoEnumFromType(name, service)
  64. serviceProto, err := serviceProtoFromConfig(service, serviceType)
  65. if err != nil {
  66. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "failing-service-name", Value: name})
  67. return nil, nil, telemetry.Error(ctx, span, err, "error casting service config")
  68. }
  69. serviceProto.Name = name
  70. serviceList = append(serviceList, serviceProto)
  71. }
  72. sort.Slice(serviceList, func(i, j int) bool {
  73. if serviceList[i].Type != serviceList[j].Type {
  74. return serviceList[i].Type < serviceList[j].Type
  75. }
  76. return serviceList[i].Name < serviceList[j].Name
  77. })
  78. appProto.ServiceList = serviceList
  79. if porterYaml.Release != nil {
  80. predeployProto, err := serviceProtoFromConfig(*porterYaml.Release, porterv1.ServiceType_SERVICE_TYPE_JOB)
  81. if err != nil {
  82. return nil, nil, telemetry.Error(ctx, span, err, "error casting predeploy config")
  83. }
  84. appProto.Predeploy = predeployProto
  85. }
  86. return appProto, porterYaml.Env, nil
  87. }
  88. func protoEnumFromType(name string, service Service) porterv1.ServiceType {
  89. serviceType := porterv1.ServiceType_SERVICE_TYPE_UNSPECIFIED
  90. if strings.Contains(name, "web") {
  91. serviceType = porterv1.ServiceType_SERVICE_TYPE_WEB
  92. }
  93. if strings.Contains(name, "wkr") || strings.Contains(name, "worker") {
  94. serviceType = porterv1.ServiceType_SERVICE_TYPE_WORKER
  95. }
  96. if strings.Contains(name, "job") {
  97. serviceType = porterv1.ServiceType_SERVICE_TYPE_JOB
  98. }
  99. switch service.Type {
  100. case "web":
  101. serviceType = porterv1.ServiceType_SERVICE_TYPE_WEB
  102. case "worker":
  103. serviceType = porterv1.ServiceType_SERVICE_TYPE_WORKER
  104. case "job":
  105. serviceType = porterv1.ServiceType_SERVICE_TYPE_JOB
  106. }
  107. return serviceType
  108. }
  109. func serviceProtoFromConfig(service Service, serviceType porterv1.ServiceType) (*porterv1.Service, error) {
  110. serviceProto := &porterv1.Service{
  111. RunOptional: service.Run,
  112. Type: serviceType,
  113. }
  114. if service.Config.ReplicaCount != nil {
  115. // if the revision number cannot be converted, it will default to 0
  116. replicaCount, _ := strconv.Atoi(*service.Config.ReplicaCount)
  117. if replicaCount < math.MinInt32 || replicaCount > math.MaxInt32 {
  118. return nil, fmt.Errorf("replica count is out of range of int32")
  119. }
  120. // nolint:gosec
  121. int32Value := int32(replicaCount)
  122. serviceProto.InstancesOptional = &int32Value
  123. }
  124. if service.Config.Resources.Requests.Cpu != "" {
  125. cpuCoresStr := service.Config.Resources.Requests.Cpu
  126. if !strings.HasSuffix(cpuCoresStr, "m") {
  127. return nil, fmt.Errorf("cpu is not in millicores")
  128. }
  129. cpuCoresStr = strings.TrimSuffix(cpuCoresStr, "m")
  130. cpuCoresFloat64, err := strconv.ParseFloat(cpuCoresStr, 32)
  131. if err != nil {
  132. return nil, fmt.Errorf("cpu is not a float")
  133. }
  134. serviceProto.CpuCores = float32(cpuCoresFloat64) / 1000
  135. }
  136. if service.Config.Resources.Requests.Memory != "" {
  137. memoryStr := service.Config.Resources.Requests.Memory
  138. if !strings.HasSuffix(memoryStr, "Mi") {
  139. return nil, fmt.Errorf("memory is not in Mi")
  140. }
  141. memoryStr = strings.TrimSuffix(memoryStr, "Mi")
  142. memoryFloat64, err := strconv.ParseFloat(memoryStr, 32)
  143. if err != nil {
  144. return nil, fmt.Errorf("memory is not a float")
  145. }
  146. // nolint:gosec
  147. serviceProto.RamMegabytes = int32(memoryFloat64)
  148. }
  149. if service.Config.Container.Port != "" && service.Config.Service.Port != "" && service.Config.Container.Port != service.Config.Service.Port {
  150. return nil, errors.New("container port and service port do not match")
  151. }
  152. if service.Config.Container.Port != "" {
  153. port, err := strconv.Atoi(service.Config.Container.Port)
  154. if err != nil {
  155. return nil, fmt.Errorf("container port cannot be converted to int: %w", err)
  156. }
  157. if port < math.MinInt32 || port > math.MaxInt32 {
  158. return nil, fmt.Errorf("port is out of range of int32")
  159. }
  160. // nolint:gosec
  161. serviceProto.Port = int32(port)
  162. }
  163. if service.Config.Service.Port != "" {
  164. port, err := strconv.Atoi(service.Config.Service.Port)
  165. if err != nil {
  166. return nil, fmt.Errorf("service port cannot be converted to int: %w", err)
  167. }
  168. if port < math.MinInt32 || port > math.MaxInt32 {
  169. return nil, fmt.Errorf("port is out of range of int32")
  170. }
  171. // nolint:gosec
  172. serviceProto.Port = int32(port)
  173. }
  174. switch serviceType {
  175. default:
  176. return nil, fmt.Errorf("invalid service type '%s'", serviceType)
  177. case porterv1.ServiceType_SERVICE_TYPE_UNSPECIFIED:
  178. return nil, errors.New("service type unspecified")
  179. case porterv1.ServiceType_SERVICE_TYPE_WEB:
  180. webConfig, err := webConfigProtoFromConfig(service)
  181. if err != nil {
  182. return nil, fmt.Errorf("error converting web config: %w", err)
  183. }
  184. serviceProto.Config = &porterv1.Service_WebConfig{
  185. WebConfig: webConfig,
  186. }
  187. case porterv1.ServiceType_SERVICE_TYPE_WORKER:
  188. workerConfig, err := workerConfigProtoFromConfig(service)
  189. if err != nil {
  190. return nil, fmt.Errorf("error converting worker config: %w", err)
  191. }
  192. serviceProto.Config = &porterv1.Service_WorkerConfig{
  193. WorkerConfig: workerConfig,
  194. }
  195. case porterv1.ServiceType_SERVICE_TYPE_JOB:
  196. jobConfig := &porterv1.JobServiceConfig{
  197. AllowConcurrentOptional: service.Config.AllowConcurrency,
  198. Cron: service.Config.Schedule.Value,
  199. }
  200. serviceProto.Config = &porterv1.Service_JobConfig{
  201. JobConfig: jobConfig,
  202. }
  203. }
  204. return serviceProto, nil
  205. }
  206. func workerConfigProtoFromConfig(service Service) (*porterv1.WorkerServiceConfig, error) {
  207. workerConfig := &porterv1.WorkerServiceConfig{}
  208. var autoscaling *porterv1.Autoscaling
  209. if service.Config.Autoscaling != nil && service.Config.Autoscaling.Enabled {
  210. autoscaling = &porterv1.Autoscaling{
  211. Enabled: service.Config.Autoscaling.Enabled,
  212. }
  213. minReplicas, _ := strconv.Atoi(service.Config.Autoscaling.MinReplicas)
  214. if minReplicas < math.MinInt32 || minReplicas > math.MaxInt32 {
  215. return nil, fmt.Errorf("minReplicas is out of range of int32")
  216. }
  217. // nolint:gosec
  218. autoscaling.MinInstances = int32(minReplicas)
  219. maxReplicas, _ := strconv.Atoi(service.Config.Autoscaling.MaxReplicas)
  220. if maxReplicas < math.MinInt32 || maxReplicas > math.MaxInt32 {
  221. return nil, fmt.Errorf("maxReplicas is out of range of int32")
  222. }
  223. // nolint:gosec
  224. autoscaling.MaxInstances = int32(maxReplicas)
  225. cpuThresholdPercent, _ := strconv.Atoi(service.Config.Autoscaling.TargetCPUUtilizationPercentage)
  226. if cpuThresholdPercent < math.MinInt32 || cpuThresholdPercent > math.MaxInt32 {
  227. return nil, fmt.Errorf("cpuThresholdPercent is out of range of int32")
  228. }
  229. // nolint:gosec
  230. autoscaling.CpuThresholdPercent = int32(cpuThresholdPercent)
  231. memoryThresholdPercent, _ := strconv.Atoi(service.Config.Autoscaling.TargetMemoryUtilizationPercentage)
  232. if memoryThresholdPercent < math.MinInt32 || memoryThresholdPercent > math.MaxInt32 {
  233. return nil, fmt.Errorf("memoryThresholdPercent is out of range of int32")
  234. }
  235. // nolint:gosec
  236. autoscaling.MemoryThresholdPercent = int32(memoryThresholdPercent)
  237. }
  238. workerConfig.Autoscaling = autoscaling
  239. return workerConfig, nil
  240. }
  241. func webConfigProtoFromConfig(service Service) (*porterv1.WebServiceConfig, error) {
  242. webConfig := &porterv1.WebServiceConfig{}
  243. var autoscaling *porterv1.Autoscaling
  244. if service.Config.Autoscaling != nil && service.Config.Autoscaling.Enabled {
  245. autoscaling = &porterv1.Autoscaling{
  246. Enabled: service.Config.Autoscaling.Enabled,
  247. }
  248. minReplicas, _ := strconv.Atoi(service.Config.Autoscaling.MinReplicas)
  249. if minReplicas < math.MinInt32 || minReplicas > math.MaxInt32 {
  250. return nil, errors.New("minReplicas is out of range of int32")
  251. }
  252. // nolint:gosec
  253. autoscaling.MinInstances = int32(minReplicas)
  254. maxReplicas, _ := strconv.Atoi(service.Config.Autoscaling.MaxReplicas)
  255. if maxReplicas < math.MinInt32 || maxReplicas > math.MaxInt32 {
  256. return nil, errors.New("maxReplicas is out of range of int32")
  257. }
  258. // nolint:gosec
  259. autoscaling.MaxInstances = int32(maxReplicas)
  260. cpuThresholdPercent, _ := strconv.Atoi(service.Config.Autoscaling.TargetCPUUtilizationPercentage)
  261. if cpuThresholdPercent < math.MinInt32 || cpuThresholdPercent > math.MaxInt32 {
  262. return nil, fmt.Errorf("cpuThresholdPercent is out of range of int32")
  263. }
  264. // nolint:gosec
  265. autoscaling.CpuThresholdPercent = int32(cpuThresholdPercent)
  266. memoryThresholdPercent, _ := strconv.Atoi(service.Config.Autoscaling.TargetMemoryUtilizationPercentage)
  267. if memoryThresholdPercent < math.MinInt32 || memoryThresholdPercent > math.MaxInt32 {
  268. return nil, fmt.Errorf("memoryThresholdPercent is out of range of int32")
  269. }
  270. // nolint:gosec
  271. autoscaling.MemoryThresholdPercent = int32(memoryThresholdPercent)
  272. }
  273. webConfig.Autoscaling = autoscaling
  274. var healthCheck *porterv1.HealthCheck
  275. // note that we are only reading from the readiness probe config, since readiness and liveness share the same config now
  276. if service.Config.Health != nil {
  277. health := service.Config.Health
  278. if health.ReadinessProbe.Enabled && health.LivenessProbe.Enabled && health.ReadinessProbe.Path != health.LivenessProbe.Path {
  279. return nil, errors.New("liveness and readiness probes must have the same path")
  280. }
  281. if health.ReadinessProbe.Enabled {
  282. healthCheck = &porterv1.HealthCheck{
  283. Enabled: service.Config.Health.ReadinessProbe.Enabled,
  284. HttpPath: service.Config.Health.ReadinessProbe.Path,
  285. }
  286. } else if health.LivenessProbe.Enabled {
  287. healthCheck = &porterv1.HealthCheck{
  288. Enabled: service.Config.Health.LivenessProbe.Enabled,
  289. HttpPath: service.Config.Health.LivenessProbe.Path,
  290. }
  291. }
  292. }
  293. webConfig.HealthCheck = healthCheck
  294. if service.Config.Ingress != nil {
  295. domains := make([]*porterv1.Domain, 0)
  296. for _, domain := range service.Config.Ingress.Hosts {
  297. hostName := domain
  298. domains = append(domains, &porterv1.Domain{
  299. Name: hostName,
  300. })
  301. }
  302. for _, domain := range service.Config.Ingress.PorterHosts {
  303. hostName := domain
  304. domains = append(domains, &porterv1.Domain{
  305. Name: hostName,
  306. })
  307. }
  308. if service.Config.Ingress.Annotations != nil && len(service.Config.Ingress.Annotations) > 0 {
  309. return nil, errors.New("annotations are not supported")
  310. }
  311. webConfig.Domains = domains
  312. private := !service.Config.Ingress.Enabled
  313. webConfig.Private = &private
  314. }
  315. return webConfig, nil
  316. }