yaml.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. serviceProtoMap := make(map[string]*porterv1.Service, 0)
  61. for name, service := range services {
  62. serviceType := protoEnumFromType(name, service)
  63. serviceProto, err := serviceProtoFromConfig(service, serviceType)
  64. if err != nil {
  65. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "failing-service-name", Value: name})
  66. return nil, nil, telemetry.Error(ctx, span, err, "error casting service config")
  67. }
  68. serviceProtoMap[name] = serviceProto
  69. }
  70. appProto.Services = serviceProtoMap
  71. if porterYaml.Release != nil {
  72. predeployProto, err := serviceProtoFromConfig(*porterYaml.Release, porterv1.ServiceType_SERVICE_TYPE_JOB)
  73. if err != nil {
  74. return nil, nil, telemetry.Error(ctx, span, err, "error casting predeploy config")
  75. }
  76. appProto.Predeploy = predeployProto
  77. }
  78. return appProto, porterYaml.Env, nil
  79. }
  80. func protoEnumFromType(name string, service Service) porterv1.ServiceType {
  81. serviceType := porterv1.ServiceType_SERVICE_TYPE_WORKER
  82. if strings.Contains(name, "web") {
  83. serviceType = porterv1.ServiceType_SERVICE_TYPE_WEB
  84. }
  85. if strings.Contains(name, "wkr") || strings.Contains(name, "worker") {
  86. serviceType = porterv1.ServiceType_SERVICE_TYPE_WORKER
  87. }
  88. if strings.Contains(name, "job") {
  89. serviceType = porterv1.ServiceType_SERVICE_TYPE_JOB
  90. }
  91. switch service.Type {
  92. case "web":
  93. serviceType = porterv1.ServiceType_SERVICE_TYPE_WEB
  94. case "worker":
  95. serviceType = porterv1.ServiceType_SERVICE_TYPE_WORKER
  96. case "job":
  97. serviceType = porterv1.ServiceType_SERVICE_TYPE_JOB
  98. }
  99. return serviceType
  100. }
  101. func serviceProtoFromConfig(service Service, serviceType porterv1.ServiceType) (*porterv1.Service, error) {
  102. serviceProto := &porterv1.Service{
  103. RunOptional: service.Run,
  104. Type: serviceType,
  105. }
  106. // if the revision number cannot be converted, it will default to 0
  107. replicaCount, _ := strconv.Atoi(service.Config.ReplicaCount)
  108. if replicaCount < math.MinInt32 || replicaCount > math.MaxInt32 {
  109. return nil, fmt.Errorf("replica count is out of range of int32")
  110. }
  111. // nolint:gosec
  112. serviceProto.Instances = int32(replicaCount)
  113. if service.Config.Resources.Requests.Cpu != "" {
  114. cpuCoresStr := service.Config.Resources.Requests.Cpu
  115. if !strings.HasSuffix(cpuCoresStr, "m") {
  116. return nil, fmt.Errorf("cpu is not in millicores")
  117. }
  118. cpuCoresStr = strings.TrimSuffix(cpuCoresStr, "m")
  119. cpuCoresFloat64, err := strconv.ParseFloat(cpuCoresStr, 32)
  120. if err != nil {
  121. return nil, fmt.Errorf("cpu is not a float")
  122. }
  123. serviceProto.CpuCores = float32(cpuCoresFloat64) / 1000
  124. }
  125. if service.Config.Resources.Requests.Memory != "" {
  126. memoryStr := service.Config.Resources.Requests.Memory
  127. if !strings.HasSuffix(memoryStr, "Mi") {
  128. return nil, fmt.Errorf("memory is not in Mi")
  129. }
  130. memoryStr = strings.TrimSuffix(memoryStr, "Mi")
  131. memoryFloat64, err := strconv.ParseFloat(memoryStr, 32)
  132. if err != nil {
  133. return nil, fmt.Errorf("memory is not a float")
  134. }
  135. // nolint:gosec
  136. serviceProto.RamMegabytes = int32(memoryFloat64)
  137. }
  138. if service.Config.Container.Port != "" && service.Config.Service.Port != "" && service.Config.Container.Port != service.Config.Service.Port {
  139. return nil, errors.New("container port and service port do not match")
  140. }
  141. if service.Config.Container.Port != "" {
  142. port, err := strconv.Atoi(service.Config.Container.Port)
  143. if err != nil {
  144. return nil, fmt.Errorf("container port cannot be converted to int: %w", err)
  145. }
  146. if port < math.MinInt32 || port > math.MaxInt32 {
  147. return nil, fmt.Errorf("port is out of range of int32")
  148. }
  149. // nolint:gosec
  150. serviceProto.Port = int32(port)
  151. }
  152. if service.Config.Service.Port != "" {
  153. port, err := strconv.Atoi(service.Config.Service.Port)
  154. if err != nil {
  155. return nil, fmt.Errorf("service 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. switch serviceType {
  164. default:
  165. return nil, fmt.Errorf("invalid service type '%s'", serviceType)
  166. case porterv1.ServiceType_SERVICE_TYPE_UNSPECIFIED:
  167. return nil, errors.New("KubernetesService type unspecified")
  168. case porterv1.ServiceType_SERVICE_TYPE_WEB:
  169. webConfig, err := webConfigProtoFromConfig(service)
  170. if err != nil {
  171. return nil, fmt.Errorf("error converting web config: %w", err)
  172. }
  173. serviceProto.Config = &porterv1.Service_WebConfig{
  174. WebConfig: webConfig,
  175. }
  176. case porterv1.ServiceType_SERVICE_TYPE_WORKER:
  177. workerConfig, err := workerConfigProtoFromConfig(service)
  178. if err != nil {
  179. return nil, fmt.Errorf("error converting worker config: %w", err)
  180. }
  181. serviceProto.Config = &porterv1.Service_WorkerConfig{
  182. WorkerConfig: workerConfig,
  183. }
  184. case porterv1.ServiceType_SERVICE_TYPE_JOB:
  185. jobConfig := &porterv1.JobServiceConfig{
  186. AllowConcurrent: service.Config.AllowConcurrency,
  187. Cron: service.Config.Schedule.Value,
  188. }
  189. serviceProto.Config = &porterv1.Service_JobConfig{
  190. JobConfig: jobConfig,
  191. }
  192. }
  193. return serviceProto, nil
  194. }
  195. func workerConfigProtoFromConfig(service Service) (*porterv1.WorkerServiceConfig, error) {
  196. workerConfig := &porterv1.WorkerServiceConfig{}
  197. var autoscaling *porterv1.Autoscaling
  198. if service.Config.Autoscaling != nil && service.Config.Autoscaling.Enabled {
  199. autoscaling = &porterv1.Autoscaling{
  200. Enabled: service.Config.Autoscaling.Enabled,
  201. }
  202. minReplicas, _ := strconv.Atoi(service.Config.Autoscaling.MinReplicas)
  203. if minReplicas < math.MinInt32 || minReplicas > math.MaxInt32 {
  204. return nil, fmt.Errorf("minReplicas is out of range of int32")
  205. }
  206. // nolint:gosec
  207. autoscaling.MinInstances = int32(minReplicas)
  208. maxReplicas, _ := strconv.Atoi(service.Config.Autoscaling.MaxReplicas)
  209. if maxReplicas < math.MinInt32 || maxReplicas > math.MaxInt32 {
  210. return nil, fmt.Errorf("maxReplicas is out of range of int32")
  211. }
  212. // nolint:gosec
  213. autoscaling.MaxInstances = int32(maxReplicas)
  214. cpuThresholdPercent, _ := strconv.Atoi(service.Config.Autoscaling.TargetCPUUtilizationPercentage)
  215. if cpuThresholdPercent < math.MinInt32 || cpuThresholdPercent > math.MaxInt32 {
  216. return nil, fmt.Errorf("cpuThresholdPercent is out of range of int32")
  217. }
  218. // nolint:gosec
  219. autoscaling.CpuThresholdPercent = int32(cpuThresholdPercent)
  220. memoryThresholdPercent, _ := strconv.Atoi(service.Config.Autoscaling.TargetMemoryUtilizationPercentage)
  221. if memoryThresholdPercent < math.MinInt32 || memoryThresholdPercent > math.MaxInt32 {
  222. return nil, fmt.Errorf("memoryThresholdPercent is out of range of int32")
  223. }
  224. // nolint:gosec
  225. autoscaling.MemoryThresholdPercent = int32(memoryThresholdPercent)
  226. }
  227. workerConfig.Autoscaling = autoscaling
  228. return workerConfig, nil
  229. }
  230. func webConfigProtoFromConfig(service Service) (*porterv1.WebServiceConfig, error) {
  231. webConfig := &porterv1.WebServiceConfig{}
  232. var autoscaling *porterv1.Autoscaling
  233. if service.Config.Autoscaling != nil && service.Config.Autoscaling.Enabled {
  234. autoscaling = &porterv1.Autoscaling{
  235. Enabled: service.Config.Autoscaling.Enabled,
  236. }
  237. minReplicas, _ := strconv.Atoi(service.Config.Autoscaling.MinReplicas)
  238. if minReplicas < math.MinInt32 || minReplicas > math.MaxInt32 {
  239. return nil, errors.New("minReplicas is out of range of int32")
  240. }
  241. // nolint:gosec
  242. autoscaling.MinInstances = int32(minReplicas)
  243. maxReplicas, _ := strconv.Atoi(service.Config.Autoscaling.MaxReplicas)
  244. if maxReplicas < math.MinInt32 || maxReplicas > math.MaxInt32 {
  245. return nil, errors.New("maxReplicas is out of range of int32")
  246. }
  247. // nolint:gosec
  248. autoscaling.MaxInstances = int32(maxReplicas)
  249. cpuThresholdPercent, _ := strconv.Atoi(service.Config.Autoscaling.TargetCPUUtilizationPercentage)
  250. if cpuThresholdPercent < math.MinInt32 || cpuThresholdPercent > math.MaxInt32 {
  251. return nil, fmt.Errorf("cpuThresholdPercent is out of range of int32")
  252. }
  253. // nolint:gosec
  254. autoscaling.CpuThresholdPercent = int32(cpuThresholdPercent)
  255. memoryThresholdPercent, _ := strconv.Atoi(service.Config.Autoscaling.TargetMemoryUtilizationPercentage)
  256. if memoryThresholdPercent < math.MinInt32 || memoryThresholdPercent > math.MaxInt32 {
  257. return nil, fmt.Errorf("memoryThresholdPercent is out of range of int32")
  258. }
  259. // nolint:gosec
  260. autoscaling.MemoryThresholdPercent = int32(memoryThresholdPercent)
  261. }
  262. webConfig.Autoscaling = autoscaling
  263. var healthCheck *porterv1.HealthCheck
  264. // note that we are only reading from the readiness probe config, since readiness and liveness share the same config now
  265. if service.Config.Health != nil {
  266. health := service.Config.Health
  267. if health.ReadinessProbe.Enabled && health.LivenessProbe.Enabled && health.ReadinessProbe.Path != health.LivenessProbe.Path {
  268. return nil, errors.New("liveness and readiness probes must have the same path")
  269. }
  270. if health.ReadinessProbe.Enabled {
  271. healthCheck = &porterv1.HealthCheck{
  272. Enabled: service.Config.Health.ReadinessProbe.Enabled,
  273. HttpPath: service.Config.Health.ReadinessProbe.Path,
  274. }
  275. } else if health.LivenessProbe.Enabled {
  276. healthCheck = &porterv1.HealthCheck{
  277. Enabled: service.Config.Health.LivenessProbe.Enabled,
  278. HttpPath: service.Config.Health.LivenessProbe.Path,
  279. }
  280. }
  281. }
  282. webConfig.HealthCheck = healthCheck
  283. if service.Config.Ingress != nil {
  284. domains := make([]*porterv1.Domain, 0)
  285. for _, domain := range service.Config.Ingress.Hosts {
  286. hostName := domain
  287. domains = append(domains, &porterv1.Domain{
  288. Name: hostName,
  289. })
  290. }
  291. for _, domain := range service.Config.Ingress.PorterHosts {
  292. hostName := domain
  293. domains = append(domains, &porterv1.Domain{
  294. Name: hostName,
  295. })
  296. }
  297. if service.Config.Ingress.Annotations != nil && len(service.Config.Ingress.Annotations) > 0 {
  298. return nil, errors.New("annotations are not supported")
  299. }
  300. webConfig.Domains = domains
  301. private := !service.Config.Ingress.Enabled
  302. webConfig.Private = &private
  303. }
  304. return webConfig, nil
  305. }