yaml.go 12 KB

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