kube.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. // +build kube
  2. /*
  3. Copyright 2020 Docker Compose CLI authors
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package resources
  15. import (
  16. "fmt"
  17. "log"
  18. "strings"
  19. "time"
  20. "github.com/compose-spec/compose-go/types"
  21. "github.com/docker/compose-cli/pkg/api"
  22. apps "k8s.io/api/apps/v1"
  23. core "k8s.io/api/core/v1"
  24. resource "k8s.io/apimachinery/pkg/api/resource"
  25. meta "k8s.io/apimachinery/pkg/apis/meta/v1"
  26. "k8s.io/apimachinery/pkg/runtime"
  27. "k8s.io/apimachinery/pkg/util/intstr"
  28. )
  29. const (
  30. clusterIPHeadless = "None"
  31. )
  32. //MapToKubernetesObjects maps compose project to Kubernetes objects
  33. func MapToKubernetesObjects(project *types.Project) (map[string]runtime.Object, error) {
  34. objects := map[string]runtime.Object{}
  35. secrets, err := toSecretSpecs(project)
  36. if err != nil {
  37. return nil, err
  38. }
  39. if len(secrets) > 0 {
  40. for _, secret := range secrets {
  41. name := secret.Name[len(project.Name)+1:]
  42. objects[fmt.Sprintf("%s-secret.yaml", name)] = &secret
  43. }
  44. }
  45. for _, service := range project.Services {
  46. svcObject := mapToService(project, service)
  47. if svcObject != nil {
  48. objects[fmt.Sprintf("%s-service.yaml", service.Name)] = svcObject
  49. } else {
  50. log.Println("Missing port mapping from service config.")
  51. }
  52. if service.Deploy != nil && service.Deploy.Mode == "global" {
  53. daemonset, err := mapToDaemonset(project, service)
  54. if err != nil {
  55. return nil, err
  56. }
  57. objects[fmt.Sprintf("%s-daemonset.yaml", service.Name)] = daemonset
  58. } else {
  59. deployment, err := mapToDeployment(project, service)
  60. if err != nil {
  61. return nil, err
  62. }
  63. objects[fmt.Sprintf("%s-deployment.yaml", service.Name)] = deployment
  64. }
  65. for _, vol := range service.Volumes {
  66. if vol.Type == "volume" {
  67. vol.Source = strings.ReplaceAll(vol.Source, "_", "-")
  68. objects[fmt.Sprintf("%s-persistentvolumeclaim.yaml", vol.Source)] = mapToPVC(project, service, vol)
  69. }
  70. }
  71. }
  72. return objects, nil
  73. }
  74. func mapToService(project *types.Project, service types.ServiceConfig) *core.Service {
  75. ports := []core.ServicePort{}
  76. serviceType := core.ServiceTypeClusterIP
  77. clusterIP := ""
  78. for _, p := range service.Ports {
  79. if p.Published != 0 {
  80. serviceType = core.ServiceTypeLoadBalancer
  81. }
  82. protocol := toProtocol(p.Protocol)
  83. ports = append(ports,
  84. core.ServicePort{
  85. Name: fmt.Sprintf("%d-%s", p.Published, strings.ToLower(string(protocol))),
  86. Port: int32(p.Published),
  87. TargetPort: intstr.FromInt(int(p.Target)),
  88. Protocol: protocol,
  89. })
  90. }
  91. if len(ports) == 0 { // headless service
  92. clusterIP = clusterIPHeadless
  93. }
  94. return &core.Service{
  95. TypeMeta: meta.TypeMeta{
  96. Kind: "Service",
  97. APIVersion: "v1",
  98. },
  99. ObjectMeta: meta.ObjectMeta{
  100. Name: service.Name,
  101. },
  102. Spec: core.ServiceSpec{
  103. ClusterIP: clusterIP,
  104. Selector: selectorLabels(project.Name, service.Name),
  105. Ports: ports,
  106. Type: serviceType,
  107. },
  108. }
  109. }
  110. func mapToDeployment(project *types.Project, service types.ServiceConfig) (*apps.Deployment, error) {
  111. labels := selectorLabels(project.Name, service.Name)
  112. selector := new(meta.LabelSelector)
  113. selector.MatchLabels = make(map[string]string)
  114. for key, val := range labels {
  115. selector.MatchLabels[key] = val
  116. }
  117. podTemplate, err := toPodTemplate(project, service, labels)
  118. if err != nil {
  119. return nil, err
  120. }
  121. return &apps.Deployment{
  122. TypeMeta: meta.TypeMeta{
  123. Kind: "Deployment",
  124. APIVersion: "apps/v1",
  125. },
  126. ObjectMeta: meta.ObjectMeta{
  127. Name: service.Name,
  128. Labels: labels,
  129. },
  130. Spec: apps.DeploymentSpec{
  131. Selector: selector,
  132. Replicas: toReplicas(service.Deploy),
  133. Strategy: toDeploymentStrategy(service.Deploy),
  134. Template: podTemplate,
  135. },
  136. }, nil
  137. }
  138. func selectorLabels(projectName string, serviceName string) map[string]string {
  139. return map[string]string{
  140. api.ProjectLabel: projectName,
  141. api.ServiceLabel: serviceName,
  142. }
  143. }
  144. func mapToDaemonset(project *types.Project, service types.ServiceConfig) (*apps.DaemonSet, error) {
  145. labels := selectorLabels(project.Name, service.Name)
  146. podTemplate, err := toPodTemplate(project, service, labels)
  147. if err != nil {
  148. return nil, err
  149. }
  150. return &apps.DaemonSet{
  151. ObjectMeta: meta.ObjectMeta{
  152. Name: service.Name,
  153. Labels: labels,
  154. },
  155. Spec: apps.DaemonSetSpec{
  156. Template: podTemplate,
  157. },
  158. }, nil
  159. }
  160. func toReplicas(deploy *types.DeployConfig) *int32 {
  161. v := int32(1)
  162. if deploy != nil {
  163. v = int32(*deploy.Replicas)
  164. }
  165. return &v
  166. }
  167. func toDeploymentStrategy(deploy *types.DeployConfig) apps.DeploymentStrategy {
  168. if deploy == nil || deploy.UpdateConfig == nil {
  169. return apps.DeploymentStrategy{
  170. Type: apps.RecreateDeploymentStrategyType,
  171. }
  172. }
  173. return apps.DeploymentStrategy{
  174. Type: apps.RollingUpdateDeploymentStrategyType,
  175. RollingUpdate: &apps.RollingUpdateDeployment{
  176. MaxUnavailable: &intstr.IntOrString{
  177. Type: intstr.Int,
  178. IntVal: int32(*deploy.UpdateConfig.Parallelism),
  179. },
  180. MaxSurge: nil,
  181. },
  182. }
  183. }
  184. func mapToPVC(project *types.Project, service types.ServiceConfig, vol types.ServiceVolumeConfig) runtime.Object {
  185. rwaccess := core.ReadWriteOnce
  186. if vol.ReadOnly {
  187. rwaccess = core.ReadOnlyMany
  188. }
  189. return &core.PersistentVolumeClaim{
  190. TypeMeta: meta.TypeMeta{
  191. Kind: "PersistentVolumeClaim",
  192. APIVersion: "v1",
  193. },
  194. ObjectMeta: meta.ObjectMeta{
  195. Name: vol.Source,
  196. Labels: selectorLabels(project.Name, service.Name),
  197. },
  198. Spec: core.PersistentVolumeClaimSpec{
  199. VolumeName: vol.Source,
  200. AccessModes: []core.PersistentVolumeAccessMode{rwaccess},
  201. Resources: core.ResourceRequirements{
  202. Requests: core.ResourceList{
  203. core.ResourceStorage: resource.MustParse("100Mi"),
  204. },
  205. },
  206. },
  207. }
  208. }
  209. // toSecondsOrDefault converts a duration string in seconds and defaults to a
  210. // given value if the duration is nil.
  211. // The supported units are us, ms, s, m and h.
  212. func toSecondsOrDefault(duration *types.Duration, defaultValue int32) int32 { //nolint: unparam
  213. if duration == nil {
  214. return defaultValue
  215. }
  216. return int32(time.Duration(*duration).Seconds())
  217. }