Merge pull request #1848 from sosan/feature-1846-network_mode-service

add networkmode service:
This commit is contained in:
Kubernetes Prow Robot 2024-04-25 09:56:29 -07:00 committed by GitHub
commit e4ca58bcf2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 1576 additions and 1 deletions

View File

@ -118,6 +118,7 @@ type ServiceConfig struct {
ReadOnly bool `compose:"read_only"` ReadOnly bool `compose:"read_only"`
Args []string `compose:"args"` Args []string `compose:"args"`
VolList []string `compose:"volumes"` VolList []string `compose:"volumes"`
NetworkMode string `compose:"network_mode"`
Network []string `compose:"network"` Network []string `compose:"network"`
Labels map[string]string `compose:"labels"` Labels map[string]string `compose:"labels"`
Annotations map[string]string `compose:""` Annotations map[string]string `compose:""`

View File

@ -487,6 +487,7 @@ func dockerComposeToKomposeMapping(composeObject *types.Project) (kobject.Kompos
serviceConfig.HostName = composeServiceConfig.Hostname serviceConfig.HostName = composeServiceConfig.Hostname
serviceConfig.DomainName = composeServiceConfig.DomainName serviceConfig.DomainName = composeServiceConfig.DomainName
serviceConfig.Secrets = composeServiceConfig.Secrets serviceConfig.Secrets = composeServiceConfig.Secrets
serviceConfig.NetworkMode = composeServiceConfig.NetworkMode
if composeServiceConfig.StopGracePeriod != nil { if composeServiceConfig.StopGracePeriod != nil {
serviceConfig.StopGracePeriod = composeServiceConfig.StopGracePeriod.String() serviceConfig.StopGracePeriod = composeServiceConfig.StopGracePeriod.String()

View File

@ -72,6 +72,15 @@ type HpaValues struct {
MemoryUtilization int32 MemoryUtilization int32
} }
const (
NetworkModeService = "service:"
)
type DeploymentMapping struct {
SourceDeploymentName string
TargetDeploymentName string
}
/** /**
* Generate Helm Chart configuration * Generate Helm Chart configuration
*/ */
@ -1251,3 +1260,101 @@ func setVolumeAccessMode(mode string, volumeAccesMode []api.PersistentVolumeAcce
return volumeAccesMode return volumeAccesMode
} }
// fixNetworkModeToService is responsible for adjusting the network mode of services in docker compose (services:)
// generate a mapping of deployments based on the network mode of each service
// merging containers into the destination deployment, and removing transferred deployments
func (k *Kubernetes) fixNetworkModeToService(objects *[]runtime.Object, services map[string]kobject.ServiceConfig) {
deploymentMappings := searchNetworkModeToService(services)
if len(deploymentMappings) == 0 {
return
}
mergeContainersIntoDestinationDeployment(deploymentMappings, objects)
removeDeploymentTransfered(deploymentMappings, objects)
}
// mergeContainersIntoDestinationDeployment takes a list of deployment mappings and a list of runtime objects
// and merges containers from source deployment into the destination deployment
func mergeContainersIntoDestinationDeployment(deploymentMappings []DeploymentMapping, objects *[]runtime.Object) {
for _, currentDeploymentMap := range deploymentMappings {
addContainersFromSourceToTargetDeployment(objects, currentDeploymentMap)
}
}
// addContainersFromSourceToTargetDeployment adds containers from the source deployment
// if current deployment name matches source deployment name
func addContainersFromSourceToTargetDeployment(objects *[]runtime.Object, currentDeploymentMap DeploymentMapping) {
for _, obj := range *objects {
if deploy, ok := obj.(*appsv1.Deployment); ok {
if deploy.ObjectMeta.Name == currentDeploymentMap.SourceDeploymentName {
addContainersToTargetDeployment(objects, deploy.Spec.Template.Spec.Containers, currentDeploymentMap.TargetDeploymentName)
}
}
}
}
// addContainersToTargetDeployment takes
// - list of runtime objects
// - list of containers to append
// - deployment name to transfer
// appends the containers to the target deployment if its name matches
func addContainersToTargetDeployment(objects *[]runtime.Object, containersToAppend []api.Container, nameDeploymentToTransfer string) {
for _, obj := range *objects {
if deploy, ok := obj.(*appsv1.Deployment); ok {
if deploy.ObjectMeta.Name == nameDeploymentToTransfer {
deploy.Spec.Template.Spec.Containers = append(deploy.Spec.Template.Spec.Containers, containersToAppend...)
}
}
}
}
// searchNetworkModeToService iterates over services and checking their network mode service:
// its separates over process of transferring containers,
// it determines where each container should be removed from and where it should be added to
func searchNetworkModeToService(services map[string]kobject.ServiceConfig) (deploymentMappings []DeploymentMapping) {
deploymentMappings = []DeploymentMapping{}
for _, service := range services {
if !strings.Contains(service.NetworkMode, NetworkModeService) {
continue
}
splitted := strings.Split(service.NetworkMode, ":")
if len(splitted) < 2 {
continue
}
deploymentMappings = append(deploymentMappings, DeploymentMapping{
SourceDeploymentName: service.Name,
TargetDeploymentName: splitted[1],
})
}
return deploymentMappings
}
// removeDeploymentTransfered iterates over a list of DeploymentMapping and
// removes each deployment that marked in deploymentMappings
func removeDeploymentTransfered(deploymentMappings []DeploymentMapping, objects *[]runtime.Object) {
for _, currentDeploymentMap := range deploymentMappings {
removeTargetDeployment(objects, currentDeploymentMap.SourceDeploymentName)
}
}
// removeTargetDeployment iterates over a list of runtime objects
// and removes the target deployment from the list
func removeTargetDeployment(objects *[]runtime.Object, targetDeploymentName string) {
for i := len(*objects) - 1; i >= 0; i-- {
if deploy, ok := (*objects)[i].(*appsv1.Deployment); ok {
if deploy.ObjectMeta.Name == targetDeploymentName {
*objects = removeFromSlice(*objects, (*objects)[i])
}
}
}
}
// removeFromSlice removes a specific object from a slice of runtime objects and returns the updated slice
func removeFromSlice(objects []runtime.Object, objectToRemove runtime.Object) []runtime.Object {
for i, currentObject := range objects {
if reflect.DeepEqual(currentObject, objectToRemove) {
return append(objects[:i], objects[i+1:]...)
}
}
return objects
}

File diff suppressed because it is too large Load Diff

View File

@ -1678,6 +1678,7 @@ func (k *Kubernetes) Transform(komposeObject kobject.KomposeObject, opt kobject.
transformer.AssignNamespaceToObjects(&allobjects, komposeObject.Namespace) transformer.AssignNamespaceToObjects(&allobjects, komposeObject.Namespace)
} }
// k.FixWorkloadVersion(&allobjects) // k.FixWorkloadVersion(&allobjects)
k.fixNetworkModeToService(&allobjects, komposeObject.ServiceConfigs)
return allobjects, nil return allobjects, nil
} }

