Skip to content

Commit

Permalink
Merge pull request #594 from rxy0210/kube_proxy_1
Browse files Browse the repository at this point in the history
fix: add kube-proxy in virtualcluster
  • Loading branch information
kosmos-robot authored Jun 12, 2024
2 parents 5d85238 + 8b8790e commit b6925c7
Show file tree
Hide file tree
Showing 11 changed files with 521 additions and 12 deletions.
2 changes: 2 additions & 0 deletions cmd/kubenest/operator/app/options/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ type KubeNestOptions struct {
AnpMode string
AdmissionPlugins bool
ApiServerReplicas int
ClusterCIDR string
}

func NewOptions() *Options {
Expand Down Expand Up @@ -59,4 +60,5 @@ func (o *Options) AddFlags(flags *pflag.FlagSet) {
flags.StringVar(&o.KubeNestOptions.AnpMode, "kube-nest-anp-mode", "tcp", "kube-apiserver network proxy mode, must be set to tcp or uds. uds mode the replicas for apiserver should be one, and tcp for multi apiserver replicas.")
flags.BoolVar(&o.KubeNestOptions.AdmissionPlugins, "kube-nest-admission-plugins", false, "kube-apiserver network disable-admission-plugins, false for - --disable-admission-plugins=License, true for remove the --disable-admission-plugins=License flag .")
flags.IntVar(&o.KubeNestOptions.ApiServerReplicas, "kube-nest-apiserver-replicas", 1, "virtual-cluster kube-apiserver replicas. default is 2.")
flags.StringVar(&o.KubeNestOptions.ClusterCIDR, "cluster-cidr", "10.244.0.0/16", "Used to set the cluster-cidr of kube-controller-manager and kube-proxy (configmap)")
}
11 changes: 8 additions & 3 deletions pkg/kubenest/constants/constant.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ const (
ApiServerCallRetryInterval = 100 * time.Millisecond
APIServerSVCPortName = "client"

//install kube-proxy in virtualCluster
Proxy = "kube-proxy"
// configmap kube-proxy clustercidr

//controlplane etcd
Etcd = "etcd"
EtcdReplicas = 3
Expand All @@ -58,9 +62,10 @@ const (
EtcdSuffix = "-etcd-client"

//controlplane kube-controller
KubeControllerReplicas = 2
KubeControllerManagerComponent = "KubeControllerManager"
KubeControllerManager = "kube-controller-manager"
KubeControllerReplicas = 2
KubeControllerManagerComponent = "KubeControllerManager"
KubeControllerManager = "kube-controller-manager"
KubeControllerManagerClusterCIDR = "10.244.0.0/16"

//controlplane scheduler
VirtualClusterSchedulerReplicas = 2
Expand Down
17 changes: 9 additions & 8 deletions pkg/kubenest/controlplane/component.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (
"github.com/kosmos.io/kosmos/pkg/kubenest/util"
)

func EnsureControlPlaneComponent(component, name, namespace string, client clientset.Interface) error {
func EnsureControlPlaneComponent(component, name, namespace string, client clientset.Interface, clusterCIDR string) error {
configMaps, err := getComponentConfigMapManifests(name, namespace)
if err != nil {
return err
Expand All @@ -31,7 +31,7 @@ func EnsureControlPlaneComponent(component, name, namespace string, client clien
return fmt.Errorf("failed to create configMap resource for component %s, err: %w", component, err)
}

deployments, err := getComponentManifests(name, namespace)
deployments, err := getComponentManifests(name, namespace, clusterCIDR)
if err != nil {
return err
}
Expand Down Expand Up @@ -72,8 +72,8 @@ func DeleteControlPlaneComponent(component, virtualclusterName, namespace string
return nil
}

func getComponentManifests(name, namespace string) (map[string]*appsv1.Deployment, error) {
kubeControllerManager, err := getKubeControllerManagerManifest(name, namespace)
func getComponentManifests(name, namespace, clusterCIDR string) (map[string]*appsv1.Deployment, error) {
kubeControllerManager, err := getKubeControllerManagerManifest(name, namespace, clusterCIDR)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -111,12 +111,12 @@ func getComponentConfigmaps(component string) []string {
return nil
}

func getKubeControllerManagerManifest(name, namespace string) (*appsv1.Deployment, error) {
func getKubeControllerManagerManifest(name, namespace, clusterCIDR string) (*appsv1.Deployment, error) {
imageRepository, imageVersion := util.GetImageMessage()
kubeControllerManagerBytes, err := util.ParseTemplate(controller.KubeControllerManagerDeployment, struct {
DeploymentName, Namespace, ImageRepository, Version string
VirtualClusterCertsSecret, KubeconfigSecret, ServiceSubnet string
Replicas int32
DeploymentName, Namespace, ImageRepository, Version, ClusterCIDR string
VirtualClusterCertsSecret, KubeconfigSecret, ServiceSubnet string
Replicas int32
}{
DeploymentName: fmt.Sprintf("%s-%s", name, "kube-controller-manager"),
Namespace: namespace,
Expand All @@ -126,6 +126,7 @@ func getKubeControllerManagerManifest(name, namespace string) (*appsv1.Deploymen
KubeconfigSecret: fmt.Sprintf("%s-%s", name, "admin-config-clusterip"),
ServiceSubnet: constants.ApiServerServiceSubnet,
Replicas: constants.KubeControllerReplicas,
ClusterCIDR: clusterCIDR,
})
if err != nil {
return nil, fmt.Errorf("error when parsing kube-controller-manager deployment template: %w", err)
Expand Down
125 changes: 125 additions & 0 deletions pkg/kubenest/controlplane/proxy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package controlplane

import (
"fmt"

"github.com/pkg/errors"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/yaml"
clientset "k8s.io/client-go/kubernetes"

"github.com/kosmos.io/kosmos/pkg/kubenest/manifest/controlplane/proxy"
"github.com/kosmos.io/kosmos/pkg/kubenest/util"
)

func EnsureVirtualClusterProxy(client clientset.Interface, kubeconfigString, clusterCIDR string) error {
// install kube-proxy ds in virtual cluster
if err := installProxyDaemonSet(client); err != nil {
return fmt.Errorf("failed to install virtual cluster proxy, err: %w", err)
}

// install kube-proxy cm in virtual cluster
if err := installProxyConfigMap(client, kubeconfigString, clusterCIDR); err != nil {
return fmt.Errorf("failed to install virtual cluster proxy, err: %w", err)
}

// install kube-proxy sa in virtual cluster
if err := installProxySA(client); err != nil {
return fmt.Errorf("failed to install virtual cluster proxy, err: %w", err)
}
return nil
}

func DeleteVirtualClusterProxy(client clientset.Interface) error {
daemonSetName := fmt.Sprintf("%s-%s", "kube", "proxy")
daemonSetNameSpace := fmt.Sprintf("%s-%s", "kube", "system")
if err := util.DeleteDaemonSet(client, daemonSetName, daemonSetNameSpace); err != nil {
return errors.Wrapf(err, "Failed to delete daemonSet %s/%s", daemonSetName, daemonSetNameSpace)
}

cmName := fmt.Sprintf("%s-%s", "kube", "proxy")
cmNameSpace := fmt.Sprintf("%s-%s", "kube", "system")
if err := util.DeleteConfigmap(client, cmName, cmNameSpace); err != nil {
return errors.Wrapf(err, "Failed to delete ConfigMap %s/%s", cmName, cmNameSpace)
}

saName := fmt.Sprintf("%s-%s", "kube", "proxy")
saNameSpace := fmt.Sprintf("%s-%s", "kube", "system")
if err := util.DeleteServiceAccount(client, saName, saNameSpace); err != nil {
return errors.Wrapf(err, "Failed to delete ServiceAccount %s/%s", saName, saNameSpace)
}
return nil
}

func installProxyDaemonSet(client clientset.Interface) error {
imageRepository, imageVersion := util.GetImageMessage()

proxyDaemonSetBytes, err := util.ParseTemplate(proxy.ProxyDaemonSet, struct {
DaemonSetName, Namespace, ImageRepository, Version string
}{
DaemonSetName: fmt.Sprintf("%s-%s", "kube", "proxy"),
Namespace: fmt.Sprintf("%s-%s", "kube", "system"),
ImageRepository: imageRepository,
Version: imageVersion,
})
if err != nil {
return fmt.Errorf("error when parsing virtual cluster proxy daemonSet template: %w", err)
}

proxyDaemonSet := &appsv1.DaemonSet{}
if err := yaml.Unmarshal([]byte(proxyDaemonSetBytes), proxyDaemonSet); err != nil {
return fmt.Errorf("error when decoding virtual cluster proxy daemonSet: %w", err)
}

if err := util.CreateOrUpdateDaemonSet(client, proxyDaemonSet); err != nil {
return fmt.Errorf("error when creating daemonSet for %s, err: %w", proxyDaemonSet.Name, err)
}
return nil
}

func installProxyConfigMap(client clientset.Interface, kubeconfigString, clusterCIDR string) error {
proxyConfigMapBytes, err := util.ParseTemplate(proxy.ProxyConfigMap, struct {
ConfigMapName, Namespace, KubeProxyKubeConfig, ClusterCIDR string
}{
ConfigMapName: fmt.Sprintf("%s-%s", "kube", "proxy"),
Namespace: fmt.Sprintf("%s-%s", "kube", "system"),
KubeProxyKubeConfig: kubeconfigString,
ClusterCIDR: clusterCIDR,
})
if err != nil {
return fmt.Errorf("error when parsing virtual cluster proxy configmap template: %w", err)
}

proxyConfigMap := &corev1.ConfigMap{}
if err := yaml.Unmarshal([]byte(proxyConfigMapBytes), proxyConfigMap); err != nil {
return fmt.Errorf("error when decoding virtual cluster proxy configmap: %w", err)
}

if err := util.CreateOrUpdateConfigMap(client, proxyConfigMap); err != nil {
return fmt.Errorf("error when creating configmap for %s, err: %w", proxyConfigMap.Name, err)
}
return nil
}

func installProxySA(client clientset.Interface) error {
proxySABytes, err := util.ParseTemplate(proxy.ProxySA, struct {
SAName, Namespace string
}{
SAName: fmt.Sprintf("%s-%s", "kube", "proxy"),
Namespace: fmt.Sprintf("%s-%s", "kube", "system"),
})
if err != nil {
return fmt.Errorf("error when parsing virtual cluster proxy SA template: %w", err)
}

proxySA := &corev1.ServiceAccount{}
if err := yaml.Unmarshal([]byte(proxySABytes), proxySA); err != nil {
return fmt.Errorf("error when decoding virtual cluster proxy SA: %w", err)
}

if err := util.CreateOrUpdateServiceAccount(client, proxySA); err != nil {
return fmt.Errorf("error when creating SA for %s, err: %w", proxySA.Name, err)
}
return nil
}
3 changes: 3 additions & 0 deletions pkg/kubenest/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ func NewInitPhase(opts *InitOptions) *workflow.Phase {
initPhase.AppendTask(tasks.NewComponentTask())
initPhase.AppendTask(tasks.NewCheckControlPlaneTask())
initPhase.AppendTask(tasks.NewAnpTask())
// create proxy
initPhase.AppendTask(tasks.NewVirtualClusterProxyTask())
// create core-dns
initPhase.AppendTask(tasks.NewCoreDNSTask())
// add server
Expand All @@ -85,6 +87,7 @@ func UninstallPhase(opts *InitOptions) *workflow.Phase {
destroyPhase.AppendTask(tasks.UninstallVirtualClusterServiceTask())
destroyPhase.AppendTask(tasks.UninstallCertsAndKubeconfigTask())
destroyPhase.AppendTask(tasks.DeleteEtcdPvcTask())
destroyPhase.AppendTask(tasks.UninstallVirtualClusterProxyTask())

destroyPhase.SetDataInitializer(func() (workflow.RunData, error) {
return newRunData(opts)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ spec:
- --authorization-kubeconfig=/etc/virtualcluster/kubeconfig
- --bind-address=0.0.0.0
- --client-ca-file=/etc/virtualcluster/pki/ca.crt
- --cluster-cidr=10.244.0.0/16
- --cluster-cidr={{ .ClusterCIDR }}
- --cluster-name=virtualcluster
- --cluster-signing-cert-file=/etc/virtualcluster/pki/ca.crt
- --cluster-signing-key-file=/etc/virtualcluster/pki/ca.key
Expand Down
147 changes: 147 additions & 0 deletions pkg/kubenest/manifest/controlplane/proxy/mainfests_daemonset.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
package proxy

const (
ProxyDaemonSet = `
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: {{ .DaemonSetName }}
namespace: {{ .Namespace }}
labels:
virtualCluster-app: kube-proxy
app.kubernetes.io/managed-by: virtual-cluster-controller
spec:
revisionHistoryLimit: 10
selector:
matchLabels:
app.kubernetes.io/managed-by: virtual-cluster-controller
template:
metadata:
labels:
app.kubernetes.io/managed-by: virtual-cluster-controller
spec:
containers:
- command:
- /usr/local/bin/kube-proxy
- --config=/var/lib/kube-proxy/config.conf
- --hostname-override=$(NODE_NAME)
env:
- name: NODE_NAME
valueFrom:
fieldRef:
apiVersion: v1
fieldPath: spec.nodeName
image: {{ .ImageRepository }}/kube-proxy:{{ .Version }}
imagePullPolicy: IfNotPresent
name: kube-proxy
resources: {}
securityContext:
privileged: true
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /var/lib/kube-proxy
name: kube-proxy
- mountPath: /run/xtables.lock
name: xtables-lock
- mountPath: /lib/modules
name: lib-modules
readOnly: true
dnsPolicy: ClusterFirst
hostNetwork: true
nodeSelector:
kubernetes.io/os: linux
priorityClassName: system-node-critical
restartPolicy: Always
schedulerName: default-scheduler
securityContext: {}
serviceAccount: kube-proxy
serviceAccountName: kube-proxy
terminationGracePeriodSeconds: 30
tolerations:
- operator: Exists
volumes:
- configMap:
defaultMode: 420
name: kube-proxy
name: kube-proxy
- hostPath:
path: /run/xtables.lock
type: FileOrCreate
name: xtables-lock
- hostPath:
path: /lib/modules
type: ""
name: lib-modules
updateStrategy:
rollingUpdate:
maxSurge: 0
maxUnavailable: 1
type: RollingUpdate
`
ProxyConfigMap = `
apiVersion: v1
data:
config.conf: |-
apiVersion: kubeproxy.config.k8s.io/v1alpha1
bindAddress: 0.0.0.0
bindAddressHardFail: false
clientConnection:
acceptContentTypes: ""
burst: 100
contentType: ""
kubeconfig: /var/lib/kube-proxy/kubeconfig.conf
qps: 100
clusterCIDR: {{ .ClusterCIDR }}
configSyncPeriod: 0s
conntrack:
maxPerCore: null
min: null
tcpCloseWaitTimeout: null
tcpEstablishedTimeout: null
detectLocal:
bridgeInterface: ""
interfaceNamePrefix: ""
detectLocalMode: ""
enableProfiling: false
healthzBindAddress: ""
hostnameOverride: ""
iptables:
masqueradeAll: true
masqueradeBit: null
minSyncPeriod: 0s
syncPeriod: 0s
ipvs:
excludeCIDRs:
- 192.0.0.1/32
minSyncPeriod: 0s
scheduler: ""
strictARP: false
syncPeriod: 0s
tcpFinTimeout: 0s
tcpTimeout: 0s
udpTimeout: 0s
kind: KubeProxyConfiguration
metricsBindAddress: 0.0.0.0:10249
mode: ipvs
nodePortAddresses: null
oomScoreAdj: null
portRange: ""
showHiddenMetricsForVersion: ""
udpIdleTimeout: 0s
winkernel:
enableDSR: false
forwardHealthCheckVip: false
networkName: ""
rootHnsEndpointName: ""
sourceVip: ""
kubeconfig.conf: |-
{{ .KubeProxyKubeConfig }}
kind: ConfigMap
metadata:
labels:
app: kube-proxy
name: {{ .ConfigMapName }}
namespace: {{ .Namespace }}
`
)
Loading

0 comments on commit b6925c7

Please sign in to comment.