提交 d3bdcd04 编写于 作者: D Duan Jiong

network: support network isolate

Add new crd to convert kubesphere network policy to k8s network policy, and then other network
plugin will do the rest work.

Use  cache.go from calico project's kube-controller,  it aim to  sync nsnp with k8s np, delete unused np, and relieve the pressure on k8s restful client.

If you want higher performance, you can implement interface  NsNetworkPolicyProvider in pkg/controller/provider/namespace_np.go.
Signed-off-by: NDuan Jiong <djduanjiong@gmail.com>
上级 fc373b18
FROM gcr.io/distroless/static:latest
WORKDIR /
COPY ks-network .
ENTRYPOINT ["/ks-network"]
......@@ -25,6 +25,8 @@ import (
"kubesphere.io/kubesphere/pkg/controller/devopscredential"
"kubesphere.io/kubesphere/pkg/controller/devopsproject"
"kubesphere.io/kubesphere/pkg/controller/job"
"kubesphere.io/kubesphere/pkg/controller/network/nsnetworkpolicy"
"kubesphere.io/kubesphere/pkg/controller/network/provider"
"kubesphere.io/kubesphere/pkg/controller/pipeline"
"kubesphere.io/kubesphere/pkg/controller/s2ibinary"
"kubesphere.io/kubesphere/pkg/controller/s2irun"
......@@ -126,6 +128,16 @@ func AddControllers(
kubesphereInformer.Cluster().V1alpha1().Clusters(),
client.KubeSphere().ClusterV1alpha1().Clusters())
nsnpProvider, err := provider.NewNsNetworkPolicyProvider(client.Kubernetes(),
kubernetesInformer.Networking().V1().NetworkPolicies())
if err != nil {
return err
}
nsnpController := nsnetworkpolicy.NewNSNetworkPolicyController(client.Kubernetes(),
client.KubeSphere().NetworkV1alpha1(), kubesphereInformer.Network().V1alpha1().NamespaceNetworkPolicies(),
kubernetesInformer.Core().V1().Services(), kubesphereInformer.Tenant().V1alpha1().Workspaces(),
kubernetesInformer.Core().V1().Namespaces(), nsnpProvider)
controllers := map[string]manager.Runnable{
"virtualservice-controller": vsController,
"destinationrule-controller": drController,
......@@ -137,8 +149,9 @@ func AddControllers(
"devopsprojects-controller": devopsProjectController,
"pipeline-controller": devopsPipelineController,
"devopscredential-controller": devopsCredentialController,
"cluster-controller": clusterController,
"user-controller": userController,
"cluster-controller": clusterController,
"nsnp-controller": nsnpController,
}
for name, ctrl := range controllers {
......
......@@ -35,6 +35,7 @@ import (
controllerconfig "kubesphere.io/kubesphere/pkg/apiserver/config"
"kubesphere.io/kubesphere/pkg/client/clientset/versioned/scheme"
"kubesphere.io/kubesphere/pkg/controller/namespace"
"kubesphere.io/kubesphere/pkg/controller/network/nsnetworkpolicy"
"kubesphere.io/kubesphere/pkg/controller/user"
"kubesphere.io/kubesphere/pkg/controller/workspace"
"kubesphere.io/kubesphere/pkg/simple/client/openpitrix"
......@@ -160,6 +161,7 @@ func Run(s *options.KubeSphereControllerManagerOptions, stopCh <-chan struct{})
klog.Info("registering webhooks to the webhook server")
hookServer.Register("/mutating-encrypt-password-iam-kubesphere-io-v1alpha2-user", &webhook.Admission{Handler: &user.PasswordCipher{Client: mgr.GetClient()}})
hookServer.Register("/validate-email-iam-kubesphere-io-v1alpha2-user", &webhook.Admission{Handler: &user.EmailValidator{Client: mgr.GetClient()}})
hookServer.Register("/validate-service-nsnp-kubesphere-io-v1alpha1-network", &webhook.Admission{Handler: &nsnetworkpolicy.ServiceValidator{}})
klog.V(0).Info("Starting the controllers.")
if err = mgr.Start(stopCh); err != nil {
......
package main
import (
"flag"
"k8s.io/klog"
"kubesphere.io/kubesphere/pkg/controller/network/runoption"
)
var opt runoption.RunOption
func init() {
flag.StringVar(&opt.ProviderName, "np-provider", "calico", "specify the network policy provider, k8s or calico")
flag.BoolVar(&opt.AllowInsecureEtcd, "allow-insecure-etcd", false, "specify allow connect to etcd using insecure http")
flag.StringVar(&opt.DataStoreType, "datastore-type", "k8s", "specify the datastore type of calico")
//TODO add more flags
}
func main() {
klog.InitFlags(nil)
flag.Set("logtostderr", "true")
flag.Parse()
klog.V(1).Info("Preparing kubernetes client")
klog.Fatal(opt.Run())
}
apiVersion: admissionregistration.k8s.io/v1beta1
kind: ValidatingWebhookConfiguration
metadata:
creationTimestamp: null
name: kubesphere-nsnp-validate-service
webhooks:
- clientConfig:
caBundle: <caBundle>
service:
name: kubesphere-controller-manager-service
namespace: kubesphere-system
path: /validate-service-nsnp-kubesphere-io-v1alpha1-network
failurePolicy: Fail
name: validate.nsnp.kubesphere.io
rules:
- apiGroups:
- ""
apiVersions:
- v1
operations:
- CREATE
- UPDATE
resources:
- services
......@@ -30,13 +30,12 @@ require (
github.com/emirpasic/gods v1.12.0 // indirect
github.com/fatih/structs v1.1.0
github.com/go-ldap/ldap v3.0.3+incompatible
github.com/go-logr/logr v0.1.0
github.com/go-logr/zapr v0.1.1 // indirect
github.com/go-openapi/jsonreference v0.19.3 // indirect
github.com/go-openapi/loads v0.19.2
github.com/go-openapi/spec v0.19.3
github.com/go-openapi/strfmt v0.19.0
github.com/go-openapi/validate v0.19.2
github.com/go-playground/universal-translator v0.16.0 // indirect
github.com/go-redis/redis v6.15.2+incompatible
github.com/go-sql-driver/mysql v1.4.1
github.com/gocraft/dbr v0.0.0-20180507214907-a0fd650918f6
......@@ -46,32 +45,34 @@ require (
github.com/google/go-cmp v0.3.0
github.com/google/go-querystring v1.0.0 // indirect
github.com/google/uuid v1.1.1
github.com/gophercloud/gophercloud v0.3.0 // indirect
github.com/gorilla/mux v1.7.1 // indirect
github.com/gorilla/websocket v1.4.0
github.com/hashicorp/go-version v1.2.0 // indirect
github.com/imdario/mergo v0.3.7 // indirect
github.com/json-iterator/go v1.1.9
github.com/json-iterator/go v1.1.8
github.com/kelseyhightower/envconfig v1.4.0 // indirect
github.com/kiali/kiali v0.15.1-0.20191210080139-edbbad1ef779
github.com/kubernetes-sigs/application v0.0.0-20191210100950-18cc93526ab4
github.com/kubesphere/sonargo v0.0.2
github.com/leodido/go-urn v1.1.0 // indirect
github.com/lib/pq v1.2.0 // indirect
github.com/mailru/easyjson v0.7.0 // indirect
github.com/mattn/go-sqlite3 v1.11.0 // indirect
github.com/morikuni/aec v0.0.0-20170113033406-39771216ff4c // indirect
github.com/onsi/ginkgo v1.12.0
github.com/onsi/gomega v1.9.0
github.com/onsi/ginkgo v1.8.0
github.com/onsi/gomega v1.5.0
github.com/open-policy-agent/opa v0.18.0
github.com/opencontainers/go-digest v1.0.0-rc1
github.com/opencontainers/image-spec v1.0.1 // indirect
github.com/openshift/api v0.0.0-20180801171038-322a19404e37 // indirect
github.com/opentracing/opentracing-go v1.1.0 // indirect
github.com/pkg/errors v0.9.1
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/pkg/errors v0.8.1
github.com/projectcalico/kube-controllers v3.8.8+incompatible
github.com/projectcalico/libcalico-go v1.7.2-0.20191104213956-8f81e1e344ce
github.com/prometheus/client_golang v1.0.0
github.com/prometheus/client_golang v0.9.4
github.com/prometheus/common v0.4.1
github.com/prometheus/prometheus v1.8.2
github.com/sirupsen/logrus v1.4.2
github.com/sony/sonyflake v0.0.0-20181109022403-6d5bd6181009
github.com/speps/go-hashids v2.0.0+incompatible
github.com/spf13/cobra v0.0.5
......@@ -84,28 +85,27 @@ require (
golang.org/x/net v0.0.0-20191004110552-13f9640d40b9
google.golang.org/grpc v1.23.1
gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d // indirect
gopkg.in/go-playground/validator.v9 v9.29.1 // indirect
gopkg.in/src-d/go-billy.v4 v4.3.0 // indirect
gopkg.in/src-d/go-git.v4 v4.11.0
gopkg.in/yaml.v2 v2.2.8
gopkg.in/yaml.v2 v2.2.4
istio.io/api v0.0.0-20191111210003-35e06ef8d838
istio.io/client-go v0.0.0-20191113122552-9bd0ba57c3d2
k8s.io/api v0.17.3
k8s.io/apiextensions-apiserver v0.17.3
k8s.io/apimachinery v0.17.3
k8s.io/apiserver v0.17.3
k8s.io/client-go v0.17.3
k8s.io/code-generator v0.17.3
k8s.io/component-base v0.17.3
k8s.io/api v0.0.0-20191114100352-16d7abae0d2a
k8s.io/apiextensions-apiserver v0.0.0-20191114105449-027877536833
k8s.io/apimachinery v0.0.0-20191028221656-72ed19daf4bb
k8s.io/apiserver v0.0.0-20191114103151-9ca1dc586682
k8s.io/client-go v0.0.0-20191114101535-6c5935290e33
k8s.io/code-generator v0.0.0-20191004115455-8e001e5d1894
k8s.io/component-base v0.0.0-20191114102325-35a9586014f7
k8s.io/gengo v0.0.0-20191120174120-e74f70b9b27e // indirect
k8s.io/klog v1.0.0
k8s.io/kube-openapi v0.0.0-20191107075043-30be4d16710a
k8s.io/utils v0.0.0-20191114184206-e782cd3c129f // indirect
kubesphere.io/im v0.1.0 // indirect
openpitrix.io/iam v0.1.0 // indirect
openpitrix.io/openpitrix v0.4.1-0.20190920134345-4d2be6e4965c
sigs.k8s.io/controller-runtime v0.5.0
sigs.k8s.io/controller-runtime v0.4.0
sigs.k8s.io/controller-tools v0.2.4
sigs.k8s.io/kubefed v0.2.0-alpha.1
)
replace (
......@@ -119,7 +119,6 @@ replace (
github.com/Azure/go-autorest/logger => github.com/Azure/go-autorest/logger v0.1.0
github.com/Azure/go-autorest/tracing => github.com/Azure/go-autorest/tracing v0.5.0
github.com/BurntSushi/toml => github.com/BurntSushi/toml v0.3.1
github.com/MakeNowJust/heredoc => github.com/MakeNowJust/heredoc v0.0.0-20170808103936-bb23615498cd
github.com/Masterminds/semver => github.com/Masterminds/semver v1.5.0
github.com/Microsoft/go-winio => github.com/Microsoft/go-winio v0.4.12
github.com/NYTimes/gziphandler => github.com/NYTimes/gziphandler v1.1.1
......@@ -143,7 +142,6 @@ replace (
github.com/bmizerany/assert => github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869
github.com/cenkalti/backoff => github.com/cenkalti/backoff v2.2.1+incompatible
github.com/cespare/xxhash => github.com/cespare/xxhash v1.1.0
github.com/chai2010/gettext-go => github.com/chai2010/gettext-go v0.0.0-20160711120539-c6fed771bfd5
github.com/cheekybits/genny => github.com/cheekybits/genny v1.0.0
github.com/client9/misspell => github.com/client9/misspell v0.3.4
github.com/coreos/bbolt => github.com/coreos/bbolt v1.3.3
......@@ -154,7 +152,6 @@ replace (
github.com/coreos/pkg => github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f
github.com/cpuguy83/go-md2man => github.com/cpuguy83/go-md2man v1.0.10
github.com/davecgh/go-spew => github.com/davecgh/go-spew v1.1.1
github.com/daviddengcn/go-colortext => github.com/daviddengcn/go-colortext v0.0.0-20160507010035-511bcaf42ccd
github.com/deckarep/golang-set => github.com/deckarep/golang-set v1.7.1
github.com/denisenkom/go-mssqldb => github.com/denisenkom/go-mssqldb v0.0.0-20190204142019-df6d76eb9289
github.com/dgrijalva/jwt-go => github.com/dgrijalva/jwt-go v3.2.0+incompatible
......@@ -176,7 +173,6 @@ replace (
github.com/emirpasic/gods => github.com/emirpasic/gods v1.12.0
github.com/erikstmartin/go-testdb => github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5
github.com/evanphx/json-patch => github.com/evanphx/json-patch v4.5.0+incompatible
github.com/exponent-io/jsonpath => github.com/exponent-io/jsonpath v0.0.0-20151013193312-d6023ce2651d
github.com/fatih/camelcase => github.com/fatih/camelcase v1.0.0
github.com/fatih/color => github.com/fatih/color v1.7.0
github.com/fatih/structs => github.com/fatih/structs v1.1.0
......@@ -218,9 +214,6 @@ replace (
github.com/golang/mock => github.com/golang/mock v1.2.0
github.com/golang/protobuf => github.com/golang/protobuf v1.3.2
github.com/golang/snappy => github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db
github.com/golangplus/bytes => github.com/golangplus/bytes v0.0.0-20160111154220-45c989fe5450
github.com/golangplus/fmt => github.com/golangplus/fmt v0.0.0-20150411045040-2a5d6d7d2995
github.com/golangplus/testing => github.com/golangplus/testing v0.0.0-20180327235837-af21d9c3145e
github.com/google/btree => github.com/google/btree v1.0.0
github.com/google/go-cmp => github.com/google/go-cmp v0.3.0
github.com/google/go-querystring => github.com/google/go-querystring v1.0.0
......@@ -271,14 +264,11 @@ replace (
github.com/kr/pty => github.com/kr/pty v1.1.5
github.com/kr/text => github.com/kr/text v0.1.0
github.com/kubernetes-sigs/application => github.com/kubesphere/application v0.0.0-20191210100950-18cc93526ab4
github.com/kubernetes-sigs/federation-v2 => github.com/kubernetes-sigs/federation-v2 v0.0.10
github.com/kubesphere/s2ioperator => github.com/kubesphere/s2ioperator v0.0.14
github.com/kubesphere/sonargo => github.com/kubesphere/sonargo v0.0.2
github.com/kylelemons/godebug => github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348
github.com/leodido/go-urn => github.com/leodido/go-urn v1.1.0
github.com/lib/pq => github.com/lib/pq v1.2.0
github.com/liggitt/tabwriter => github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de
github.com/lithammer/dedent => github.com/lithammer/dedent v1.1.0
github.com/lucas-clemente/quic-go => github.com/lucas-clemente/quic-go v0.11.1
github.com/magiconair/properties => github.com/magiconair/properties v1.8.0
github.com/mailru/easyjson => github.com/mailru/easyjson v0.7.0
......@@ -292,7 +282,6 @@ replace (
github.com/mholt/certmagic => github.com/mholt/certmagic v0.5.1
github.com/miekg/dns => github.com/miekg/dns v1.1.9
github.com/mitchellh/go-homedir => github.com/mitchellh/go-homedir v1.1.0
github.com/mitchellh/go-wordwrap => github.com/mitchellh/go-wordwrap v1.0.0
github.com/mitchellh/mapstructure => github.com/mitchellh/mapstructure v1.1.2
github.com/mna/pigeon => github.com/mna/pigeon v0.0.0-20180808201053-bb0192cfc2ae
github.com/modern-go/concurrent => github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd
......@@ -312,7 +301,6 @@ replace (
github.com/opencontainers/image-spec => github.com/opencontainers/image-spec v1.0.1
github.com/openshift/api => github.com/openshift/api v0.0.0-20180801171038-322a19404e37
github.com/openshift/build-machinery-go => github.com/openshift/build-machinery-go v0.0.0-20200211121458-5e3d6e570160
github.com/openshift/generic-admission-server => github.com/openshift/generic-admission-server v1.14.0
github.com/opentracing/opentracing-go => github.com/opentracing/opentracing-go v1.1.0
github.com/pborman/uuid => github.com/pborman/uuid v1.2.0
github.com/pelletier/go-buffruneio => github.com/pelletier/go-buffruneio v0.2.0
......@@ -364,7 +352,6 @@ replace (
github.com/urfave/cli => github.com/urfave/cli v1.20.0
github.com/xanzy/ssh-agent => github.com/xanzy/ssh-agent v0.2.1
github.com/xiang90/probing => github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2
github.com/xlab/handysort => github.com/xlab/handysort v0.0.0-20150421192137-fb3537ed64a1
github.com/xlab/treeprint => github.com/xlab/treeprint v0.0.0-20180616005107-d6fb6747feb6
github.com/xordataexchange/crypt => github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77
github.com/yashtewari/glob-intersection => github.com/yashtewari/glob-intersection v0.0.0-20180916065949-5c77d914dd0b
......@@ -422,16 +409,12 @@ replace (
k8s.io/apiextensions-apiserver => k8s.io/apiextensions-apiserver v0.0.0-20191114105449-027877536833
k8s.io/apimachinery => k8s.io/apimachinery v0.0.0-20191028221656-72ed19daf4bb
k8s.io/apiserver => k8s.io/apiserver v0.0.0-20191114103151-9ca1dc586682
k8s.io/cli-runtime => k8s.io/cli-runtime v0.17.3
k8s.io/client-go => k8s.io/client-go v0.0.0-20191114101535-6c5935290e33
k8s.io/cluster-registry => k8s.io/cluster-registry v0.0.6
k8s.io/code-generator => k8s.io/code-generator v0.0.0-20191004115455-8e001e5d1894
k8s.io/component-base => k8s.io/component-base v0.0.0-20191114102325-35a9586014f7
k8s.io/gengo => k8s.io/gengo v0.0.0-20191120174120-e74f70b9b27e
k8s.io/klog => k8s.io/klog v1.0.0
k8s.io/kube-openapi => k8s.io/kube-openapi v0.0.0-20191107075043-30be4d16710a
k8s.io/kubectl => k8s.io/kubectl v0.17.3
k8s.io/metrics => k8s.io/metrics v0.17.3
k8s.io/utils => k8s.io/utils v0.0.0-20191114184206-e782cd3c129f
kubesphere.io/application => kubesphere.io/application v0.0.0-20190404151855-67ae7f915d4e
kubesphere.io/im => kubesphere.io/im v0.1.0
......@@ -446,10 +429,7 @@ replace (
rsc.io/goversion => rsc.io/goversion v1.0.0
sigs.k8s.io/controller-runtime => sigs.k8s.io/controller-runtime v0.4.0
sigs.k8s.io/controller-tools => sigs.k8s.io/controller-tools v0.2.4
sigs.k8s.io/kubefed => sigs.k8s.io/kubefed v0.2.0-alpha.1
sigs.k8s.io/kustomize => sigs.k8s.io/kustomize v2.0.3+incompatible
sigs.k8s.io/structured-merge-diff => sigs.k8s.io/structured-merge-diff v0.0.0-20190817042607-6149e4549fca
sigs.k8s.io/testing_frameworks => sigs.k8s.io/testing_frameworks v0.1.2
sigs.k8s.io/yaml => sigs.k8s.io/yaml v1.1.0
vbom.ml/util => vbom.ml/util v0.0.0-20160121211510-db5cfe13f5cc
)
......@@ -323,6 +323,8 @@ github.com/openshift/api v0.0.0-20180801171038-322a19404e37/go.mod h1:dh9o4Fs58g
github.com/openshift/generic-admission-server v1.14.0/go.mod h1:GD9KN/W4KxqRQGVMbqQHpHzb2XcQVvLCaBaSciqXvfM=
github.com/opentracing/opentracing-go v1.1.0 h1:pWlfV3Bxv7k65HYwkikxat0+s3pV4bsqf19k25Ur8rU=
github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/pborman/uuid v1.2.0 h1:J7Q5mO4ysT1dv8hyrUGHb9+ooztCXu1D8MY8DZYsu3g=
github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k=
github.com/pelletier/go-buffruneio v0.2.0 h1:U4t4R6YkofJ5xHm3dJzuRpPZ0mr5MMCoAWooScCR7aA=
......@@ -344,6 +346,8 @@ github.com/projectcalico/go-yaml v0.0.0-20161201183616-955bc3e451ef h1:Di9BaA9ap
github.com/projectcalico/go-yaml v0.0.0-20161201183616-955bc3e451ef/go.mod h1:1Ra2BftSa7Go38Gbq1q0bfmBFSSgUv+Cdc3SY8IL/C0=
github.com/projectcalico/go-yaml-wrapper v0.0.0-20161127220527-598e54215bee h1:yVWsNSlAuYoJ0CznHsYRPiFgsotoj07k00k5rQvGlHM=
github.com/projectcalico/go-yaml-wrapper v0.0.0-20161127220527-598e54215bee/go.mod h1:UgC0aTQ2KMDxlX3lU/stndk7DMUBJqzN40yFiILHgxc=
github.com/projectcalico/kube-controllers v3.8.8+incompatible h1:ZbCg0wJ+gd7i81CB6vOASiUN//oR4ZBl+wEdy0Vk1uI=
github.com/projectcalico/kube-controllers v3.8.8+incompatible/go.mod h1:ZEafKeKN5wiNARRw1LZP8l10uEfp04C7redU848MMZw=
github.com/projectcalico/libcalico-go v1.7.2-0.20191104213956-8f81e1e344ce h1:O/R67iwUe8TvZwgKbDB2cvF2/8L8PR4zVOcBtYEHD5Y=
github.com/projectcalico/libcalico-go v1.7.2-0.20191104213956-8f81e1e344ce/go.mod h1:z4tuFqrAg/423AMSaDamY5LgqeOZ5ETui6iOxDwJ/ag=
github.com/prometheus/client_golang v0.9.4 h1:Y8E/JaaPbmFSW2V81Ab/d8yZFYQQGbni1b1jPcG9Y6A=
......
approvers:
- magicsong
- zheng1
reviewers:
- magicsong
- zheng1
labels:
- area/deploy
- area/networking
\ No newline at end of file
bases:
- ../crds
resources:
- network.yaml
- rbac/role.yaml
- rbac/role_binding.yaml
generatorOptions:
disableNameSuffixHash: true
secretGenerator:
- name: calico-etcd-secrets
files:
- etcd-ca=etcd/ca
- etcd-key=etcd/key
- etcd-cert=etcd/crt
type: Opaque
patchesStrategicMerge:
- patch_image_name.yaml
namespace: network-test-f22e8ea9
apiVersion: v1
kind: Namespace
metadata:
name: network-system
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: network-manager
namespace: network-system
labels:
control-plane: network-manager
spec:
selector:
matchLabels:
control-plane: network-manager
replicas: 1
template:
metadata:
labels:
control-plane: network-manager
spec:
nodeSelector:
node-role.kubernetes.io/master: ""
hostNetwork: true
tolerations:
- key: "CriticalAddonsOnly"
operator: "Exists"
- key: "node-role.kubernetes.io/master"
effect: NoSchedule
containers:
- command:
- /ks-network
args:
- -v=4
- np-provider=calico
image: network:latest
imagePullPolicy: Always
name: manager
resources:
limits:
cpu: 100m
memory: 30Mi
requests:
cpu: 100m
memory: 20Mi
volumeMounts:
- mountPath: /calicocerts
name: etcd-certs
readOnly: true
terminationGracePeriodSeconds: 10
volumes:
- name: etcd-certs
secret:
secretName: calico-etcd-secrets
defaultMode: 0400
apiVersion: apps/v1
kind: Deployment
metadata:
name: network-manager
namespace: network-system
spec:
template:
spec:
containers:
# Change the value of image field below to your controller image URL
- image: magicsong/ks-network:f22e8ea9
name: manager
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: manager-rolebinding
subjects:
- kind: ServiceAccount
name: default
namespace: network-test-f22e8ea9
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
creationTimestamp: null
name: network-manager
rules:
- apiGroups:
- network.kubesphere.io
resources:
- namespacenetworkpolicies
- workspacenetworkpolicies
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
- apiGroups:
- tenant.kubesphere.io
resources:
- workspaces
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: manager-rolebinding
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: net-manager-role
subjects:
- kind: ServiceAccount
name: default
namespace: network-system
\ No newline at end of file
bases:
- ../crds
resources:
- network.yaml
- role.yaml
patchesStrategicMerge:
- patch_image_name.yaml
namespace: network-test-f22e8ea9
apiVersion: v1
kind: Namespace
metadata:
name: network-system
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: network-manager
namespace: network-system
labels:
control-plane: network-manager
spec:
selector:
matchLabels:
control-plane: network-manager
replicas: 1
template:
metadata:
labels:
control-plane: network-manager
spec:
nodeSelector:
node-role.kubernetes.io/master: ""
tolerations:
- key: "CriticalAddonsOnly"
operator: "Exists"
- key: "node-role.kubernetes.io/master"
effect: NoSchedule
serviceAccountName: network-manager
containers:
- command:
- /ks-network
args:
- -v=4
- np-provider=calico
- datastore-type=k8s
image: network:latest
imagePullPolicy: Always
name: manager
resources:
limits:
cpu: 100m
memory: 30Mi
requests:
cpu: 100m
memory: 20Mi
terminationGracePeriodSeconds: 10
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: net-role-binding
namespace: network-system
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: network-manager
subjects:
- kind: ServiceAccount
name: network-manager
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: network-manager
\ No newline at end of file
apiVersion: apps/v1
kind: Deployment
metadata:
name: network-manager
namespace: network-system
spec:
template:
spec:
containers:
# Change the value of image field below to your controller image URL
- image: magicsong/ks-network:f22e8ea9
name: manager
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: net-role-binding
subjects:
- kind: ServiceAccount
name: network-manager
namespace: network-test-f22e8ea9
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
creationTimestamp: null
name: network-manager
rules:
- apiGroups:
- crd.projectcalico.org
resources:
- clusterinformations
- felixconfigurations
- globalfelixconfigs
- globalnetworkpolicies
- globalnetworksets
- hostendpoints
- ipamblocks
- ippools
- networkpolicies
- networksets
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
- apiGroups:
- network.kubesphere.io
resources:
- namespacenetworkpolicies
- workspacenetworkpolicies
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
- apiGroups:
- tenant.kubesphere.io
resources:
- workspaces
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
resources:
- wsnp.yaml
- nsnp.yaml
\ No newline at end of file
此差异已折叠。
此差异已折叠。
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: net-manager-role
rules:
- apiGroups:
- network.kubesphere.io
resources:
- namespacenetworkpolicies
- workspacenetworkpolicies
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
- apiGroups:
- tenant.kubesphere.io
resources:
- workspaces
verbs:
- create
- delete
- get
- list
- patch
- update
- watch
package v1alpha1
import (
corev1 "k8s.io/api/core/v1"
"kubesphere.io/kubesphere/pkg/apis/network/v1alpha1/numorstring"
)
// A Rule encapsulates a set of match criteria and an action. Both selector-based security Policy
// and security Profiles reference rules - separated out as a list of rules for both
// ingress and egress packet matching.
//
// Each positive match criteria has a negated version, prefixed with ”Not”. All the match
// criteria within a rule must be satisfied for a packet to match. A single rule can contain
// the positive and negative version of a match and both must be satisfied for the rule to match.
type Rule struct {
Action Action `json:"action" validate:"action"`
// IPVersion is an optional field that restricts the rule to only match a specific IP
// version.
IPVersion *int `json:"ipVersion,omitempty" validate:"omitempty,ipVersion"`
// Protocol is an optional field that restricts the rule to only apply to traffic of
// a specific IP protocol. Required if any of the EntityRules contain Ports
// (because ports only apply to certain protocols).
//
// Must be one of these string values: "TCP", "UDP", "ICMP", "ICMPv6", "SCTP", "UDPLite"
// or an integer in the range 1-255.
Protocol *corev1.Protocol `json:"protocol,omitempty" validate:"omitempty"`
// ICMP is an optional field that restricts the rule to apply to a specific type and
// code of ICMP traffic. This should only be specified if the Protocol field is set to
// "ICMP" or "ICMPv6".
ICMP *ICMPFields `json:"icmp,omitempty" validate:"omitempty"`
// NotProtocol is the negated version of the Protocol field.
NotProtocol *corev1.Protocol `json:"notProtocol,omitempty" validate:"omitempty"`
// NotICMP is the negated version of the ICMP field.
NotICMP *ICMPFields `json:"notICMP,omitempty" validate:"omitempty"`
// Source contains the match criteria that apply to source entity.
Source EntityRule `json:"source,omitempty" validate:"omitempty"`
// Destination contains the match criteria that apply to destination entity.
Destination EntityRule `json:"destination,omitempty" validate:"omitempty"`
// HTTP contains match criteria that apply to HTTP requests.
HTTP *HTTPMatch `json:"http,omitempty" validate:"omitempty"`
}
// HTTPPath specifies an HTTP path to match. It may be either of the form:
// exact: <path>: which matches the path exactly or
// prefix: <path-prefix>: which matches the path prefix
type HTTPPath struct {
Exact string `json:"exact,omitempty" validate:"omitempty"`
Prefix string `json:"prefix,omitempty" validate:"omitempty"`
}
// HTTPMatch is an optional field that apply only to HTTP requests
// The Methods and Path fields are joined with AND
type HTTPMatch struct {
// Methods is an optional field that restricts the rule to apply only to HTTP requests that use one of the listed
// HTTP Methods (e.g. GET, PUT, etc.)
// Multiple methods are OR'd together.
Methods []string `json:"methods,omitempty" validate:"omitempty"`
// Paths is an optional field that restricts the rule to apply to HTTP requests that use one of the listed
// HTTP Paths.
// Multiple paths are OR'd together.
// e.g:
// - exact: /foo
// - prefix: /bar
// NOTE: Each entry may ONLY specify either a `exact` or a `prefix` match. The validator will check for it.
Paths []HTTPPath `json:"paths,omitempty" validate:"omitempty"`
}
// ICMPFields defines structure for ICMP and NotICMP sub-struct for ICMP code and type
type ICMPFields struct {
// Match on a specific ICMP type. For example a value of 8 refers to ICMP Echo Request
// (i.e. pings).
Type *int `json:"type,omitempty" validate:"omitempty,gte=0,lte=254"`
// Match on a specific ICMP code. If specified, the Type value must also be specified.
// This is a technical limitation imposed by the kernel’s iptables firewall, which
// Calico uses to enforce the rule.
Code *int `json:"code,omitempty" validate:"omitempty,gte=0,lte=255"`
}
// An EntityRule is a sub-component of a Rule comprising the match criteria specific
// to a particular entity (that is either the source or destination).
//
// A source EntityRule matches the source endpoint and originating traffic.
// A destination EntityRule matches the destination endpoint and terminating traffic.
type EntityRule struct {
// Nets is an optional field that restricts the rule to only apply to traffic that
// originates from (or terminates at) IP addresses in any of the given subnets.
Nets []string `json:"nets,omitempty" validate:"omitempty,dive,net"`
// Selector is an optional field that contains a selector expression (see Policy for
// sample syntax). Only traffic that originates from (terminates at) endpoints matching
// the selector will be matched.
//
// Note that: in addition to the negated version of the Selector (see NotSelector below), the
// selector expression syntax itself supports negation. The two types of negation are subtly
// different. One negates the set of matched endpoints, the other negates the whole match:
//
// Selector = "!has(my_label)" matches packets that are from other Calico-controlled
// endpoints that do not have the label “my_label”.
//
// NotSelector = "has(my_label)" matches packets that are not from Calico-controlled
// endpoints that do have the label “my_label”.
//
// The effect is that the latter will accept packets from non-Calico sources whereas the
// former is limited to packets from Calico-controlled endpoints.
Selector string `json:"selector,omitempty" validate:"omitempty,selector"`
// NamespaceSelector is an optional field that contains a selector expression. Only traffic
// that originates from (or terminates at) endpoints within the selected namespaces will be
// matched. When both NamespaceSelector and Selector are defined on the same rule, then only
// workload endpoints that are matched by both selectors will be selected by the rule.
//
// For NetworkPolicy, an empty NamespaceSelector implies that the Selector is limited to selecting
// only workload endpoints in the same namespace as the NetworkPolicy.
//
// For GlobalNetworkPolicy, an empty NamespaceSelector implies the Selector applies to workload
// endpoints across all namespaces.
NamespaceSelector string `json:"namespaceSelector,omitempty" validate:"omitempty,selector"`
// Ports is an optional field that restricts the rule to only apply to traffic that has a
// source (destination) port that matches one of these ranges/values. This value is a
// list of integers or strings that represent ranges of ports.
//
// Since only some protocols have ports, if any ports are specified it requires the
// Protocol match in the Rule to be set to "TCP" or "UDP".
Ports []numorstring.Port `json:"ports,omitempty" validate:"omitempty,dive"`
// NotNets is the negated version of the Nets field.
NotNets []string `json:"notNets,omitempty" validate:"omitempty,dive,net"`
// NotSelector is the negated version of the Selector field. See Selector field for
// subtleties with negated selectors.
NotSelector string `json:"notSelector,omitempty" validate:"omitempty,selector"`
// NotPorts is the negated version of the Ports field.
// Since only some protocols have ports, if any ports are specified it requires the
// Protocol match in the Rule to be set to "TCP" or "UDP".
NotPorts []numorstring.Port `json:"notPorts,omitempty" validate:"omitempty,dive"`
// ServiceAccounts is an optional field that restricts the rule to only apply to traffic that originates from (or
// terminates at) a pod running as a matching service account.
ServiceAccounts *ServiceAccountMatch `json:"serviceAccounts,omitempty" validate:"omitempty"`
}
type ServiceAccountMatch struct {
// Names is an optional field that restricts the rule to only apply to traffic that originates from (or terminates
// at) a pod running as a service account whose name is in the list.
Names []string `json:"names,omitempty" validate:"omitempty"`
// Selector is an optional field that restricts the rule to only apply to traffic that originates from
// (or terminates at) a pod running as a service account that matches the given label selector.
// If both Names and Selector are specified then they are AND'ed.
Selector string `json:"selector,omitempty" validate:"omitempty,selector"`
}
type Action string
const (
Allow Action = "Allow"
Deny = "Deny"
Log = "Log"
Pass = "Pass"
)
type PolicyType string
const (
PolicyTypeIngress PolicyType = "Ingress"
PolicyTypeEgress PolicyType = "Egress"
)
......@@ -17,68 +17,114 @@ limitations under the License.
package v1alpha1
import (
k8snet "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// All types in this file is copy from calicoapi as we use calico to policy
const (
ResourceKindNamespaceNetworkPolicy = "NamespaceNetworkPolicy"
ResourceSingularNamespaceNetworkPolicy = "namespacenetworkpolicy"
ResourcePluralNamespaceNetworkPolicy = "namespacenetworkpolicies"
)
// NamespaceNetworkPolicySpec defines the desired state of NamespaceNetworkPolicy
// NamespaceNetworkPolicySpec provides the specification of a NamespaceNetworkPolicy
type NamespaceNetworkPolicySpec struct {
// Order is an optional field that specifies the order in which the policy is applied.
// Policies with higher "order" are applied after those with lower
// order. If the order is omitted, it may be considered to be "infinite" - i.e. the
// policy will be applied last. Policies with identical order will be applied in
// alphanumerical order based on the Policy "Name".
Order *int `json:"order,omitempty"`
// The ordered set of ingress rules. Each rule contains a set of packet match criteria and
// a corresponding action to apply.
Ingress []Rule `json:"ingress,omitempty" validate:"omitempty,dive"`
// The ordered set of egress rules. Each rule contains a set of packet match criteria and
// a corresponding action to apply.
Egress []Rule `json:"egress,omitempty" validate:"omitempty,dive"`
// The selector is an expression used to pick pick out the endpoints that the policy should
// be applied to.
//
// Selector expressions follow this syntax:
//
// label == "string_literal" -> comparison, e.g. my_label == "foo bar"
// label != "string_literal" -> not equal; also matches if label is not present
// label in { "a", "b", "c", ... } -> true if the value of label X is one of "a", "b", "c"
// label not in { "a", "b", "c", ... } -> true if the value of label X is not one of "a", "b", "c"
// has(label_name) -> True if that label is present
// ! expr -> negation of expr
// expr && expr -> Short-circuit and
// expr || expr -> Short-circuit or
// ( expr ) -> parens for grouping
// all() or the empty selector -> matches all endpoints.
//
// Label names are allowed to contain alphanumerics, -, _ and /. String literals are more permissive
// but they do not support escape characters.
//
// Examples (with made-up labels):
//
// type == "webserver" && deployment == "prod"
// type in {"frontend", "backend"}
// deployment != "dev"
// ! has(label_name)
Selector string `json:"selector" validate:"selector"`
// Types indicates whether this policy applies to ingress, or to egress, or to both. When
// not explicitly specified (and so the value on creation is empty or nil), Calico defaults
// Types according to what Ingress and Egress are present in the policy. The
// default is:
//
// - [ PolicyTypeIngress ], if there are no Egress rules (including the case where there are
// also no Ingress rules)
//
// - [ PolicyTypeEgress ], if there are Egress rules but no Ingress rules
//
// - [ PolicyTypeIngress, PolicyTypeEgress ], if there are both Ingress and Egress rules.
//
// When the policy is read back again, Types will always be one of these values, never empty
// or nil.
Types []PolicyType `json:"types,omitempty" validate:"omitempty,dive,policyType"`
// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster
// Important: Run "make" to regenerate code after modifying this file
// List of ingress rules to be applied to the selected pods. Traffic is allowed to
// a pod if there are no NetworkPolicies selecting the pod
// (and cluster policy otherwise allows the traffic), OR if the traffic source is
// the pod's local node, OR if the traffic matches at least one ingress rule
// across all of the NetworkPolicy objects whose podSelector matches the pod. If
// this field is empty then this NetworkPolicy does not allow any traffic (and serves
// solely to ensure that the pods it selects are isolated by default)
// +optional
Ingress []NetworkPolicyIngressRule `json:"ingress,omitempty" protobuf:"bytes,1,rep,name=ingress"`
// List of egress rules to be applied to the selected pods. Outgoing traffic is
// allowed if there are no NetworkPolicies selecting the pod (and cluster policy
// otherwise allows the traffic), OR if the traffic matches at least one egress rule
// across all of the NetworkPolicy objects whose podSelector matches the pod. If
// this field is empty then this NetworkPolicy limits all outgoing traffic (and serves
// solely to ensure that the pods it selects are isolated by default).
// This field is beta-level in 1.8
// +optional
Egress []NetworkPolicyEgressRule `json:"egress,omitempty" protobuf:"bytes,2,rep,name=egress"`
// List of rule types that the NetworkPolicy relates to.
// Valid options are "Ingress", "Egress", or "Ingress,Egress".
// If this field is not specified, it will default based on the existence of Ingress or Egress rules;
// policies that contain an Egress section are assumed to affect Egress, and all policies
// (whether or not they contain an Ingress section) are assumed to affect Ingress.
// If you want to write an egress-only policy, you must explicitly specify policyTypes [ "Egress" ].
// Likewise, if you want to write a policy that specifies that no egress is allowed,
// you must specify a policyTypes value that include "Egress" (since such a policy would not include
// an Egress section and would otherwise default to just [ "Ingress" ]).
// This field is beta-level in 1.8
// +optional
PolicyTypes []k8snet.PolicyType `json:"policyTypes,omitempty" protobuf:"bytes,3,rep,name=policyTypes,casttype=PolicyType"`
}
// NetworkPolicyIngressRule describes a particular set of traffic that is allowed to the pods
// matched by a NetworkPolicySpec's podSelector. The traffic must match both ports and from.
type NetworkPolicyIngressRule struct {
// List of ports which should be made accessible on the pods selected for this
// rule. Each item in this list is combined using a logical OR. If this field is
// empty or missing, this rule matches all ports (traffic not restricted by port).
// If this field is present and contains at least one item, then this rule allows
// traffic only if the traffic matches at least one port in the list.
// +optional
Ports []k8snet.NetworkPolicyPort `json:"ports,omitempty" protobuf:"bytes,1,rep,name=ports"`
// List of sources which should be able to access the pods selected for this rule.
// Items in this list are combined using a logical OR operation. If this field is
// empty or missing, this rule matches all sources (traffic not restricted by
// source). If this field is present and contains at least one item, this rule
// allows traffic only if the traffic matches at least one item in the from list.
// +optional
From []NetworkPolicyPeer `json:"from,omitempty" protobuf:"bytes,2,rep,name=from"`
}
// NetworkPolicyEgressRule describes a particular set of traffic that is allowed out of pods
// matched by a NetworkPolicySpec's podSelector. The traffic must match both ports and to.
// This type is beta-level in 1.8
type NetworkPolicyEgressRule struct {
// List of destination ports for outgoing traffic.
// Each item in this list is combined using a logical OR. If this field is
// empty or missing, this rule matches all ports (traffic not restricted by port).
// If this field is present and contains at least one item, then this rule allows
// traffic only if the traffic matches at least one port in the list.
// +optional
Ports []k8snet.NetworkPolicyPort `json:"ports,omitempty" protobuf:"bytes,1,rep,name=ports"`
// List of destinations for outgoing traffic of pods selected for this rule.
// Items in this list are combined using a logical OR operation. If this field is
// empty or missing, this rule matches all destinations (traffic not restricted by
// destination). If this field is present and contains at least one item, this rule
// allows traffic only if the traffic matches at least one item in the to list.
// +optional
To []NetworkPolicyPeer `json:"to,omitempty" protobuf:"bytes,2,rep,name=to"`
}
type NamespaceSelector struct {
Name string `json:"name" protobuf:"bytes,1,name=name"`
}
type ServiceSelector struct {
Name string `json:"name" protobuf:"bytes,1,name=name"`
Namespace string `json:"namespace" protobuf:"bytes,2,name=namespace"`
}
// NetworkPolicyPeer describes a peer to allow traffic from. Only certain combinations of
// fields are allowed
type NetworkPolicyPeer struct {
// +optional
NamespaceSelector *NamespaceSelector `json:"namespace,omitempty" protobuf:"bytes,1,opt,name=namespace"`
// IPBlock defines policy on a particular IPBlock. If this field is set then
// neither of the other fields can be.
// +optional
IPBlock *k8snet.IPBlock `json:"ipBlock,omitempty" protobuf:"bytes,2,rep,name=ipBlock"`
ServiceSelector *ServiceSelector `json:"service,omitempty" protobuf:"bytes,3,opt,name=service"`
}
// +genclient
......
// Copyright (c) 2016 Tigera, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package numorstring
import (
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
)
type ASNumber uint32
// ASNumberFromString creates an ASNumber struct from a string value. The
// string value may simply be a number or may be the ASN in dotted notation.
func ASNumberFromString(s string) (ASNumber, error) {
if num, err := strconv.ParseUint(s, 10, 32); err == nil {
return ASNumber(num), nil
}
parts := strings.Split(s, ".")
if len(parts) != 2 {
msg := fmt.Sprintf("invalid AS Number format (%s)", s)
return 0, errors.New(msg)
}
if num1, err := strconv.ParseUint(parts[0], 10, 16); err != nil {
msg := fmt.Sprintf("invalid AS Number format (%s)", s)
return 0, errors.New(msg)
} else if num2, err := strconv.ParseUint(parts[1], 10, 16); err != nil {
msg := fmt.Sprintf("invalid AS Number format (%s)", s)
return 0, errors.New(msg)
} else {
return ASNumber((num1 << 16) + num2), nil
}
}
// UnmarshalJSON implements the json.Unmarshaller uinterface.
func (a *ASNumber) UnmarshalJSON(b []byte) error {
if err := json.Unmarshal(b, (*uint32)(a)); err == nil {
return nil
} else {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
if v, err := ASNumberFromString(s); err != nil {
return err
} else {
*a = v
return nil
}
}
}
// String returns the string value, or the Itoa of the uint value.
func (a ASNumber) String() string {
return strconv.FormatUint(uint64(a), 10)
}
// Copyright (c) 2016 Tigera, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
Package numorstring implements a set of type definitions that in YAML or JSON
format may be represented by either a number or a string.
*/
package numorstring
// Copyright (c) 2016-2017 Tigera, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package numorstring_test
import (
"encoding/json"
"fmt"
"reflect"
. "github.com/onsi/ginkgo/extensions/table"
. "github.com/onsi/gomega"
"github.com/projectcalico/libcalico-go/lib/numorstring"
)
func init() {
asNumberType := reflect.TypeOf(numorstring.ASNumber(0))
protocolType := reflect.TypeOf(numorstring.Protocol{})
portType := reflect.TypeOf(numorstring.Port{})
// Perform tests of JSON unmarshaling of the various field types.
DescribeTable("NumOrStringJSONUnmarshaling",
func(jtext string, typ reflect.Type, expected interface{}) {
// Create a new field type and invoke the unmarshaller interface
// directly (this covers a couple more error cases than calling
// through json.Unmarshal.
new := reflect.New(typ)
u := new.Interface().(json.Unmarshaler)
err := u.UnmarshalJSON([]byte(jtext))
if expected != nil {
Expect(err).To(BeNil(),
"expected json unmarshal to not error")
Expect(new.Elem().Interface()).To(Equal(expected),
"expected value not same as json unmarshalled value")
} else {
Expect(err).ToNot(BeNil(),
"expected json unmarshal to error")
}
},
// ASNumber tests.
Entry("should accept 0 AS number as int", "0", asNumberType, numorstring.ASNumber(0)),
Entry("should accept 4294967295 AS number as int", "4294967295", asNumberType, numorstring.ASNumber(4294967295)),
Entry("should accept 0 AS number as string", "\"0\"", asNumberType, numorstring.ASNumber(0)),
Entry("should accept 4294967295 AS number as string", "\"4294967295\"", asNumberType, numorstring.ASNumber(4294967295)),
Entry("should accept 1.10 AS number as string", "\"1.10\"", asNumberType, numorstring.ASNumber(65546)),
Entry("should accept 00.00 AS number as string", "\"00.00\"", asNumberType, numorstring.ASNumber(0)),
Entry("should accept 00.01 AS number as string", "\"00.01\"", asNumberType, numorstring.ASNumber(1)),
Entry("should accept 65535.65535 AS number as string", "\"65535.65535\"", asNumberType, numorstring.ASNumber(4294967295)),
Entry("should reject 1.1.1 AS number as string", "\"1.1.1\"", asNumberType, nil),
Entry("should reject 65536.65535 AS number as string", "\"65536.65535\"", asNumberType, nil),
Entry("should reject 65535.65536 AS number as string", "\"65535.65536\"", asNumberType, nil),
Entry("should reject 0.-1 AS number as string", "\"0.-1\"", asNumberType, nil),
Entry("should reject -1 AS number as int", "-1", asNumberType, nil),
Entry("should reject 4294967296 AS number as int", "4294967296", asNumberType, nil),
// Port tests.
Entry("should accept 0 port as int", "0", portType, numorstring.SinglePort(0)),
Entry("should accept 65535 port as int", "65535", portType, numorstring.SinglePort(65535)),
Entry("should accept 0:65535 port range as string", "\"0:65535\"", portType, portFromRange(0, 65535)),
Entry("should accept 1:10 port range as string", "\"1:10\"", portType, portFromRange(1, 10)),
Entry("should accept foo-bar as named port", "\"foo-bar\"", portType, numorstring.NamedPort("foo-bar")),
Entry("should reject -1 port as int", "-1", portType, nil),
Entry("should reject 65536 port as int", "65536", portType, nil),
Entry("should reject 0:65536 port range as string", "\"0:65536\"", portType, nil),
Entry("should reject -1:65535 port range as string", "\"-1:65535\"", portType, nil),
Entry("should reject 10:1 port range as string", "\"10:1\"", portType, nil),
Entry("should reject 1:2:3 port range as string", "\"1:2:3\"", portType, nil),
Entry("should reject bad named port string", "\"*\"", portType, nil),
Entry("should reject bad port string", "\"1:2", portType, nil),
// Protocol tests. Invalid integer values will be stored as strings.
Entry("should accept 0 protocol as int", "0", protocolType, numorstring.ProtocolFromInt(0)),
Entry("should accept 255 protocol as int", "255", protocolType, numorstring.ProtocolFromInt(255)),
Entry("should accept tcp protocol as string", "\"TCP\"", protocolType, numorstring.ProtocolFromString("TCP")),
Entry("should accept tcp protocol as string", "\"TCP\"", protocolType, numorstring.ProtocolFromString("TCP")),
Entry("should accept 0 protocol as string", "\"0\"", protocolType, numorstring.ProtocolFromInt(0)),
Entry("should accept 0 protocol as string", "\"255\"", protocolType, numorstring.ProtocolFromInt(255)),
Entry("should accept 256 protocol as string", "\"256\"", protocolType, numorstring.ProtocolFromString("256")),
Entry("should reject bad protocol string", "\"25", protocolType, nil),
)
// Perform tests of JSON marshaling of the various field types.
DescribeTable("NumOrStringJSONMarshaling",
func(field interface{}, jtext string) {
b, err := json.Marshal(field)
if jtext != "" {
Expect(err).To(BeNil(),
"expected json marshal to not error")
Expect(string(b)).To(Equal(jtext),
"expected json not same as marshalled value")
} else {
Expect(err).ToNot(BeNil(),
"expected json marshal to error")
}
},
// ASNumber tests.
Entry("should marshal ASN of 0", numorstring.ASNumber(0), "0"),
Entry("should marshal ASN of 4294967295", numorstring.ASNumber(4294967295), "4294967295"),
// Port tests.
Entry("should marshal port of 0", numorstring.SinglePort(0), "0"),
Entry("should marshal port of 65535", portFromRange(65535, 65535), "65535"),
Entry("should marshal port of 10", portFromString("10"), "10"),
Entry("should marshal port range of 10:20", portFromRange(10, 20), "\"10:20\""),
Entry("should marshal port range of 20:30", portFromRange(20, 30), "\"20:30\""),
Entry("should marshal named port", numorstring.NamedPort("foobar"), `"foobar"`),
// Protocol tests.
Entry("should marshal protocol of 0", numorstring.ProtocolFromInt(0), "0"),
Entry("should marshal protocol of udp", numorstring.ProtocolFromString("UDP"), "\"UDP\""),
)
// Perform tests of Stringer interface various field types.
DescribeTable("NumOrStringStringify",
func(field interface{}, s string) {
a := fmt.Sprint(field)
Expect(a).To(Equal(s),
"expected String() value to match")
},
// ASNumber tests.
Entry("should stringify ASN of 0", numorstring.ASNumber(0), "0"),
Entry("should stringify ASN of 4294967295", numorstring.ASNumber(4294967295), "4294967295"),
// Port tests.
Entry("should stringify port of 20", numorstring.SinglePort(20), "20"),
Entry("should stringify port range of 10:20", portFromRange(10, 20), "10:20"),
// Protocol tests.
Entry("should stringify protocol of 0", numorstring.ProtocolFromInt(0), "0"),
Entry("should stringify protocol of udp", numorstring.ProtocolFromString("UDP"), "UDP"),
)
// Perform tests of Protocols supporting ports.
DescribeTable("NumOrStringProtocolsSupportingPorts",
func(protocol numorstring.Protocol, supportsPorts bool) {
Expect(protocol.SupportsPorts()).To(Equal(supportsPorts),
"expected protocol port support to match")
},
Entry("protocol 6 supports ports", numorstring.ProtocolFromInt(6), true),
Entry("protocol 17 supports ports", numorstring.ProtocolFromInt(17), true),
Entry("protocol udp supports ports", numorstring.ProtocolFromString("UDP"), true),
Entry("protocol udp supports ports", numorstring.ProtocolFromString("TCP"), true),
Entry("protocol foo does not support ports", numorstring.ProtocolFromString("foo"), false),
Entry("protocol 2 does not support ports", numorstring.ProtocolFromInt(2), false),
)
// Perform tests of Protocols FromString method.
DescribeTable("NumOrStringProtocols FromString is not case sensitive",
func(input, expected string) {
Expect(numorstring.ProtocolFromString(input).StrVal).To(Equal(expected),
"expected parsed protocol to match")
},
Entry("protocol udp -> UDP", "udp", "UDP"),
Entry("protocol tcp -> TCP", "tcp", "TCP"),
Entry("protocol updlite -> UDPLite", "udplite", "UDPLite"),
Entry("unknown protocol xxxXXX", "xxxXXX", "xxxXXX"),
)
// Perform tests of Protocols FromStringV1 method.
DescribeTable("NumOrStringProtocols FromStringV1 is lowercase",
func(input, expected string) {
Expect(numorstring.ProtocolFromStringV1(input).StrVal).To(Equal(expected),
"expected parsed protocol to match")
},
Entry("protocol udp -> UDP", "UDP", "udp"),
Entry("protocol tcp -> TCP", "TCP", "tcp"),
Entry("protocol updlite -> UDPLite", "UDPLite", "udplite"),
Entry("unknown protocol xxxXXX", "xxxXXX", "xxxxxx"),
)
// Perform tests of Protocols ToV1 method.
DescribeTable("NumOrStringProtocols FromStringV1 is lowercase",
func(input, expected numorstring.Protocol) {
Expect(input.ToV1()).To(Equal(expected),
"expected parsed protocol to match")
},
// Protocol tests.
Entry("protocol udp -> UDP", numorstring.ProtocolFromInt(2), numorstring.ProtocolFromInt(2)),
Entry("protocol tcp -> TCP", numorstring.ProtocolFromString("TCP"), numorstring.ProtocolFromStringV1("TCP")),
)
}
func portFromRange(minPort, maxPort uint16) numorstring.Port {
p, _ := numorstring.PortFromRange(minPort, maxPort)
return p
}
func portFromString(s string) numorstring.Port {
p, _ := numorstring.PortFromString(s)
return p
}
// Copyright (c) 2016-2017 Tigera, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package numorstring
import (
"encoding/json"
"errors"
"fmt"
"regexp"
"strconv"
)
// Port represents either a range of numeric ports or a named port.
//
// - For a named port, set the PortName, leaving MinPort and MaxPort as 0.
// - For a port range, set MinPort and MaxPort to the (inclusive) port numbers. Set
// PortName to "".
// - For a single port, set MinPort = MaxPort and PortName = "".
type Port struct {
MinPort uint16 `json:"minPort,omitempty"`
MaxPort uint16 `json:"maxPort,omitempty"`
PortName string `validate:"omitempty,portName" json:"portName,omitempty"`
}
// SinglePort creates a Port struct representing a single port.
func SinglePort(port uint16) Port {
return Port{MinPort: port, MaxPort: port}
}
func NamedPort(name string) Port {
return Port{PortName: name}
}
// PortFromRange creates a Port struct representing a range of ports.
func PortFromRange(minPort, maxPort uint16) (Port, error) {
port := Port{MinPort: minPort, MaxPort: maxPort}
if minPort > maxPort {
msg := fmt.Sprintf("minimum port number (%d) is greater than maximum port number (%d) in port range", minPort, maxPort)
return port, errors.New(msg)
}
return port, nil
}
var (
allDigits = regexp.MustCompile(`^\d+$`)
portRange = regexp.MustCompile(`^(\d+):(\d+)$`)
nameRegex = regexp.MustCompile("^[a-zA-Z0-9_.-]{1,128}$")
)
// PortFromString creates a Port struct from its string representation. A port
// may either be single value "1234", a range of values "100:200" or a named port: "name".
func PortFromString(s string) (Port, error) {
if allDigits.MatchString(s) {
// Port is all digits, it should parse as a single port.
num, err := strconv.ParseUint(s, 10, 16)
if err != nil {
msg := fmt.Sprintf("invalid port format (%s)", s)
return Port{}, errors.New(msg)
}
return SinglePort(uint16(num)), nil
}
if groups := portRange.FindStringSubmatch(s); len(groups) > 0 {
// Port matches <digits>:<digits>, it should parse as a range of ports.
if pmin, err := strconv.ParseUint(groups[1], 10, 16); err != nil {
msg := fmt.Sprintf("invalid minimum port number in range (%s)", s)
return Port{}, errors.New(msg)
} else if pmax, err := strconv.ParseUint(groups[2], 10, 16); err != nil {
msg := fmt.Sprintf("invalid maximum port number in range (%s)", s)
return Port{}, errors.New(msg)
} else {
return PortFromRange(uint16(pmin), uint16(pmax))
}
}
if !nameRegex.MatchString(s) {
msg := fmt.Sprintf("invalid name for named port (%s)", s)
return Port{}, errors.New(msg)
}
return NamedPort(s), nil
}
// UnmarshalJSON implements the json.Unmarshaller interface.
func (p *Port) UnmarshalJSON(b []byte) error {
if b[0] == '"' {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
if v, err := PortFromString(s); err != nil {
return err
} else {
*p = v
return nil
}
}
// It's not a string, it must be a single int.
var i uint16
if err := json.Unmarshal(b, &i); err != nil {
return err
}
v := SinglePort(i)
*p = v
return nil
}
// MarshalJSON implements the json.Marshaller interface.
func (p Port) MarshalJSON() ([]byte, error) {
if p.PortName != "" {
return json.Marshal(p.PortName)
} else if p.MinPort == p.MaxPort {
return json.Marshal(p.MinPort)
} else {
return json.Marshal(p.String())
}
}
// String returns the string value. If the min and max port are the same
// this returns a single string representation of the port number, otherwise
// if returns a colon separated range of ports.
func (p Port) String() string {
if p.PortName != "" {
return p.PortName
} else if p.MinPort == p.MaxPort {
return strconv.FormatUint(uint64(p.MinPort), 10)
} else {
return fmt.Sprintf("%d:%d", p.MinPort, p.MaxPort)
}
}
// Copyright (c) 2016 Tigera, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package numorstring
import "strings"
const (
ProtocolUDP = "UDP"
ProtocolTCP = "TCP"
ProtocolICMP = "ICMP"
ProtocolICMPv6 = "ICMPv6"
ProtocolSCTP = "SCTP"
ProtocolUDPLite = "UDPLite"
ProtocolUDPV1 = "udp"
ProtocolTCPV1 = "tcp"
)
var (
allProtocolNames = []string{
ProtocolUDP,
ProtocolTCP,
ProtocolICMP,
ProtocolICMPv6,
ProtocolSCTP,
ProtocolUDPLite,
}
)
type Protocol Uint8OrString
// ProtocolFromInt creates a Protocol struct from an integer value.
func ProtocolFromInt(p uint8) Protocol {
return Protocol(
Uint8OrString{Type: NumOrStringNum, NumVal: p},
)
}
// ProtocolV3FromProtocolV1 creates a v3 Protocol from a v1 Protocol,
// while handling case conversion.
func ProtocolV3FromProtocolV1(p Protocol) Protocol {
if p.Type == NumOrStringNum {
return p
}
for _, n := range allProtocolNames {
if strings.ToLower(n) == strings.ToLower(p.StrVal) {
return Protocol(
Uint8OrString{Type: NumOrStringString, StrVal: n},
)
}
}
return p
}
// ProtocolFromString creates a Protocol struct from a string value.
func ProtocolFromString(p string) Protocol {
for _, n := range allProtocolNames {
if strings.ToLower(n) == strings.ToLower(p) {
return Protocol(
Uint8OrString{Type: NumOrStringString, StrVal: n},
)
}
}
// Unknown protocol - return the value unchanged. Validation should catch this.
return Protocol(
Uint8OrString{Type: NumOrStringString, StrVal: p},
)
}
// ProtocolFromStringV1 creates a Protocol struct from a string value (for the v1 API)
func ProtocolFromStringV1(p string) Protocol {
return Protocol(
Uint8OrString{Type: NumOrStringString, StrVal: strings.ToLower(p)},
)
}
// UnmarshalJSON implements the json.Unmarshaller interface.
func (p *Protocol) UnmarshalJSON(b []byte) error {
return (*Uint8OrString)(p).UnmarshalJSON(b)
}
// MarshalJSON implements the json.Marshaller interface.
func (p Protocol) MarshalJSON() ([]byte, error) {
return Uint8OrString(p).MarshalJSON()
}
// String returns the string value, or the Itoa of the int value.
func (p Protocol) String() string {
return (Uint8OrString)(p).String()
}
// String returns the string value, or the Itoa of the int value.
func (p Protocol) ToV1() Protocol {
if p.Type == NumOrStringNum {
return p
}
return ProtocolFromStringV1(p.StrVal)
}
// NumValue returns the NumVal if type Int, or if
// it is a String, will attempt a conversion to int.
func (p Protocol) NumValue() (uint8, error) {
return (Uint8OrString)(p).NumValue()
}
// SupportsProtocols returns whether this protocol supports ports. This returns true if
// the numerical or string verion of the protocol indicates TCP (6) or UDP (17).
func (p Protocol) SupportsPorts() bool {
num, err := p.NumValue()
if err == nil {
return num == 6 || num == 17
} else {
switch p.StrVal {
case ProtocolTCP, ProtocolUDP, ProtocolTCPV1, ProtocolUDPV1:
return true
}
return false
}
}
// Copyright (c) 2016 Tigera, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package numorstring
// Type represents the stored type of Int32OrString.
type NumOrStringType int
const (
NumOrStringNum NumOrStringType = iota // The structure holds a number.
NumOrStringString // The structure holds a string.
)
// Copyright (c) 2016 Tigera, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package numorstring
import (
"encoding/json"
"strconv"
)
// UInt8OrString is a type that can hold an uint8 or a string. When used in
// JSON or YAML marshalling and unmarshalling, it produces or consumes the
// inner type. This allows you to have, for example, a JSON field that can
// accept a name or number.
type Uint8OrString struct {
Type NumOrStringType
NumVal uint8
StrVal string
}
// UnmarshalJSON implements the json.Unmarshaller interface.
func (i *Uint8OrString) UnmarshalJSON(b []byte) error {
if b[0] == '"' {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
num, err := strconv.ParseUint(s, 10, 8)
if err == nil {
i.Type = NumOrStringNum
i.NumVal = uint8(num)
} else {
i.Type = NumOrStringString
i.StrVal = s
}
return nil
}
i.Type = NumOrStringNum
return json.Unmarshal(b, &i.NumVal)
}
// MarshalJSON implements the json.Marshaller interface.
func (i Uint8OrString) MarshalJSON() ([]byte, error) {
if num, err := i.NumValue(); err == nil {
return json.Marshal(num)
} else {
return json.Marshal(i.StrVal)
}
}
// String returns the string value, or the Itoa of the int value.
func (i Uint8OrString) String() string {
if i.Type == NumOrStringString {
return i.StrVal
}
return strconv.FormatUint(uint64(i.NumVal), 10)
}
// NumValue returns the NumVal if type Int, or if
// it is a String, will attempt a conversion to int.
func (i Uint8OrString) NumValue() (uint8, error) {
if i.Type == NumOrStringString {
num, err := strconv.ParseUint(i.StrVal, 10, 8)
return uint8(num), err
}
return i.NumVal, nil
}
......@@ -33,7 +33,7 @@ var c client.Client
func TestMain(m *testing.M) {
t := &envtest.Environment{
CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "..", "kustomize", "network", "crds")},
CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "..", "config", "crds")},
}
err := SchemeBuilder.AddToScheme(scheme.Scheme)
......
/*
Copyright 2019 The KubeSphere authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1
import (
k8snetworkv1 "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
ResourceKindWorkspaceNetworkPolicy = "WorkspaceNetworkPolicy"
ResourceSingularWorkspaceNetworkPolicy = "workspacenetworkpolicy"
ResourcePluralWorkspaceNetworkPolicy = "workspacenetworkpolicies"
)
// WorkspaceNetworkPolicySpec defines the desired state of WorkspaceNetworkPolicy
type WorkspaceNetworkPolicySpec struct {
// Workspace specify the name of ws to apply this workspace network policy
Workspace string `json:"workspace,omitempty"`
// List of rule types that the WorkspaceNetworkPolicy relates to.
// Valid options are Ingress, Egress, or Ingress,Egress.
// If this field is not specified, it will default based on the existence of Ingress or Egress rules;
// policies that contain an Egress section are assumed to affect Egress, and all policies
// (whether or not they contain an Ingress section) are assumed to affect Ingress.
// If you want to write an egress-only policy, you must explicitly specify policyTypes [ "Egress" ].
// Likewise, if you want to write a policy that specifies that no egress is allowed,
// you must specify a policyTypes value that include "Egress" (since such a policy would not include
// an Egress section and would otherwise default to just [ "Ingress" ]).
// +optional
PolicyTypes []k8snetworkv1.PolicyType `json:"policyTypes,omitempty" protobuf:"bytes,4,rep,name=policyTypes,casttype=PolicyType"`
// List of ingress rules to be applied to the selected pods. Traffic is allowed to
// a pod if there are no NetworkPolicies selecting the pod
// (and cluster policy otherwise allows the traffic), OR if the traffic source is
// the pod's local node, OR if the traffic matches at least one ingress rule
// across all of the NetworkPolicy objects whose podSelector matches the pod. If
// this field is empty then this NetworkPolicy does not allow any traffic (and serves
// solely to ensure that the pods it selects are isolated by default)
// +optional
Ingress []WorkspaceNetworkPolicyIngressRule `json:"ingress,omitempty" protobuf:"bytes,2,rep,name=ingress"`
// List of egress rules to be applied to the selected pods. Outgoing traffic is
// allowed if there are no NetworkPolicies selecting the pod (and cluster policy
// otherwise allows the traffic), OR if the traffic matches at least one egress rule
// across all of the NetworkPolicy objects whose podSelector matches the pod. If
// this field is empty then this NetworkPolicy limits all outgoing traffic (and serves
// solely to ensure that the pods it selects are isolated by default).
// This field is beta-level in 1.8
// +optional
Egress []WorkspaceNetworkPolicyEgressRule `json:"egress,omitempty" protobuf:"bytes,3,rep,name=egress"`
}
// WorkspaceNetworkPolicyStatus defines the observed state of WorkspaceNetworkPolicy
type WorkspaceNetworkPolicyStatus struct {
// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
// Important: Run "make" to regenerate code after modifying this file
}
// +genclient
// +genclient:nonNamespaced
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// WorkspaceNetworkPolicy is a set of network policies applied to the scope to workspace
// +k8s:openapi-gen=true
// +kubebuilder:resource:categories="networking",scope="Cluster",shortName="wsnp"
type WorkspaceNetworkPolicy struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec WorkspaceNetworkPolicySpec `json:"spec,omitempty"`
Status WorkspaceNetworkPolicyStatus `json:"status,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// WorkspaceNetworkPolicyList contains a list of WorkspaceNetworkPolicy
type WorkspaceNetworkPolicyList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []WorkspaceNetworkPolicy `json:"items"`
}
// WorkspaceNetworkPolicyIngressRule describes a particular set of traffic that is allowed to the pods
// matched by a WorkspaceNetworkPolicySpec's podSelector. The traffic must match both ports and from.
type WorkspaceNetworkPolicyIngressRule struct {
// List of ports which should be made accessible on the pods selected for this
// rule. Each item in this list is combined using a logical OR. If this field is
// empty or missing, this rule matches all ports (traffic not restricted by port).
// If this field is present and contains at least one item, then this rule allows
// traffic only if the traffic matches at least one port in the list.
// +optional
Ports []k8snetworkv1.NetworkPolicyPort `json:"ports,omitempty" protobuf:"bytes,1,rep,name=ports"`
// List of sources which should be able to access the pods selected for this rule.
// Items in this list are combined using a logical OR operation. If this field is
// empty or missing, this rule matches all sources (traffic not restricted by
// source). If this field is present and contains at least on item, this rule
// allows traffic only if the traffic matches at least one item in the from list.
// +optional
From []WorkspaceNetworkPolicyPeer `json:"from,omitempty" protobuf:"bytes,2,rep,name=from"`
}
// WorkspaceNetworkPolicyPeer describes a peer to allow traffic from. Only certain combinations of
// fields are allowed. It is same as 'NetworkPolicyPeer' in k8s but with an additional field 'WorkspaceSelector'
type WorkspaceNetworkPolicyPeer struct {
k8snetworkv1.NetworkPolicyPeer `json:",inline"`
WorkspaceSelector *metav1.LabelSelector `json:"workspaceSelector,omitempty"`
}
// WorkspaceNetworkPolicyEgressRule describes a particular set of traffic that is allowed out of pods
// matched by a WorkspaceNetworkPolicySpec's podSelector. The traffic must match both ports and to.
type WorkspaceNetworkPolicyEgressRule struct {
// List of ports which should be made accessible on the pods selected for this
// rule. Each item in this list is combined using a logical OR. If this field is
// empty or missing, this rule matches all ports (traffic not restricted by port).
// If this field is present and contains at least one item, then this rule allows
// traffic only if the traffic matches at least one port in the list.
// +optional
Ports []k8snetworkv1.NetworkPolicyPort `json:"ports,omitempty" protobuf:"bytes,1,rep,name=ports"`
// List of sources which should be able to access the pods selected for this rule.
// Items in this list are combined using a logical OR operation. If this field is
// empty or missing, this rule matches all sources (traffic not restricted by
// source). If this field is present and contains at least on item, this rule
// allows traffic only if the traffic matches at least one item in the from list.
// +optional
To []WorkspaceNetworkPolicyPeer `json:"from,omitempty" protobuf:"bytes,2,rep,name=from"`
}
func init() {
SchemeBuilder.Register(&WorkspaceNetworkPolicy{}, &WorkspaceNetworkPolicyList{})
}
/*
Copyright 2019 The KubeSphere authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1
import (
"testing"
"github.com/onsi/gomega"
"golang.org/x/net/context"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
)
func TestStorageWorkspaceNetworkPolicy(t *testing.T) {
key := types.NamespacedName{
Name: "foo",
}
created := &WorkspaceNetworkPolicy{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
}}
g := gomega.NewGomegaWithT(t)
// Test Create
fetched := &WorkspaceNetworkPolicy{}
g.Expect(c.Create(context.TODO(), created)).To(gomega.Succeed())
g.Expect(c.Get(context.TODO(), key, fetched)).To(gomega.Succeed())
g.Expect(fetched).To(gomega.Equal(created))
// Test Updating the Labels
updated := fetched.DeepCopy()
updated.Labels = map[string]string{"hello": "world"}
g.Expect(c.Update(context.TODO(), updated)).To(gomega.Succeed())
g.Expect(c.Get(context.TODO(), key, fetched)).To(gomega.Succeed())
g.Expect(fetched).To(gomega.Equal(updated))
// Test Delete
g.Expect(c.Delete(context.TODO(), fetched)).To(gomega.Succeed())
g.Expect(c.Get(context.TODO(), key, fetched)).ToNot(gomega.Succeed())
}
......@@ -16,129 +16,22 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by controller-gen. DO NOT EDIT.
// Code generated by deepcopy-gen. DO NOT EDIT.
package v1alpha1
import (
"k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
v1 "k8s.io/api/networking/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
"kubesphere.io/kubesphere/pkg/apis/network/v1alpha1/numorstring"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *EntityRule) DeepCopyInto(out *EntityRule) {
*out = *in
if in.Nets != nil {
in, out := &in.Nets, &out.Nets
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.Ports != nil {
in, out := &in.Ports, &out.Ports
*out = make([]numorstring.Port, len(*in))
copy(*out, *in)
}
if in.NotNets != nil {
in, out := &in.NotNets, &out.NotNets
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.NotPorts != nil {
in, out := &in.NotPorts, &out.NotPorts
*out = make([]numorstring.Port, len(*in))
copy(*out, *in)
}
if in.ServiceAccounts != nil {
in, out := &in.ServiceAccounts, &out.ServiceAccounts
*out = new(ServiceAccountMatch)
(*in).DeepCopyInto(*out)
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EntityRule.
func (in *EntityRule) DeepCopy() *EntityRule {
if in == nil {
return nil
}
out := new(EntityRule)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *HTTPMatch) DeepCopyInto(out *HTTPMatch) {
*out = *in
if in.Methods != nil {
in, out := &in.Methods, &out.Methods
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.Paths != nil {
in, out := &in.Paths, &out.Paths
*out = make([]HTTPPath, len(*in))
copy(*out, *in)
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPMatch.
func (in *HTTPMatch) DeepCopy() *HTTPMatch {
if in == nil {
return nil
}
out := new(HTTPMatch)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *HTTPPath) DeepCopyInto(out *HTTPPath) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPPath.
func (in *HTTPPath) DeepCopy() *HTTPPath {
if in == nil {
return nil
}
out := new(HTTPPath)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ICMPFields) DeepCopyInto(out *ICMPFields) {
*out = *in
if in.Type != nil {
in, out := &in.Type, &out.Type
*out = new(int)
**out = **in
}
if in.Code != nil {
in, out := &in.Code, &out.Code
*out = new(int)
**out = **in
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ICMPFields.
func (in *ICMPFields) DeepCopy() *ICMPFields {
if in == nil {
return nil
}
out := new(ICMPFields)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NamespaceNetworkPolicy) DeepCopyInto(out *NamespaceNetworkPolicy) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NamespaceNetworkPolicy.
......@@ -171,6 +64,7 @@ func (in *NamespaceNetworkPolicyList) DeepCopyInto(out *NamespaceNetworkPolicyLi
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NamespaceNetworkPolicyList.
......@@ -194,30 +88,26 @@ func (in *NamespaceNetworkPolicyList) DeepCopyObject() runtime.Object {
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NamespaceNetworkPolicySpec) DeepCopyInto(out *NamespaceNetworkPolicySpec) {
*out = *in
if in.Order != nil {
in, out := &in.Order, &out.Order
*out = new(int)
**out = **in
}
if in.Ingress != nil {
in, out := &in.Ingress, &out.Ingress
*out = make([]Rule, len(*in))
*out = make([]NetworkPolicyIngressRule, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.Egress != nil {
in, out := &in.Egress, &out.Egress
*out = make([]Rule, len(*in))
*out = make([]NetworkPolicyEgressRule, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.Types != nil {
in, out := &in.Types, &out.Types
*out = make([]PolicyType, len(*in))
if in.PolicyTypes != nil {
in, out := &in.PolicyTypes, &out.PolicyTypes
*out = make([]v1.PolicyType, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NamespaceNetworkPolicySpec.
......@@ -231,255 +121,124 @@ func (in *NamespaceNetworkPolicySpec) DeepCopy() *NamespaceNetworkPolicySpec {
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Rule) DeepCopyInto(out *Rule) {
func (in *NamespaceSelector) DeepCopyInto(out *NamespaceSelector) {
*out = *in
if in.IPVersion != nil {
in, out := &in.IPVersion, &out.IPVersion
*out = new(int)
**out = **in
}
if in.Protocol != nil {
in, out := &in.Protocol, &out.Protocol
*out = new(v1.Protocol)
**out = **in
}
if in.ICMP != nil {
in, out := &in.ICMP, &out.ICMP
*out = new(ICMPFields)
(*in).DeepCopyInto(*out)
}
if in.NotProtocol != nil {
in, out := &in.NotProtocol, &out.NotProtocol
*out = new(v1.Protocol)
**out = **in
}
if in.NotICMP != nil {
in, out := &in.NotICMP, &out.NotICMP
*out = new(ICMPFields)
(*in).DeepCopyInto(*out)
}
in.Source.DeepCopyInto(&out.Source)
in.Destination.DeepCopyInto(&out.Destination)
if in.HTTP != nil {
in, out := &in.HTTP, &out.HTTP
*out = new(HTTPMatch)
(*in).DeepCopyInto(*out)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Rule.
func (in *Rule) DeepCopy() *Rule {
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NamespaceSelector.
func (in *NamespaceSelector) DeepCopy() *NamespaceSelector {
if in == nil {
return nil
}
out := new(Rule)
out := new(NamespaceSelector)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ServiceAccountMatch) DeepCopyInto(out *ServiceAccountMatch) {
*out = *in
if in.Names != nil {
in, out := &in.Names, &out.Names
*out = make([]string, len(*in))
copy(*out, *in)
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServiceAccountMatch.
func (in *ServiceAccountMatch) DeepCopy() *ServiceAccountMatch {
if in == nil {
return nil
}
out := new(ServiceAccountMatch)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *WorkspaceNetworkPolicy) DeepCopyInto(out *WorkspaceNetworkPolicy) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
out.Status = in.Status
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkspaceNetworkPolicy.
func (in *WorkspaceNetworkPolicy) DeepCopy() *WorkspaceNetworkPolicy {
if in == nil {
return nil
}
out := new(WorkspaceNetworkPolicy)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *WorkspaceNetworkPolicy) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *WorkspaceNetworkPolicyEgressRule) DeepCopyInto(out *WorkspaceNetworkPolicyEgressRule) {
func (in *NetworkPolicyEgressRule) DeepCopyInto(out *NetworkPolicyEgressRule) {
*out = *in
if in.Ports != nil {
in, out := &in.Ports, &out.Ports
*out = make([]networkingv1.NetworkPolicyPort, len(*in))
*out = make([]v1.NetworkPolicyPort, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.To != nil {
in, out := &in.To, &out.To
*out = make([]WorkspaceNetworkPolicyPeer, len(*in))
*out = make([]NetworkPolicyPeer, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkspaceNetworkPolicyEgressRule.
func (in *WorkspaceNetworkPolicyEgressRule) DeepCopy() *WorkspaceNetworkPolicyEgressRule {
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NetworkPolicyEgressRule.
func (in *NetworkPolicyEgressRule) DeepCopy() *NetworkPolicyEgressRule {
if in == nil {
return nil
}
out := new(WorkspaceNetworkPolicyEgressRule)
out := new(NetworkPolicyEgressRule)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *WorkspaceNetworkPolicyIngressRule) DeepCopyInto(out *WorkspaceNetworkPolicyIngressRule) {
func (in *NetworkPolicyIngressRule) DeepCopyInto(out *NetworkPolicyIngressRule) {
*out = *in
if in.Ports != nil {
in, out := &in.Ports, &out.Ports
*out = make([]networkingv1.NetworkPolicyPort, len(*in))
*out = make([]v1.NetworkPolicyPort, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.From != nil {
in, out := &in.From, &out.From
*out = make([]WorkspaceNetworkPolicyPeer, len(*in))
*out = make([]NetworkPolicyPeer, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkspaceNetworkPolicyIngressRule.
func (in *WorkspaceNetworkPolicyIngressRule) DeepCopy() *WorkspaceNetworkPolicyIngressRule {
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NetworkPolicyIngressRule.
func (in *NetworkPolicyIngressRule) DeepCopy() *NetworkPolicyIngressRule {
if in == nil {
return nil
}
out := new(WorkspaceNetworkPolicyIngressRule)
out := new(NetworkPolicyIngressRule)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *WorkspaceNetworkPolicyList) DeepCopyInto(out *WorkspaceNetworkPolicyList) {
func (in *NetworkPolicyPeer) DeepCopyInto(out *NetworkPolicyPeer) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]WorkspaceNetworkPolicy, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkspaceNetworkPolicyList.
func (in *WorkspaceNetworkPolicyList) DeepCopy() *WorkspaceNetworkPolicyList {
if in == nil {
return nil
}
out := new(WorkspaceNetworkPolicyList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *WorkspaceNetworkPolicyList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
if in.NamespaceSelector != nil {
in, out := &in.NamespaceSelector, &out.NamespaceSelector
*out = new(NamespaceSelector)
**out = **in
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *WorkspaceNetworkPolicyPeer) DeepCopyInto(out *WorkspaceNetworkPolicyPeer) {
*out = *in
in.NetworkPolicyPeer.DeepCopyInto(&out.NetworkPolicyPeer)
if in.WorkspaceSelector != nil {
in, out := &in.WorkspaceSelector, &out.WorkspaceSelector
*out = new(metav1.LabelSelector)
if in.IPBlock != nil {
in, out := &in.IPBlock, &out.IPBlock
*out = new(v1.IPBlock)
(*in).DeepCopyInto(*out)
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkspaceNetworkPolicyPeer.
func (in *WorkspaceNetworkPolicyPeer) DeepCopy() *WorkspaceNetworkPolicyPeer {
if in == nil {
return nil
}
out := new(WorkspaceNetworkPolicyPeer)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *WorkspaceNetworkPolicySpec) DeepCopyInto(out *WorkspaceNetworkPolicySpec) {
*out = *in
if in.PolicyTypes != nil {
in, out := &in.PolicyTypes, &out.PolicyTypes
*out = make([]networkingv1.PolicyType, len(*in))
copy(*out, *in)
}
if in.Ingress != nil {
in, out := &in.Ingress, &out.Ingress
*out = make([]WorkspaceNetworkPolicyIngressRule, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.Egress != nil {
in, out := &in.Egress, &out.Egress
*out = make([]WorkspaceNetworkPolicyEgressRule, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
if in.ServiceSelector != nil {
in, out := &in.ServiceSelector, &out.ServiceSelector
*out = new(ServiceSelector)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkspaceNetworkPolicySpec.
func (in *WorkspaceNetworkPolicySpec) DeepCopy() *WorkspaceNetworkPolicySpec {
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NetworkPolicyPeer.
func (in *NetworkPolicyPeer) DeepCopy() *NetworkPolicyPeer {
if in == nil {
return nil
}
out := new(WorkspaceNetworkPolicySpec)
out := new(NetworkPolicyPeer)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *WorkspaceNetworkPolicyStatus) DeepCopyInto(out *WorkspaceNetworkPolicyStatus) {
func (in *ServiceSelector) DeepCopyInto(out *ServiceSelector) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkspaceNetworkPolicyStatus.
func (in *WorkspaceNetworkPolicyStatus) DeepCopy() *WorkspaceNetworkPolicyStatus {
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServiceSelector.
func (in *ServiceSelector) DeepCopy() *ServiceSelector {
if in == nil {
return nil
}
out := new(WorkspaceNetworkPolicyStatus)
out := new(ServiceSelector)
in.DeepCopyInto(out)
return out
}
......@@ -32,10 +32,6 @@ func (c *FakeNetworkV1alpha1) NamespaceNetworkPolicies(namespace string) v1alpha
return &FakeNamespaceNetworkPolicies{c, namespace}
}
func (c *FakeNetworkV1alpha1) WorkspaceNetworkPolicies() v1alpha1.WorkspaceNetworkPolicyInterface {
return &FakeWorkspaceNetworkPolicies{c}
}
// RESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *FakeNetworkV1alpha1) RESTClient() rest.Interface {
......
......@@ -19,5 +19,3 @@ limitations under the License.
package v1alpha1
type NamespaceNetworkPolicyExpansion interface{}
type WorkspaceNetworkPolicyExpansion interface{}
......@@ -27,7 +27,6 @@ import (
type NetworkV1alpha1Interface interface {
RESTClient() rest.Interface
NamespaceNetworkPoliciesGetter
WorkspaceNetworkPoliciesGetter
}
// NetworkV1alpha1Client is used to interact with features provided by the network.kubesphere.io group.
......@@ -39,10 +38,6 @@ func (c *NetworkV1alpha1Client) NamespaceNetworkPolicies(namespace string) Names
return newNamespaceNetworkPolicies(c, namespace)
}
func (c *NetworkV1alpha1Client) WorkspaceNetworkPolicies() WorkspaceNetworkPolicyInterface {
return newWorkspaceNetworkPolicies(c)
}
// NewForConfig creates a new NetworkV1alpha1Client for the given config.
func NewForConfig(c *rest.Config) (*NetworkV1alpha1Client, error) {
config := *c
......
......@@ -91,8 +91,6 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource
// Group=network.kubesphere.io, Version=v1alpha1
case networkv1alpha1.SchemeGroupVersion.WithResource("namespacenetworkpolicies"):
return &genericInformer{resource: resource.GroupResource(), informer: f.Network().V1alpha1().NamespaceNetworkPolicies().Informer()}, nil
case networkv1alpha1.SchemeGroupVersion.WithResource("workspacenetworkpolicies"):
return &genericInformer{resource: resource.GroupResource(), informer: f.Network().V1alpha1().WorkspaceNetworkPolicies().Informer()}, nil
// Group=servicemesh.kubesphere.io, Version=v1alpha2
case servicemeshv1alpha2.SchemeGroupVersion.WithResource("servicepolicies"):
......
此差异已折叠。
此差异已折叠。
package provider
// +kubebuilder:rbac:groups="crd.projectcalico.org",resources=globalfelixconfigs;felixconfigurations;ippools;ipamblocks;globalnetworkpolicies;globalnetworksets;networkpolicies;networksets;clusterinformations;hostendpoints,verbs=get;list;watch;create;patch;update;delete
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册