kube.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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/api/compose"
  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. for _, service := range project.Services {
  36. svcObject := mapToService(project, service)
  37. if svcObject != nil {
  38. objects[fmt.Sprintf("%s-service.yaml", service.Name)] = svcObject
  39. } else {
  40. log.Println("Missing port mapping from service config.")
  41. }
  42. if service.Deploy != nil && service.Deploy.Mode == "global" {
  43. daemonset, err := mapToDaemonset(project, service)
  44. if err != nil {
  45. return nil, err
  46. }
  47. objects[fmt.Sprintf("%s-daemonset.yaml", service.Name)] = daemonset
  48. } else {
  49. deployment, err := mapToDeployment(project, service)
  50. if err != nil {
  51. return nil, err
  52. }
  53. objects[fmt.Sprintf("%s-deployment.yaml", service.Name)] = deployment
  54. }
  55. for _, vol := range service.Volumes {
  56. if vol.Type == "volume" {
  57. vol.Source = strings.ReplaceAll(vol.Source, "_", "-")
  58. objects[fmt.Sprintf("%s-persistentvolumeclaim.yaml", vol.Source)] = mapToPVC(project, service, vol)
  59. }
  60. }
  61. }
  62. return objects, nil
  63. }
  64. func mapToService(project *types.Project, service types.ServiceConfig) *core.Service {
  65. ports := []core.ServicePort{}
  66. serviceType := core.ServiceTypeClusterIP
  67. clusterIP := ""
  68. for _, p := range service.Ports {
  69. if p.Published != 0 {
  70. serviceType = core.ServiceTypeLoadBalancer
  71. }
  72. ports = append(ports,
  73. core.ServicePort{
  74. Name: fmt.Sprintf("%d-%s", p.Target, strings.ToLower(p.Protocol)),
  75. Port: int32(p.Target),
  76. TargetPort: intstr.FromInt(int(p.Target)),
  77. Protocol: toProtocol(p.Protocol),
  78. })
  79. }
  80. if len(ports) == 0 { // headless service
  81. clusterIP = clusterIPHeadless
  82. }
  83. return &core.Service{
  84. TypeMeta: meta.TypeMeta{
  85. Kind: "Service",
  86. APIVersion: "v1",
  87. },
  88. ObjectMeta: meta.ObjectMeta{
  89. Name: service.Name,
  90. },
  91. Spec: core.ServiceSpec{
  92. ClusterIP: clusterIP,
  93. Selector: selectorLabels(project.Name, service.Name),
  94. Ports: ports,
  95. Type: serviceType,
  96. },
  97. }
  98. }
  99. func mapToDeployment(project *types.Project, service types.ServiceConfig) (*apps.Deployment, error) {
  100. labels := selectorLabels(project.Name, service.Name)
  101. selector := new(meta.LabelSelector)
  102. selector.MatchLabels = make(map[string]string)
  103. for key, val := range labels {
  104. selector.MatchLabels[key] = val
  105. }
  106. podTemplate, err := toPodTemplate(project, service, labels)
  107. if err != nil {
  108. return nil, err
  109. }
  110. return &apps.Deployment{
  111. TypeMeta: meta.TypeMeta{
  112. Kind: "Deployment",
  113. APIVersion: "apps/v1",
  114. },
  115. ObjectMeta: meta.ObjectMeta{
  116. Name: service.Name,
  117. Labels: labels,
  118. },
  119. Spec: apps.DeploymentSpec{
  120. Selector: selector,
  121. Replicas: toReplicas(service.Deploy),
  122. Strategy: toDeploymentStrategy(service.Deploy),
  123. Template: podTemplate,
  124. },
  125. }, nil
  126. }
  127. func selectorLabels(projectName string, serviceName string) map[string]string {
  128. return map[string]string{
  129. compose.ProjectTag: projectName,
  130. compose.ServiceTag: serviceName,
  131. }
  132. }
  133. func mapToDaemonset(project *types.Project, service types.ServiceConfig) (*apps.DaemonSet, error) {
  134. labels := selectorLabels(project.Name, service.Name)
  135. podTemplate, err := toPodTemplate(project, service, labels)
  136. if err != nil {
  137. return nil, err
  138. }
  139. return &apps.DaemonSet{
  140. ObjectMeta: meta.ObjectMeta{
  141. Name: service.Name,
  142. Labels: labels,
  143. },
  144. Spec: apps.DaemonSetSpec{
  145. Template: podTemplate,
  146. },
  147. }, nil
  148. }
  149. func toReplicas(deploy *types.DeployConfig) *int32 {
  150. v := int32(1)
  151. if deploy != nil {
  152. v = int32(*deploy.Replicas)
  153. }
  154. return &v
  155. }
  156. func toDeploymentStrategy(deploy *types.DeployConfig) apps.DeploymentStrategy {
  157. if deploy == nil || deploy.UpdateConfig == nil {
  158. return apps.DeploymentStrategy{
  159. Type: apps.RecreateDeploymentStrategyType,
  160. }
  161. }
  162. return apps.DeploymentStrategy{
  163. Type: apps.RollingUpdateDeploymentStrategyType,
  164. RollingUpdate: &apps.RollingUpdateDeployment{
  165. MaxUnavailable: &intstr.IntOrString{
  166. Type: intstr.Int,
  167. IntVal: int32(*deploy.UpdateConfig.Parallelism),
  168. },
  169. MaxSurge: nil,
  170. },
  171. }
  172. }
  173. func mapToPVC(project *types.Project, service types.ServiceConfig, vol types.ServiceVolumeConfig) runtime.Object {
  174. rwaccess := core.ReadWriteOnce
  175. if vol.ReadOnly {
  176. rwaccess = core.ReadOnlyMany
  177. }
  178. return &core.PersistentVolumeClaim{
  179. TypeMeta: meta.TypeMeta{
  180. Kind: "PersistentVolumeClaim",
  181. APIVersion: "v1",
  182. },
  183. ObjectMeta: meta.ObjectMeta{
  184. Name: vol.Source,
  185. Labels: selectorLabels(project.Name, service.Name),
  186. },
  187. Spec: core.PersistentVolumeClaimSpec{
  188. VolumeName: vol.Source,
  189. AccessModes: []core.PersistentVolumeAccessMode{rwaccess},
  190. Resources: core.ResourceRequirements{
  191. Requests: core.ResourceList{
  192. core.ResourceStorage: resource.MustParse("100Mi"),
  193. },
  194. },
  195. },
  196. }
  197. }
  198. // toSecondsOrDefault converts a duration string in seconds and defaults to a
  199. // given value if the duration is nil.
  200. // The supported units are us, ms, s, m and h.
  201. func toSecondsOrDefault(duration *types.Duration, defaultValue int32) int32 { //nolint: unparam
  202. if duration == nil {
  203. return defaultValue
  204. }
  205. return int32(time.Duration(*duration).Seconds())
  206. }