yaml.go 12 KB

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