View File

@ -372,4 +372,9 @@ k8s_output="$KOMPOSE_ROOT/script/test/fixtures/configmap-file-configs/output-k8s
os_cmd="kompose -f $KOMPOSE_ROOT/script/test/fixtures/configmap-file-configs/compose-3.yaml convert --provider openshift --stdout --with-kompose-annotation=false" os_cmd="kompose -f $KOMPOSE_ROOT/script/test/fixtures/configmap-file-configs/compose-3.yaml convert --provider openshift --stdout --with-kompose-annotation=false"
os_output="$KOMPOSE_ROOT/script/test/fixtures/configmap-file-configs/output-os-3.yaml" os_output="$KOMPOSE_ROOT/script/test/fixtures/configmap-file-configs/output-os-3.yaml"
convert::expect_success "$k8s_cmd" "$k8s_output" || exit 1 convert::expect_success "$k8s_cmd" "$k8s_output" || exit 1
convert::expect_success "$os_cmd" "$os_output" || exit 1 convert::expect_success "$os_cmd" "$os_output" || exit 1
# Test network_mode: service:
k8s_cmd="kompose -f $KOMPOSE_ROOT/script/test/fixtures/network-mode-service/compose.yaml convert --stdout --with-kompose-annotation=false"
k8s_output="$KOMPOSE_ROOT/script/test/fixtures/network-mode-service/output-k8s.yaml"
convert::expect_success "$k8s_cmd" "$k8s_output" || exit 1

View File

@ -0,0 +1,17 @@
version: '3.8'
services:
client:
image: busybox
command: ['sleep', 'infinity']
container_name: threats-client
restart: unless-stopped
ports:
- '8080:8080'
server:
image: busybox
command: ['sleep', 'infinity']
container_name: threats-server
restart: unless-stopped
network_mode: service:client

View File

@ -0,0 +1,49 @@
---
apiVersion: v1
kind: Service
metadata:
labels:
io.kompose.service: client
name: client
spec:
ports:
- name: "8080"
port: 8080
targetPort: 8080
selector:
io.kompose.service: client
---
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
io.kompose.service: client
name: client
spec:
replicas: 1
selector:
matchLabels:
io.kompose.service: client
template:
metadata:
labels:
io.kompose.network/network-mode-service-default: "true"
io.kompose.service: client
spec:
containers:
- args:
- sleep
- infinity
image: busybox
name: threats-client
ports:
- containerPort: 8080
hostPort: 8080
protocol: TCP
- args:
- sleep
- infinity
image: busybox
name: threats-server
restartPolicy: Always