yaml.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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_WORKER
  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 the revision number cannot be converted, it will default to 0
  112. replicaCount, _ := strconv.Atoi(service.Config.ReplicaCount)
  113. if replicaCount < math.MinInt32 || replicaCount > math.MaxInt32 {
  114. return nil, fmt.Errorf("replica count is out of range of int32")
  115. }
  116. // nolint:gosec
  117. serviceProto.Instances = int32(replicaCount)
  118. if service.Config.Resources.Requests.Cpu != "" {
  119. cpuCoresStr := service.Config.Resources.Requests.Cpu
  120. if !strings.HasSuffix(cpuCoresStr, "m") {
  121. return nil, fmt.Errorf("cpu is not in millicores")
  122. }
  123. cpuCoresStr = strings.TrimSuffix(cpuCoresStr, "m")
  124. cpuCoresFloat64, err := strconv.ParseFloat(cpuCoresStr, 32)
  125. if err != nil {
  126. return nil, fmt.Errorf("cpu is not a float")
  127. }
  128. serviceProto.CpuCores = float32(cpuCoresFloat64) / 1000
  129. }
  130. if service.Config.Resources.Requests.Memory != "" {
  131. memoryStr := service.Config.Resources.Requests.Memory
  132. if !strings.HasSuffix(memoryStr, "Mi") {
  133. return nil, fmt.Errorf("memory is not in Mi")
  134. }
  135. memoryStr = strings.TrimSuffix(memoryStr, "Mi")
  136. memoryFloat64, err := strconv.ParseFloat(memoryStr, 32)
  137. if err != nil {
  138. return nil, fmt.Errorf("memory is not a float")
  139. }
  140. // nolint:gosec
  141. serviceProto.RamMegabytes = int32(memoryFloat64)
  142. }
  143. if service.Config.Container.Port != "" && service.Config.Service.Port != "" && service.Config.Container.Port != service.Config.Service.Port {
  144. return nil, errors.New("container port and service port do not match")
  145. }
  146. if service.Config.Container.Port != "" {
  147. port, err := strconv.Atoi(service.Config.Container.Port)
  148. if err != nil {
  149. return nil, fmt.Errorf("container port cannot be converted to int: %w", err)
  150. }
  151. if port < math.MinInt32 || port > math.MaxInt32 {
  152. return nil, fmt.Errorf("port is out of range of int32")
  153. }
  154. // nolint:gosec
  155. serviceProto.Port = int32(port)
  156. }
  157. if service.Config.Service.Port != "" {
  158. port, err := strconv.Atoi(service.Config.Service.Port)
  159. if err != nil {
  160. return nil, fmt.Errorf("service port cannot be converted to int: %w", err)
  161. }
  162. if port < math.MinInt32 || port > math.MaxInt32 {
  163. return nil, fmt.Errorf("port is out of range of int32")
  164. }
  165. // nolint:gosec
  166. serviceProto.Port = int32(port)
  167. }
  168. switch serviceType {
  169. default:
  170. return nil, fmt.Errorf("invalid service type '%s'", serviceType)
  171. case porterv1.ServiceType_SERVICE_TYPE_UNSPECIFIED:
  172. return nil, errors.New("KubernetesService type unspecified")
  173. case porterv1.ServiceType_SERVICE_TYPE_WEB:
  174. webConfig, err := webConfigProtoFromConfig(service)
  175. if err != nil {
  176. return nil, fmt.Errorf("error converting web config: %w", err)
  177. }
  178. serviceProto.Config = &porterv1.Service_WebConfig{
  179. WebConfig: webConfig,
  180. }
  181. case porterv1.ServiceType_SERVICE_TYPE_WORKER:
  182. workerConfig, err := workerConfigProtoFromConfig(service)
  183. if err != nil {
  184. return nil, fmt.Errorf("error converting worker config: %w", err)
  185. }
  186. serviceProto.Config = &porterv1.Service_WorkerConfig{
  187. WorkerConfig: workerConfig,
  188. }
  189. case porterv1.ServiceType_SERVICE_TYPE_JOB:
  190. jobConfig := &porterv1.JobServiceConfig{
  191. AllowConcurrent: service.Config.AllowConcurrency,
  192. Cron: service.Config.Schedule.Value,
  193. }
  194. serviceProto.Config = &porterv1.Service_JobConfig{
  195. JobConfig: jobConfig,
  196. }
  197. }
  198. return serviceProto, nil
  199. }
  200. func workerConfigProtoFromConfig(service Service) (*porterv1.WorkerServiceConfig, error) {
  201. workerConfig := &porterv1.WorkerServiceConfig{}
  202. var autoscaling *porterv1.Autoscaling
  203. if service.Config.Autoscaling != nil && service.Config.Autoscaling.Enabled {
  204. autoscaling = &porterv1.Autoscaling{
  205. Enabled: service.Config.Autoscaling.Enabled,
  206. }
  207. minReplicas, _ := strconv.Atoi(service.Config.Autoscaling.MinReplicas)
  208. if minReplicas < math.MinInt32 || minReplicas > math.MaxInt32 {
  209. return nil, fmt.Errorf("minReplicas is out of range of int32")
  210. }
  211. // nolint:gosec
  212. autoscaling.MinInstances = int32(minReplicas)
  213. maxReplicas, _ := strconv.Atoi(service.Config.Autoscaling.MaxReplicas)
  214. if maxReplicas < math.MinInt32 || maxReplicas > math.MaxInt32 {
  215. return nil, fmt.Errorf("maxReplicas is out of range of int32")
  216. }
  217. // nolint:gosec
  218. autoscaling.MaxInstances = int32(maxReplicas)
  219. cpuThresholdPercent, _ := strconv.Atoi(service.Config.Autoscaling.TargetCPUUtilizationPercentage)
  220. if cpuThresholdPercent < math.MinInt32 || cpuThresholdPercent > math.MaxInt32 {
  221. return nil, fmt.Errorf("cpuThresholdPercent is out of range of int32")
  222. }
  223. // nolint:gosec
  224. autoscaling.CpuThresholdPercent = int32(cpuThresholdPercent)
  225. memoryThresholdPercent, _ := strconv.Atoi(service.Config.Autoscaling.TargetMemoryUtilizationPercentage)
  226. if memoryThresholdPercent < math.MinInt32 || memoryThresholdPercent > math.MaxInt32 {
  227. return nil, fmt.Errorf("memoryThresholdPercent is out of range of int32")
  228. }
  229. // nolint:gosec
  230. autoscaling.MemoryThresholdPercent = int32(memoryThresholdPercent)
  231. }
  232. workerConfig.Autoscaling = autoscaling
  233. return workerConfig, nil
  234. }
  235. func webConfigProtoFromConfig(service Service) (*porterv1.WebServiceConfig, error) {
  236. webConfig := &porterv1.WebServiceConfig{}
  237. var autoscaling *porterv1.Autoscaling
  238. if service.Config.Autoscaling != nil && service.Config.Autoscaling.Enabled {
  239. autoscaling = &porterv1.Autoscaling{
  240. Enabled: service.Config.Autoscaling.Enabled,
  241. }
  242. minReplicas, _ := strconv.Atoi(service.Config.Autoscaling.MinReplicas)
  243. if minReplicas < math.MinInt32 || minReplicas > math.MaxInt32 {
  244. return nil, errors.New("minReplicas is out of range of int32")
  245. }
  246. // nolint:gosec
  247. autoscaling.MinInstances = int32(minReplicas)
  248. maxReplicas, _ := strconv.Atoi(service.Config.Autoscaling.MaxReplicas)
  249. if maxReplicas < math.MinInt32 || maxReplicas > math.MaxInt32 {
  250. return nil, errors.New("maxReplicas is out of range of int32")
  251. }
  252. // nolint:gosec
  253. autoscaling.MaxInstances = int32(maxReplicas)
  254. cpuThresholdPercent, _ := strconv.Atoi(service.Config.Autoscaling.TargetCPUUtilizationPercentage)
  255. if cpuThresholdPercent < math.MinInt32 || cpuThresholdPercent > math.MaxInt32 {
  256. return nil, fmt.Errorf("cpuThresholdPercent is out of range of int32")
  257. }
  258. // nolint:gosec
  259. autoscaling.CpuThresholdPercent = int32(cpuThresholdPercent)
  260. memoryThresholdPercent, _ := strconv.Atoi(service.Config.Autoscaling.TargetMemoryUtilizationPercentage)
  261. if memoryThresholdPercent < math.MinInt32 || memoryThresholdPercent > math.MaxInt32 {
  262. return nil, fmt.Errorf("memoryThresholdPercent is out of range of int32")
  263. }
  264. // nolint:gosec
  265. autoscaling.MemoryThresholdPercent = int32(memoryThresholdPercent)
  266. }
  267. webConfig.Autoscaling = autoscaling
  268. var healthCheck *porterv1.HealthCheck
  269. // note that we are only reading from the readiness probe config, since readiness and liveness share the same config now
  270. if service.Config.Health != nil {
  271. health := service.Config.Health
  272. if health.ReadinessProbe.Enabled && health.LivenessProbe.Enabled && health.ReadinessProbe.Path != health.LivenessProbe.Path {
  273. return nil, errors.New("liveness and readiness probes must have the same path")
  274. }
  275. if health.ReadinessProbe.Enabled {
  276. healthCheck = &porterv1.HealthCheck{
  277. Enabled: service.Config.Health.ReadinessProbe.Enabled,
  278. HttpPath: service.Config.Health.ReadinessProbe.Path,
  279. }
  280. } else if health.LivenessProbe.Enabled {
  281. healthCheck = &porterv1.HealthCheck{
  282. Enabled: service.Config.Health.LivenessProbe.Enabled,
  283. HttpPath: service.Config.Health.LivenessProbe.Path,
  284. }
  285. }
  286. }
  287. webConfig.HealthCheck = healthCheck
  288. if service.Config.Ingress != nil {
  289. domains := make([]*porterv1.Domain, 0)
  290. for _, domain := range service.Config.Ingress.Hosts {
  291. hostName := domain
  292. domains = append(domains, &porterv1.Domain{
  293. Name: hostName,
  294. })
  295. }
  296. for _, domain := range service.Config.Ingress.PorterHosts {
  297. hostName := domain
  298. domains = append(domains, &porterv1.Domain{
  299. Name: hostName,
  300. })
  301. }
  302. if service.Config.Ingress.Annotations != nil && len(service.Config.Ingress.Annotations) > 0 {
  303. return nil, errors.New("annotations are not supported")
  304. }
  305. webConfig.Domains = domains
  306. private := !service.Config.Ingress.Enabled
  307. webConfig.Private = &private
  308. }
  309. return webConfig, nil
  310. }