未验证 提交 61d827db 编写于 作者: K KubeSphere CI Bot 提交者: GitHub

Merge pull request #2195 from zheng1/refactor_op

Refactor with OpenPitrix
......@@ -69,6 +69,9 @@ deploy: manifests
generate:
go generate ./pkg/... ./cmd/...
mockgen:
mockgen -package=openpitrix -source=pkg/simple/client/openpitrix/openpitrix.go -destination=pkg/simple/client/openpitrix/mock.go
deepcopy:
GO111MODULE=on go install -mod=vendor k8s.io/code-generator/cmd/deepcopy-gen
${GOPATH}/bin/deepcopy-gen -i kubesphere.io/kubesphere/pkg/apis/... -h ./hack/boilerplate.go.txt -O zz_generated.deepcopy
......
......@@ -20,7 +20,7 @@ import (
"context"
"fmt"
"github.com/spf13/cobra"
v1 "k8s.io/api/core/v1"
"k8s.io/api/core/v1"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/uuid"
"k8s.io/client-go/tools/leaderelection"
......@@ -40,7 +40,6 @@ import (
"kubesphere.io/kubesphere/pkg/simple/client/devops"
"kubesphere.io/kubesphere/pkg/simple/client/devops/jenkins"
"kubesphere.io/kubesphere/pkg/simple/client/k8s"
"kubesphere.io/kubesphere/pkg/simple/client/openpitrix"
"kubesphere.io/kubesphere/pkg/simple/client/s3"
"kubesphere.io/kubesphere/pkg/utils/term"
"os"
......@@ -103,15 +102,6 @@ func Run(s *options.KubeSphereControllerManagerOptions, stopCh <-chan struct{})
return err
}
var openpitrixClient openpitrix.Client
if s.OpenPitrixOptions != nil && !s.OpenPitrixOptions.IsEmpty() {
openpitrixClient, err = openpitrix.NewClient(s.OpenPitrixOptions)
if err != nil {
klog.Errorf("Failed to create openpitrix client %v", err)
return err
}
}
var devopsClient devops.Interface
if s.DevopsOptions != nil && len(s.DevopsOptions.Host) != 0 {
devopsClient, err = jenkins.NewDevopsClient(s.DevopsOptions)
......@@ -151,7 +141,7 @@ func Run(s *options.KubeSphereControllerManagerOptions, stopCh <-chan struct{})
klog.Fatal("Unable to create workspace controller")
}
err = namespace.Add(mgr, openpitrixClient)
err = namespace.Add(mgr)
if err != nil {
klog.Fatal("Unable to create namespace controller")
}
......
......@@ -8,32 +8,27 @@ go 1.12
require (
code.cloudfoundry.org/bytefmt v0.0.0-20190710193110-1eb035ffe2b6
github.com/Masterminds/semver v1.5.0 // indirect
github.com/Microsoft/go-winio v0.4.12 // indirect
github.com/NYTimes/gziphandler v1.1.1 // indirect
github.com/PuerkitoBio/goquery v1.5.0
github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a
github.com/aws/aws-sdk-go v1.22.2
github.com/aws/aws-sdk-go v1.25.21
github.com/beevik/etree v1.1.0
github.com/container-storage-interface/spec v1.2.0
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/docker/distribution v2.7.1+incompatible
github.com/docker/docker v1.4.2-0.20190822205725-ed20165a37b4
github.com/docker/go-connections v0.3.0 // indirect
github.com/docker/spdystream v0.0.0-20181023171402-6480d4af844c // indirect
github.com/elastic/go-elasticsearch/v5 v5.6.1
github.com/elastic/go-elasticsearch/v6 v6.8.2
github.com/elastic/go-elasticsearch/v7 v7.3.0
github.com/elazarl/goproxy v0.0.0-20190711103511-473e67f1d7d2 // indirect
github.com/elazarl/goproxy/ext v0.0.0-20190711103511-473e67f1d7d2 // indirect
github.com/emicklei/go-restful v2.9.5+incompatible
github.com/emicklei/go-restful v2.11.1+incompatible
github.com/emicklei/go-restful-openapi v1.0.0
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/zapr v0.1.1 // indirect
github.com/go-openapi/loads v0.19.2
github.com/go-openapi/spec v0.19.3
github.com/go-openapi/spec v0.19.4
github.com/go-openapi/strfmt v0.19.3
github.com/go-openapi/validate v0.19.5
github.com/go-redis/redis v6.15.2+incompatible
......@@ -46,7 +41,7 @@ require (
github.com/google/go-querystring v1.0.0 // indirect
github.com/google/uuid v1.1.1
github.com/gorilla/mux v1.7.1 // indirect
github.com/gorilla/websocket v1.4.0
github.com/gorilla/websocket v1.4.1
github.com/hashicorp/go-version v1.2.0 // indirect
github.com/json-iterator/go v1.1.9
github.com/kelseyhightower/envconfig v1.4.0 // indirect
......@@ -56,22 +51,20 @@ require (
github.com/kubesphere/sonargo v0.0.2
github.com/lib/pq v1.2.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/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/patrickmn/go-cache v2.1.0+incompatible // indirect
github.com/pkg/errors v0.9.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 v1.2.1
github.com/prometheus/common v0.4.1
github.com/prometheus/prometheus v1.8.2
github.com/sony/sonyflake v0.0.0-20181109022403-6d5bd6181009
github.com/sony/sonyflake v1.0.0
github.com/speps/go-hashids v2.0.0+incompatible
github.com/spf13/cobra v0.0.5
github.com/spf13/pflag v1.0.5
......@@ -79,7 +72,7 @@ require (
github.com/stretchr/testify v1.4.0
github.com/syndtr/goleveldb v1.0.0 // indirect
github.com/xanzy/ssh-agent v0.2.1 // indirect
golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392
golang.org/x/crypto v0.0.0-20200220183623-bac4c82f6975
golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45
google.golang.org/grpc v1.26.0
......@@ -102,9 +95,7 @@ require (
k8s.io/klog v1.0.0
k8s.io/kube-openapi v0.0.0-20191107075043-30be4d16710a
k8s.io/kubectl v0.17.3
kubesphere.io/im v0.1.0 // indirect
openpitrix.io/iam v0.1.0 // indirect
openpitrix.io/openpitrix v0.4.1-0.20190920134345-4d2be6e4965c
openpitrix.io/openpitrix v0.4.9-0.20200611125425-ae07f141e797
sigs.k8s.io/controller-runtime v0.5.0
sigs.k8s.io/controller-tools v0.2.4
sigs.k8s.io/kubefed v0.2.0-alpha.1
......@@ -123,13 +114,20 @@ replace (
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/goutils => github.com/Masterminds/goutils v1.1.0
github.com/Masterminds/semver => github.com/Masterminds/semver v1.5.0
github.com/Masterminds/semver/v3 => github.com/Masterminds/semver/v3 v3.0.1
github.com/Masterminds/sprig/v3 => github.com/Masterminds/sprig/v3 v3.0.0
github.com/Masterminds/vcs => github.com/Masterminds/vcs v1.13.0
github.com/Microsoft/go-winio => github.com/Microsoft/go-winio v0.4.12
github.com/Microsoft/hcsshim => github.com/Microsoft/hcsshim v0.8.6
github.com/NYTimes/gziphandler => github.com/NYTimes/gziphandler v1.1.1
github.com/Nvveen/Gotty => github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5
github.com/OneOfOne/xxhash => github.com/OneOfOne/xxhash v1.2.2
github.com/PuerkitoBio/goquery => github.com/PuerkitoBio/goquery v1.5.0
github.com/PuerkitoBio/purell => github.com/PuerkitoBio/purell v1.1.1
github.com/PuerkitoBio/urlesc => github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578
github.com/Shopify/logrus-bugsnag => github.com/Shopify/logrus-bugsnag v0.0.0-20171204204709-577dee27f20d
github.com/StackExchange/wmi => github.com/StackExchange/wmi v0.0.0-20170410192909-ea383cf3ba6e
github.com/alcortesm/tgz => github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7
github.com/alecthomas/template => github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc
......@@ -145,11 +143,17 @@ replace (
github.com/bitly/go-simplejson => github.com/bitly/go-simplejson v0.5.0
github.com/blang/semver => github.com/blang/semver v3.5.0+incompatible
github.com/bmizerany/assert => github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869
github.com/bshuster-repo/logrus-logstash-hook => github.com/bshuster-repo/logrus-logstash-hook v0.4.1
github.com/bugsnag/bugsnag-go => github.com/bugsnag/bugsnag-go v1.5.0
github.com/bugsnag/panicwrap => github.com/bugsnag/panicwrap v1.2.0
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/chai2010/jsonmap => github.com/chai2010/jsonmap v1.0.0
github.com/client9/misspell => github.com/client9/misspell v0.3.4
github.com/cockroachdb/datadriven => github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa
github.com/container-storage-interface/spec => github.com/container-storage-interface/spec v1.2.0
github.com/containerd/containerd => github.com/containerd/containerd v1.3.0
github.com/containerd/continuity => github.com/containerd/continuity v0.0.0-20181203112020-004b46473808
github.com/coreos/bbolt => github.com/coreos/bbolt v1.3.3
github.com/coreos/etcd => github.com/coreos/etcd v3.3.17+incompatible
github.com/coreos/go-oidc => github.com/coreos/go-oidc v2.1.0+incompatible
......@@ -158,15 +162,22 @@ 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/creack/pty => github.com/creack/pty v1.1.7
github.com/cyphar/filepath-securejoin => github.com/cyphar/filepath-securejoin v0.2.2
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/deislabs/oras => github.com/deislabs/oras v0.7.0
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
github.com/disintegration/imaging => github.com/disintegration/imaging v1.6.1
github.com/docker/cli => github.com/docker/cli v0.0.0-20190506213505-d88565df0c2d
github.com/docker/distribution => github.com/docker/distribution v2.7.1+incompatible
github.com/docker/docker => github.com/docker/engine v1.4.2-0.20190822205725-ed20165a37b4
github.com/docker/docker-credential-helpers => github.com/docker/docker-credential-helpers v0.6.1
github.com/docker/go-connections => github.com/docker/go-connections v0.3.0
github.com/docker/go-metrics => github.com/docker/go-metrics v0.0.0-20181218153428-b84716841b82
github.com/docker/go-units => github.com/docker/go-units v0.3.3
github.com/docker/libtrust => github.com/docker/libtrust v0.0.0-20160708172513-aabc10ec26b7
github.com/docker/spdystream => github.com/docker/spdystream v0.0.0-20181023171402-6480d4af844c
github.com/docopt/docopt-go => github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815
github.com/dustin/go-humanize => github.com/dustin/go-humanize v1.0.0
......@@ -186,7 +197,10 @@ replace (
github.com/fatih/structs => github.com/fatih/structs v1.1.0
github.com/flynn/go-shlex => github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568
github.com/fsnotify/fsnotify => github.com/fsnotify/fsnotify v1.4.7
github.com/garyburd/redigo => github.com/garyburd/redigo v1.6.0
github.com/ghodss/yaml => github.com/ghodss/yaml v1.0.0
github.com/gin-contrib/sse => github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3
github.com/gin-gonic/gin => github.com/gin-gonic/gin v1.4.0
github.com/gliderlabs/ssh => github.com/gliderlabs/ssh v0.1.1
github.com/globalsign/mgo => github.com/globalsign/mgo v0.0.0-20181015135952-eeefdecb41b8
github.com/go-kit/kit => github.com/go-kit/kit v0.8.0
......@@ -213,6 +227,7 @@ replace (
github.com/gobuffalo/flect => github.com/gobuffalo/flect v0.1.5
github.com/gobwas/glob => github.com/gobwas/glob v0.2.3
github.com/gocraft/dbr => github.com/gocraft/dbr v0.0.0-20180507214907-a0fd650918f6
github.com/gofrs/flock => github.com/gofrs/flock v0.7.1
github.com/gofrs/uuid => github.com/gofrs/uuid v3.2.0+incompatible
github.com/gogo/protobuf => github.com/gogo/protobuf v1.3.0
github.com/golang/example => github.com/golang/example v0.0.0-20170904185048-46695d81d1fa
......@@ -235,16 +250,19 @@ replace (
github.com/googleapis/gax-go/v2 => github.com/googleapis/gax-go/v2 v2.0.4
github.com/googleapis/gnostic => github.com/googleapis/gnostic v0.3.1
github.com/gophercloud/gophercloud => github.com/gophercloud/gophercloud v0.3.0
github.com/gorilla/handlers => github.com/gorilla/handlers v1.4.0
github.com/gorilla/mux => github.com/gorilla/mux v1.7.1
github.com/gorilla/websocket => github.com/gorilla/websocket v1.4.0
github.com/gosuri/uitable => github.com/gosuri/uitable v0.0.1
github.com/gregjones/httpcache => github.com/gregjones/httpcache v0.0.0-20170728041850-787624de3eb7
github.com/grpc-ecosystem/go-grpc-middleware => github.com/grpc-ecosystem/go-grpc-middleware v1.0.0
github.com/grpc-ecosystem/go-grpc-prometheus => github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0
github.com/grpc-ecosystem/grpc-gateway => github.com/grpc-ecosystem/grpc-gateway v1.9.6
github.com/grpc-ecosystem/grpc-gateway => github.com/grpc-ecosystem/grpc-gateway v1.11.3
github.com/hashicorp/go-version => github.com/hashicorp/go-version v1.2.0
github.com/hashicorp/golang-lru => github.com/hashicorp/golang-lru v0.5.3
github.com/hashicorp/hcl => github.com/hashicorp/hcl v1.0.0
github.com/hpcloud/tail => github.com/hpcloud/tail v1.0.0
github.com/huandu/xstrings => github.com/huandu/xstrings v1.2.0
github.com/imdario/mergo => github.com/imdario/mergo v0.3.7
github.com/inconshreveable/mousetrap => github.com/inconshreveable/mousetrap v1.0.0
github.com/jbenet/go-context => github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99
......@@ -284,11 +302,15 @@ replace (
github.com/mattn/go-colorable => github.com/mattn/go-colorable v0.1.2
github.com/mattn/go-isatty => github.com/mattn/go-isatty v0.0.8
github.com/mattn/go-runewidth => github.com/mattn/go-runewidth v0.0.0-20181025052659-b20a3daf6a39
github.com/mattn/go-shellwords => github.com/mattn/go-shellwords v1.0.5
github.com/mattn/go-sqlite3 => github.com/mattn/go-sqlite3 v1.11.0
github.com/matttproud/golang_protobuf_extensions => github.com/matttproud/golang_protobuf_extensions v1.0.1
github.com/miekg/dns => github.com/miekg/dns v0.0.0-20181005163659-0d29b283ac0f
github.com/mitchellh/copystructure => github.com/mitchellh/copystructure v1.0.0
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/mitchellh/reflectwalk => github.com/mitchellh/reflectwalk v1.0.0
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
github.com/modern-go/reflect2 => github.com/modern-go/reflect2 v1.0.1
......@@ -302,6 +324,7 @@ replace (
github.com/open-policy-agent/opa => github.com/open-policy-agent/opa v0.18.0
github.com/opencontainers/go-digest => github.com/opencontainers/go-digest v1.0.0-rc1
github.com/opencontainers/image-spec => github.com/opencontainers/image-spec v1.0.1
github.com/opencontainers/runc => github.com/opencontainers/runc v0.1.1
github.com/openshift/api => github.com/openshift/api v0.0.0-20180801171038-322a19404e37
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
......@@ -311,6 +334,7 @@ replace (
github.com/pelletier/go-toml => github.com/pelletier/go-toml v1.2.0
github.com/peterbourgon/diskv => github.com/peterbourgon/diskv v2.0.1+incompatible
github.com/peterh/liner => github.com/peterh/liner v0.0.0-20170211195444-bf27d3ba8e1d
github.com/phayes/freeport => github.com/phayes/freeport v0.0.0-20171002181615-b8543db493a5
github.com/philhofer/fwd => github.com/philhofer/fwd v1.0.0
github.com/pkg/errors => github.com/pkg/errors v0.8.1
github.com/pmezard/go-difflib => github.com/pmezard/go-difflib v1.0.0
......@@ -328,6 +352,7 @@ replace (
github.com/prometheus/prometheus => github.com/prometheus/prometheus v1.8.2
github.com/rcrowley/go-metrics => github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a
github.com/remyoudompheng/bigfft => github.com/remyoudompheng/bigfft v0.0.0-20170806203942-52369c62f446
github.com/robfig/cron => github.com/robfig/cron v1.2.0
github.com/rogpeppe/fastuuid => github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af
github.com/rogpeppe/go-charset => github.com/rogpeppe/go-charset v0.0.0-20180617210344-2471d30d28b4
github.com/russross/blackfriday => github.com/russross/blackfriday v1.5.2
......@@ -353,13 +378,21 @@ replace (
github.com/tinylib/msgp => github.com/tinylib/msgp v1.1.0
github.com/tmc/grpc-websocket-proxy => github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5
github.com/ugorji/go => github.com/ugorji/go v1.1.4
github.com/ugorji/go/codec => github.com/ugorji/go/codec v0.0.0-20190128213124-ee1426cffec0
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/xeipuuv/gojsonpointer => github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f
github.com/xeipuuv/gojsonreference => github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415
github.com/xeipuuv/gojsonschema => github.com/xeipuuv/gojsonschema v1.2.0
github.com/xenolf/lego => github.com/xenolf/lego v0.3.2-0.20160613233155-a9d8cec0e656
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
github.com/yvasiyarov/go-metrics => github.com/yvasiyarov/go-metrics v0.0.0-20150112132944-c25f46c4b940
github.com/yvasiyarov/gorelic => github.com/yvasiyarov/gorelic v0.0.6
github.com/yvasiyarov/newrelic_platform_go => github.com/yvasiyarov/newrelic_platform_go v0.0.0-20140908184405-b21fdbd4370f
go.etcd.io/bbolt => go.etcd.io/bbolt v1.3.3
go.etcd.io/etcd => go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738
go.opencensus.io => go.opencensus.io v0.21.0
......@@ -368,6 +401,7 @@ replace (
go.uber.org/zap => go.uber.org/zap v1.10.0
golang.org/x/crypto => golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2
golang.org/x/exp => golang.org/x/exp v0.0.0-20190121172915-509febef88a4
golang.org/x/image => golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81
golang.org/x/lint => golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f
golang.org/x/net => golang.org/x/net v0.0.0-20190620200207-3b0461eec859
golang.org/x/oauth2 => golang.org/x/oauth2 v0.0.0-20190402181905-9f3314589c9a
......@@ -386,16 +420,21 @@ replace (
google.golang.org/grpc => google.golang.org/grpc v1.23.1
gopkg.in/airbrake/gobrake.v2 => gopkg.in/airbrake/gobrake.v2 v2.0.9
gopkg.in/alecthomas/kingpin.v2 => gopkg.in/alecthomas/kingpin.v2 v2.2.6
gopkg.in/alexcesaro/quotedprintable.v3 => gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc
gopkg.in/asn1-ber.v1 => gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d
gopkg.in/check.v1 => gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15
gopkg.in/cheggaaa/pb.v1 => gopkg.in/cheggaaa/pb.v1 v1.0.25
gopkg.in/fsnotify.v1 => gopkg.in/fsnotify.v1 v1.4.7
gopkg.in/gemnasium/logrus-airbrake-hook.v2 => gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2
gopkg.in/go-playground/assert.v1 => gopkg.in/go-playground/assert.v1 v1.2.1
gopkg.in/go-playground/validator.v8 => gopkg.in/go-playground/validator.v8 v8.18.2
gopkg.in/go-playground/validator.v9 => gopkg.in/go-playground/validator.v9 v9.29.1
gopkg.in/gomail.v2 => gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
gopkg.in/inf.v0 => gopkg.in/inf.v0 v0.9.1
gopkg.in/mail.v2 => gopkg.in/mail.v2 v2.3.1
gopkg.in/natefinch/lumberjack.v2 => gopkg.in/natefinch/lumberjack.v2 v2.0.0
gopkg.in/resty.v1 => gopkg.in/resty.v1 v1.12.0
gopkg.in/square/go-jose.v1 => gopkg.in/square/go-jose.v1 v1.1.2
gopkg.in/square/go-jose.v2 => gopkg.in/square/go-jose.v2 v2.3.1
gopkg.in/src-d/go-billy.v4 => gopkg.in/src-d/go-billy.v4 v4.3.0
gopkg.in/src-d/go-git-fixtures.v3 => gopkg.in/src-d/go-git-fixtures.v3 v3.1.1
......@@ -407,6 +446,7 @@ replace (
gopkg.in/yaml.v2 => gopkg.in/yaml.v2 v2.2.8
gopkg.in/yaml.v3 => gopkg.in/yaml.v3 v3.0.0-20190905181640-827449938966
gotest.tools => gotest.tools v2.2.0+incompatible
helm.sh/helm/v3 => helm.sh/helm/v3 v3.0.1
honnef.co/go/tools => honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc
istio.io/api => istio.io/api v0.0.0-20191111210003-35e06ef8d838
istio.io/client-go => istio.io/client-go v0.0.0-20191113122552-9bd0ba57c3d2
......@@ -434,9 +474,12 @@ replace (
modernc.org/strutil => modernc.org/strutil v1.0.0
modernc.org/xc => modernc.org/xc v1.0.0
openpitrix.io/iam => openpitrix.io/iam v0.1.0
openpitrix.io/libqueue => openpitrix.io/libqueue v0.4.1
openpitrix.io/logger => openpitrix.io/logger v0.1.0
openpitrix.io/openpitrix => openpitrix.io/openpitrix v0.4.1-0.20190920134345-4d2be6e4965c
openpitrix.io/notification => openpitrix.io/notification v0.2.2
openpitrix.io/openpitrix => openpitrix.io/openpitrix v0.4.9-0.20200611125425-ae07f141e797
rsc.io/goversion => rsc.io/goversion v1.0.0
rsc.io/letsencrypt => rsc.io/letsencrypt v0.0.1
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
......
此差异已折叠。
......@@ -34,6 +34,7 @@ const (
WorkspaceLabelKey = "kubesphere.io/workspace"
NamespaceLabelKey = "kubesphere.io/namespace"
RuntimeLabelKey = "openpitrix.io/namespace"
DisplayNameAnnotationKey = "kubesphere.io/alias-name"
DescriptionAnnotationKey = "kubesphere.io/description"
CreatorAnnotationKey = "kubesphere.io/creator"
......
......@@ -18,8 +18,6 @@ package namespace
import (
"context"
"fmt"
"github.com/golang/protobuf/ptypes/wrappers"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
......@@ -29,9 +27,7 @@ import (
"k8s.io/klog"
"kubesphere.io/kubesphere/pkg/apis/tenant/v1alpha1"
"kubesphere.io/kubesphere/pkg/constants"
"kubesphere.io/kubesphere/pkg/simple/client/openpitrix"
"kubesphere.io/kubesphere/pkg/utils/sliceutil"
"openpitrix.io/openpitrix/pkg/pb"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
......@@ -48,16 +44,15 @@ import (
// Add creates a new Namespace Controller and adds it to the Manager with default RBAC. The Manager will set fields on the Controller
// and Start it when the Manager is Started.
func Add(mgr manager.Manager, openpitrixClient openpitrix.Client) error {
return add(mgr, newReconciler(mgr, openpitrixClient))
func Add(mgr manager.Manager) error {
return add(mgr, newReconciler(mgr))
}
// newReconciler returns a new reconcile.Reconciler
func newReconciler(mgr manager.Manager, openpitrixClient openpitrix.Client) reconcile.Reconciler {
func newReconciler(mgr manager.Manager) reconcile.Reconciler {
return &ReconcileNamespace{
Client: mgr.GetClient(),
scheme: mgr.GetScheme(),
openpitrixClient: openpitrixClient,
Client: mgr.GetClient(),
scheme: mgr.GetScheme(),
}
}
......@@ -83,8 +78,7 @@ var _ reconcile.Reconciler = &ReconcileNamespace{}
// ReconcileNamespace reconciles a Namespace object
type ReconcileNamespace struct {
client.Client
openpitrixClient openpitrix.Client
scheme *runtime.Scheme
scheme *runtime.Scheme
}
// Reconcile reads that state of the cluster for a Namespace object and makes changes based on the state read
......@@ -130,11 +124,6 @@ func (r *ReconcileNamespace) Reconcile(request reconcile.Request) (reconcile.Res
return reconcile.Result{}, err
}
// delete runtime
if err = r.deleteRuntime(instance); err != nil {
return reconcile.Result{}, err
}
// remove our finalizer from the list and update it.
instance.ObjectMeta.Finalizers = sliceutil.RemoveString(instance.ObjectMeta.Finalizers, func(item string) bool {
return item == finalizer
......@@ -153,13 +142,6 @@ func (r *ReconcileNamespace) Reconcile(request reconcile.Request) (reconcile.Res
return reconcile.Result{}, err
}
// skip if openpitrix is not enabled
if r.openpitrixClient != nil {
if err := r.checkAndCreateRuntime(instance); err != nil {
return reconcile.Result{}, err
}
}
return reconcile.Result{}, nil
}
......@@ -175,88 +157,6 @@ func (r *ReconcileNamespace) isControlledByWorkspace(namespace *corev1.Namespace
return true, nil
}
// Create openpitrix runtime
func (r *ReconcileNamespace) checkAndCreateRuntime(namespace *corev1.Namespace) error {
if runtimeId := namespace.Annotations[constants.OpenPitrixRuntimeAnnotationKey]; runtimeId != "" {
return nil
}
adminKubeConfigName := fmt.Sprintf("kubeconfig-%s", constants.AdminUserName)
runtimeCredentials, err := r.openpitrixClient.DescribeRuntimeCredentials(openpitrix.SystemContext(), &pb.DescribeRuntimeCredentialsRequest{SearchWord: &wrappers.StringValue{Value: adminKubeConfigName}, Limit: 1})
if err != nil {
klog.Error(fmt.Sprintf("create runtime, namespace: %s, error: %s", namespace.Name, err))
return err
}
var kubesphereRuntimeCredentialId string
// runtime credential exist
if len(runtimeCredentials.GetRuntimeCredentialSet()) > 0 {
kubesphereRuntimeCredentialId = runtimeCredentials.GetRuntimeCredentialSet()[0].GetRuntimeCredentialId().GetValue()
} else {
adminKubeConfig := corev1.ConfigMap{}
err := r.Get(context.TODO(), types.NamespacedName{Namespace: constants.KubeSphereControlNamespace, Name: adminKubeConfigName}, &adminKubeConfig)
if err != nil {
klog.Error(fmt.Sprintf("create runtime, namespace: %s, error: %s", namespace.Name, err))
return err
}
resp, err := r.openpitrixClient.CreateRuntimeCredential(openpitrix.SystemContext(), &pb.CreateRuntimeCredentialRequest{
Name: &wrappers.StringValue{Value: adminKubeConfigName},
Provider: &wrappers.StringValue{Value: "kubernetes"},
Description: &wrappers.StringValue{Value: "kubeconfig"},
RuntimeUrl: &wrappers.StringValue{Value: "kubesphere"},
RuntimeCredentialContent: &wrappers.StringValue{Value: adminKubeConfig.Data["config"]},
})
if err != nil {
klog.Error(fmt.Sprintf("create runtime, namespace: %s, error: %s", namespace.Name, err))
return err
}
kubesphereRuntimeCredentialId = resp.GetRuntimeCredentialId().GetValue()
}
// TODO runtime id is invalid when recreate runtime
runtimeId, err := r.openpitrixClient.CreateRuntime(openpitrix.SystemContext(), &pb.CreateRuntimeRequest{
Name: &wrappers.StringValue{Value: namespace.Name},
RuntimeCredentialId: &wrappers.StringValue{Value: kubesphereRuntimeCredentialId},
Provider: &wrappers.StringValue{Value: openpitrix.KubernetesProvider},
Zone: &wrappers.StringValue{Value: namespace.Name},
})
if err != nil {
klog.Error(fmt.Sprintf("create runtime, namespace: %s, error: %s", namespace.Name, err))
return err
}
klog.V(4).Infof("runtime created successfully, namespace: %s, runtime id: %s", namespace.Name, runtimeId)
return nil
}
// Delete openpitrix runtime
func (r *ReconcileNamespace) deleteRuntime(namespace *corev1.Namespace) error {
if runtimeId := namespace.Annotations[constants.OpenPitrixRuntimeAnnotationKey]; runtimeId != "" {
_, err := r.openpitrixClient.DeleteRuntimes(openpitrix.SystemContext(), &pb.DeleteRuntimesRequest{RuntimeId: []string{runtimeId}, Force: &wrappers.BoolValue{Value: true}})
if err == nil || openpitrix.IsNotFound(err) || openpitrix.IsDeleted(err) {
return nil
} else {
klog.Errorf("delete openpitrix runtime: %s, error: %s", runtimeId, err)
return err
}
}
return nil
}
// Create openpitrix runtime
func (r *ReconcileNamespace) checkAndBindWorkspace(namespace *corev1.Namespace) error {
workspaceName := namespace.Labels[constants.WorkspaceLabelKey]
......
/*
Copyright 2020 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 v1
import (
......@@ -10,7 +23,6 @@ import (
"kubesphere.io/kubesphere/pkg/api"
"kubesphere.io/kubesphere/pkg/constants"
"kubesphere.io/kubesphere/pkg/informers"
"kubesphere.io/kubesphere/pkg/models"
"kubesphere.io/kubesphere/pkg/models/openpitrix"
"kubesphere.io/kubesphere/pkg/server/errors"
"kubesphere.io/kubesphere/pkg/server/params"
......@@ -32,57 +44,40 @@ func newOpenpitrixHandler(factory informers.InformerFactory, opClient op.Client)
}
}
func (h *openpitrixHandler) ListApplications(request *restful.Request, response *restful.Response) {
limit, offset := params.ParsePaging(request)
namespace := request.PathParameter("namespace")
orderBy := params.GetStringValueWithDefault(request, params.OrderByParam, openpitrix.CreateTime)
reverse := params.GetBoolValueWithDefault(request, params.ReverseParam, false)
conditions, err := params.ParseConditions(request)
func (h *openpitrixHandler) ListApplications(req *restful.Request, resp *restful.Response) {
limit, offset := params.ParsePaging(req)
clusterName := req.PathParameter("cluster")
namespace := req.PathParameter("namespace")
orderBy := params.GetStringValueWithDefault(req, params.OrderByParam, openpitrix.CreateTime)
reverse := params.GetBoolValueWithDefault(req, params.ReverseParam, false)
conditions, err := params.ParseConditions(req)
if err != nil {
klog.V(4).Infoln(err)
api.HandleBadRequest(response, nil, err)
api.HandleBadRequest(resp, nil, err)
return
}
// filter namespaced applications by runtime_id
if namespace != "" {
ns, err := h.informers.Core().V1().Namespaces().Lister().Get(namespace)
if err != nil {
klog.Errorln(err)
api.HandleInternalError(response, nil, err)
return
}
runtimeId := ns.Annotations[constants.OpenPitrixRuntimeAnnotationKey]
if runtimeId == "" {
// runtime id not exist,return empty response
response.WriteAsJson(models.PageableResponse{Items: []interface{}{}, TotalCount: 0})
return
} else {
// filter by runtime id
conditions.Match[openpitrix.RuntimeId] = runtimeId
}
}
conditions.Match[openpitrix.Zone] = namespace
// in openpitrix, runtime id is the cluster name
conditions.Match[openpitrix.RuntimeId] = clusterName
result, err := h.openpitrix.ListApplications(conditions, limit, offset, orderBy, reverse)
if err != nil {
klog.Errorln(err)
api.HandleInternalError(response, nil, err)
api.HandleInternalError(resp, nil, err)
return
}
response.WriteAsJson(result)
resp.WriteAsJson(result)
}
func (h *openpitrixHandler) DescribeApplication(req *restful.Request, resp *restful.Response) {
clusterId := req.PathParameter("application")
clusterName := req.PathParameter("cluster")
namespace := req.PathParameter("namespace")
applicationId := req.PathParameter("application")
app, err := h.openpitrix.DescribeApplication(namespace, clusterId)
app, err := h.openpitrix.DescribeApplication(namespace, applicationId, clusterName)
if err != nil {
klog.Errorln(err)
......@@ -90,28 +85,12 @@ func (h *openpitrixHandler) DescribeApplication(req *restful.Request, resp *rest
return
}
ns, err := h.informers.Core().V1().Namespaces().Lister().Get(namespace)
if err != nil {
klog.Errorln(err)
api.HandleInternalError(resp, nil, err)
return
}
runtimeId := ns.Annotations[constants.OpenPitrixRuntimeAnnotationKey]
if runtimeId != app.Cluster.RuntimeId {
err = fmt.Errorf("rumtime not match %s,%s", app.Cluster.RuntimeId, runtimeId)
klog.V(4).Infoln(err)
api.HandleForbidden(resp, nil, err)
return
}
resp.WriteEntity(app)
return
}
func (h *openpitrixHandler) CreateApplication(req *restful.Request, resp *restful.Response) {
clusterName := req.PathParameter("cluster")
namespace := req.PathParameter("namespace")
var createClusterRequest openpitrix.CreateClusterRequest
err := req.ReadEntity(&createClusterRequest)
......@@ -123,7 +102,7 @@ func (h *openpitrixHandler) CreateApplication(req *restful.Request, resp *restfu
createClusterRequest.Username = req.HeaderParameter(constants.UserNameHeader)
err = h.openpitrix.CreateApplication(namespace, createClusterRequest)
err = h.openpitrix.CreateApplication(clusterName, namespace, createClusterRequest)
if err != nil {
klog.Errorln(err)
......@@ -136,7 +115,8 @@ func (h *openpitrixHandler) CreateApplication(req *restful.Request, resp *restfu
func (h *openpitrixHandler) ModifyApplication(req *restful.Request, resp *restful.Response) {
var modifyClusterAttributesRequest openpitrix.ModifyClusterAttributesRequest
clusterId := req.PathParameter("application")
clusterName := req.PathParameter("cluster")
applicationId := req.PathParameter("application")
namespace := req.PathParameter("namespace")
err := req.ReadEntity(&modifyClusterAttributesRequest)
if err != nil {
......@@ -145,7 +125,7 @@ func (h *openpitrixHandler) ModifyApplication(req *restful.Request, resp *restfu
return
}
app, err := h.openpitrix.DescribeApplication(namespace, clusterId)
app, err := h.openpitrix.DescribeApplication(namespace, applicationId, clusterName)
if err != nil {
klog.Errorln(err)
......@@ -153,24 +133,44 @@ func (h *openpitrixHandler) ModifyApplication(req *restful.Request, resp *restfu
return
}
ns, err := h.informers.Core().V1().Namespaces().Lister().Get(namespace)
if clusterName != app.Cluster.RuntimeId {
err = fmt.Errorf("runtime and cluster not match %s,%s", app.Cluster.RuntimeId, clusterName)
klog.V(4).Infoln(err)
api.HandleForbidden(resp, nil, err)
return
}
err = h.openpitrix.ModifyApplication(modifyClusterAttributesRequest)
if err != nil {
klog.Errorln(err)
api.HandleInternalError(resp, nil, err)
handleOpenpitrixError(resp, err)
return
}
runtimeId := ns.Annotations[constants.OpenPitrixRuntimeAnnotationKey]
resp.WriteEntity(errors.None)
}
func (h *openpitrixHandler) DeleteApplication(req *restful.Request, resp *restful.Response) {
clusterName := req.PathParameter("cluster")
applicationId := req.PathParameter("application")
namespace := req.PathParameter("namespace")
app, err := h.openpitrix.DescribeApplication(namespace, applicationId, clusterName)
if err != nil {
klog.Errorln(err)
handleOpenpitrixError(resp, err)
return
}
if runtimeId != app.Cluster.RuntimeId {
err = fmt.Errorf("rumtime not match %s,%s", app.Cluster.RuntimeId, runtimeId)
if clusterName != app.Cluster.RuntimeId {
err = fmt.Errorf("runtime and cluster not match %s,%s", app.Cluster.RuntimeId, clusterName)
klog.V(4).Infoln(err)
api.HandleForbidden(resp, nil, err)
return
}
err = h.openpitrix.ModifyApplication(modifyClusterAttributesRequest)
err = h.openpitrix.DeleteApplication(applicationId)
if err != nil {
klog.Errorln(err)
......@@ -181,39 +181,40 @@ func (h *openpitrixHandler) ModifyApplication(req *restful.Request, resp *restfu
resp.WriteEntity(errors.None)
}
func (h *openpitrixHandler) DeleteApplication(req *restful.Request, resp *restful.Response) {
clusterId := req.PathParameter("application")
func (h *openpitrixHandler) UpgradeApplication(req *restful.Request, resp *restful.Response) {
clusterName := req.PathParameter("cluster")
namespace := req.PathParameter("namespace")
app, err := h.openpitrix.DescribeApplication(namespace, clusterId)
applicationId := req.PathParameter("application")
var upgradeClusterRequest openpitrix.UpgradeClusterRequest
err := req.ReadEntity(&upgradeClusterRequest)
if err != nil {
klog.Errorln(err)
handleOpenpitrixError(resp, err)
klog.V(4).Infoln(err)
api.HandleBadRequest(resp, nil, err)
return
}
ns, err := h.informers.Core().V1().Namespaces().Lister().Get(namespace)
upgradeClusterRequest.Username = req.HeaderParameter(constants.UserNameHeader)
app, err := h.openpitrix.DescribeApplication(namespace, applicationId, clusterName)
if err != nil {
klog.Errorln(err)
api.HandleInternalError(resp, nil, err)
handleOpenpitrixError(resp, err)
return
}
runtimeId := ns.Annotations[constants.OpenPitrixRuntimeAnnotationKey]
if runtimeId != app.Cluster.RuntimeId {
err = fmt.Errorf("rumtime not match %s,%s", app.Cluster.RuntimeId, runtimeId)
if clusterName != app.Cluster.RuntimeId {
err = fmt.Errorf("runtime and cluster not match %s,%s", app.Cluster.RuntimeId, clusterName)
klog.V(4).Infoln(err)
api.HandleForbidden(resp, nil, err)
return
}
err = h.openpitrix.DeleteApplication(clusterId)
err = h.openpitrix.UpgradeApplication(upgradeClusterRequest)
if err != nil {
klog.Errorln(err)
handleOpenpitrixError(resp, err)
api.HandleInternalError(resp, nil, err)
return
}
......@@ -833,6 +834,7 @@ func (h *openpitrixHandler) DescribeRepo(req *restful.Request, resp *restful.Res
resp.WriteEntity(result)
}
func (h *openpitrixHandler) ListRepos(req *restful.Request, resp *restful.Response) {
limit, offset := params.ParsePaging(req)
orderBy := params.GetStringValueWithDefault(req, params.OrderByParam, openpitrix.CreateTime)
......@@ -856,6 +858,29 @@ func (h *openpitrixHandler) ListRepos(req *restful.Request, resp *restful.Respon
resp.WriteEntity(result)
}
func (h *openpitrixHandler) ListEvents(req *restful.Request, resp *restful.Response) {
limit, offset := params.ParsePaging(req)
orderBy := params.GetStringValueWithDefault(req, params.OrderByParam, openpitrix.CreateTime)
reverse := params.GetBoolValueWithDefault(req, params.ReverseParam, false)
conditions, err := params.ParseConditions(req)
if err != nil {
klog.V(4).Infoln(err)
api.HandleBadRequest(resp, nil, err)
return
}
result, err := h.openpitrix.ListEvents(conditions, orderBy, reverse, limit, offset)
if err != nil {
klog.Errorln(err)
handleOpenpitrixError(resp, err)
return
}
resp.WriteEntity(result)
}
func (h *openpitrixHandler) ListRepoEvents(req *restful.Request, resp *restful.Response) {
repoId := req.PathParameter("repo")
limit, offset := params.ParsePaging(req)
......
/*
Copyright 2019 The KubeSphere Authors.
Copyright 2020 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 v1
import (
......@@ -54,13 +52,27 @@ func AddToContainer(c *restful.Container, factory informers.InformerFactory, op
Required(false).
DataFormat("key=value,key~value").
DefaultValue("")).
Param(webservice.PathParameter("namespace", "the name of the project")).
Param(webservice.QueryParameter(params.PagingParam, "paging query, e.g. limit=100,page=1").
Required(false).
DataFormat("limit=%d,page=%d").
DefaultValue("limit=10,page=1")))
webservice.Route(webservice.GET("/namespaces/{namespace}/applications").
webservice.Route(webservice.GET("/clusters/{cluster}/applications").
To(handler.ListApplications).
Returns(http.StatusOK, api.StatusOK, models.PageableResponse{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.NamespaceResourcesTag}).
Doc("List all applications in special cluster").
Param(webservice.QueryParameter(params.ConditionsParam, "query conditions, connect multiple conditions with commas, equal symbol for exact query, wave symbol for fuzzy query e.g. name~a").
Required(false).
DataFormat("key=value,key~value").
DefaultValue("")).
Param(webservice.PathParameter("cluster", "the name of the cluster.").Required(true)).
Param(webservice.QueryParameter(params.PagingParam, "paging query, e.g. limit=100,page=1").
Required(false).
DataFormat("limit=%d,page=%d").
DefaultValue("limit=10,page=1")))
webservice.Route(webservice.GET("/clusters/{cluster}/namespaces/{namespace}/applications").
To(handler.ListApplications).
Returns(http.StatusOK, api.StatusOK, models.PageableResponse{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.NamespaceResourcesTag}).
......@@ -69,45 +81,61 @@ func AddToContainer(c *restful.Container, factory informers.InformerFactory, op
Required(false).
DataFormat("key=value,key~value").
DefaultValue("")).
Param(webservice.PathParameter("namespace", "the name of the project")).
Param(webservice.PathParameter("cluster", "the name of the cluster.").Required(true)).
Param(webservice.PathParameter("namespace", "the name of the project").Required(true)).
Param(webservice.QueryParameter(params.PagingParam, "paging query, e.g. limit=100,page=1").
Required(false).
DataFormat("limit=%d,page=%d").
DefaultValue("limit=10,page=1")))
webservice.Route(webservice.GET("/namespaces/{namespace}/applications/{application}").
webservice.Route(webservice.GET("/clusters/{cluster}/namespaces/{namespace}/applications/{application}").
To(handler.DescribeApplication).
Returns(http.StatusOK, api.StatusOK, openpitrix2.Application{}).
Metadata(restfulspec.KeyOpenAPITags, []string{constants.NamespaceResourcesTag}).
Doc("Describe the specified application of the namespace").
Param(webservice.PathParameter("namespace", "the name of the project")).
Param(webservice.PathParameter("application", "application ID")))
Param(webservice.PathParameter("cluster", "the name of the cluster.").Required(true)).
Param(webservice.PathParameter("namespace", "the name of the project").Required(true)).
Param(webservice.PathParameter("application", "the id of the application").Required(true)))
webservice.Route(webservice.POST("/namespaces/{namespace}/applications").
webservice.Route(webservice.POST("/clusters/{cluster}/namespaces/{namespace}/applications").
To(handler.CreateApplication).
Doc("Deploy a new application").
Metadata(restfulspec.KeyOpenAPITags, []string{constants.NamespaceResourcesTag}).
Reads(openpitrix2.CreateClusterRequest{}).
Returns(http.StatusOK, api.StatusOK, errors.Error{}).
Param(webservice.PathParameter("namespace", "the name of the project")))
Param(webservice.PathParameter("cluster", "the name of the cluster.").Required(true)).
Param(webservice.PathParameter("namespace", "the name of the project").Required(true)))
webservice.Route(webservice.PATCH("/namespaces/{namespace}/applications/{application}").
webservice.Route(webservice.PATCH("/clusters/{cluster}/namespaces/{namespace}/applications/{application}").
Consumes(mimePatch...).
To(handler.ModifyApplication).
Doc("Modify application").
Metadata(restfulspec.KeyOpenAPITags, []string{constants.NamespaceResourcesTag}).
Reads(openpitrix2.ModifyClusterAttributesRequest{}).
Returns(http.StatusOK, api.StatusOK, errors.Error{}).
Param(webservice.PathParameter("namespace", "the name of the project")).
Param(webservice.PathParameter("application", "the id of the application cluster")))
Param(webservice.PathParameter("cluster", "the name of the cluster.").Required(true)).
Param(webservice.PathParameter("namespace", "the name of the project").Required(true)).
Param(webservice.PathParameter("application", "the id of the application").Required(true)))
webservice.Route(webservice.DELETE("/namespaces/{namespace}/applications/{application}").
webservice.Route(webservice.DELETE("/clusters/{cluster}/namespaces/{namespace}/applications/{application}").
To(handler.DeleteApplication).
Doc("Delete the specified application").
Metadata(restfulspec.KeyOpenAPITags, []string{constants.NamespaceResourcesTag}).
Returns(http.StatusOK, api.StatusOK, errors.Error{}).
Param(webservice.PathParameter("namespace", "the name of the project")).
Param(webservice.PathParameter("application", "the id of the application cluster")))
Param(webservice.PathParameter("cluster", "the name of the cluster.").Required(true)).
Param(webservice.PathParameter("namespace", "the name of the project").Required(true)).
Param(webservice.PathParameter("application", "the id of the application").Required(true)))
webservice.Route(webservice.POST("/clusters/{cluster}/namespaces/{namespace}/applications/{application}").
Consumes(mimePatch...).
To(handler.UpgradeApplication).
Doc("Upgrade application").
Metadata(restfulspec.KeyOpenAPITags, []string{constants.NamespaceResourcesTag}).
Reads(openpitrix2.UpgradeClusterRequest{}).
Returns(http.StatusOK, api.StatusOK, errors.Error{}).
Param(webservice.PathParameter("cluster", "the name of the cluster.").Required(true)).
Param(webservice.PathParameter("namespace", "the name of the project").Required(true)).
Param(webservice.PathParameter("application", "the id of the application").Required(true)))
webservice.Route(webservice.POST("/apps/{app}/versions").
To(handler.CreateAppVersion).
......@@ -333,6 +361,13 @@ func AddToContainer(c *restful.Container, factory informers.InformerFactory, op
Reads(openpitrix2.RepoActionRequest{}).
Returns(http.StatusOK, api.StatusOK, errors.Error{}).
Param(webservice.PathParameter("repo", "repo id")))
webservice.Route(webservice.GET("/events").
To(handler.ListEvents).
Doc("Get events").
Param(webservice.QueryParameter(params.ConditionsParam, "query conditions,connect multiple conditions with commas, equal symbol for exact query, wave symbol for fuzzy query e.g. name~a").
Required(false).
DataFormat("key=%s,key~%s")).
Returns(http.StatusOK, api.StatusOK, models.PageableResponse{}))
webservice.Route(webservice.GET("/repos/{repo}/events").
To(handler.ListRepoEvents).
Doc("Get repository events").
......
/*
Copyright 2020 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 openpitrix
import (
"fmt"
"encoding/json"
"github.com/golang/protobuf/ptypes/wrappers"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
......@@ -27,20 +25,21 @@ import (
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/informers"
"k8s.io/klog"
"kubesphere.io/kubesphere/pkg/constants"
"kubesphere.io/kubesphere/pkg/models"
"kubesphere.io/kubesphere/pkg/server/params"
"kubesphere.io/kubesphere/pkg/simple/client/openpitrix"
"openpitrix.io/openpitrix/pkg/pb"
"openpitrix.io/openpitrix/pkg/util/pbutil"
"strings"
)
type ApplicationInterface interface {
ListApplications(conditions *params.Conditions, limit, offset int, orderBy string, reverse bool) (*models.PageableResponse, error)
DescribeApplication(namespace, clusterId string) (*Application, error)
CreateApplication(namespace string, request CreateClusterRequest) error
DescribeApplication(namespace, applicationId, clusterName string) (*Application, error)
CreateApplication(clusterName, namespace string, request CreateClusterRequest) error
ModifyApplication(request ModifyClusterAttributesRequest) error
DeleteApplication(id string) error
UpgradeApplication(request UpgradeClusterRequest) error
}
type applicationOperator struct {
......@@ -68,6 +67,14 @@ type workLoads struct {
Daemonsets []appsv1.DaemonSet `json:"daemonsets,omitempty" description:"daemonset list"`
}
type resourceInfo struct {
Deployments []appsv1.Deployment `json:"deployments,omitempty" description:"deployment list"`
Statefulsets []appsv1.StatefulSet `json:"statefulsets,omitempty" description:"statefulset list"`
Daemonsets []appsv1.DaemonSet `json:"daemonsets,omitempty" description:"daemonset list"`
Services []v1.Service `json:"services,omitempty" description:"application services"`
Ingresses []v1beta1.Ingress `json:"ingresses,omitempty" description:"application ingresses"`
}
func (c *applicationOperator) ListApplications(conditions *params.Conditions, limit, offset int, orderBy string, reverse bool) (*models.PageableResponse, error) {
describeClustersRequest := &pb.DescribeClustersRequest{
Limit: uint32(limit),
......@@ -87,6 +94,9 @@ func (c *applicationOperator) ListApplications(conditions *params.Conditions, li
if status := conditions.Match[Status]; status != "" {
describeClustersRequest.Status = strings.Split(status, "|")
}
if zone := conditions.Match[Zone]; zone != "" {
describeClustersRequest.Zone = []string{zone}
}
if orderBy != "" {
describeClustersRequest.SortKey = &wrappers.StringValue{Value: orderBy}
}
......@@ -133,9 +143,15 @@ func (c *applicationOperator) describeApplication(cluster *pb.Cluster) (*Applica
return &app, nil
}
func (c *applicationOperator) DescribeApplication(namespace string, clusterId string) (*Application, error) {
clusters, err := c.opClient.DescribeClusters(openpitrix.SystemContext(), &pb.DescribeClustersRequest{ClusterId: []string{clusterId}, Limit: 1})
func (c *applicationOperator) DescribeApplication(namespace string, applicationId string, clusterName string) (*Application, error) {
describeClusterRequest := &pb.DescribeClustersRequest{
ClusterId: []string{applicationId},
RuntimeId: []string{clusterName},
Zone: []string{namespace},
WithDetail: pbutil.ToProtoBool(true),
Limit: 1,
}
clusters, err := c.opClient.DescribeClusters(openpitrix.SystemContext(), describeClusterRequest)
if err != nil {
klog.Errorln(err)
......@@ -156,16 +172,26 @@ func (c *applicationOperator) DescribeApplication(namespace string, clusterId st
return nil, err
}
workloads, err := c.getWorkLoads(namespace, cluster.ClusterRoleSet)
resource := new(resourceInfo)
workloads := cluster.AdditionalInfo.GetValue()
if workloads == "" {
err := status.New(codes.NotFound, "cannot get workload").Err()
klog.Errorln(err)
return nil, err
}
err = json.Unmarshal([]byte(workloads), resource)
if err != nil {
klog.Errorln(err)
return nil, err
}
app.WorkLoads = workloads
workloadLabels := c.getLabels(namespace, app.WorkLoads)
app.Services = c.getSvcs(namespace, workloadLabels)
app.Ingresses = c.getIng(namespace, app.Services)
app.WorkLoads = &workLoads{
Deployments: resource.Deployments,
Statefulsets: resource.Statefulsets,
Daemonsets: resource.Daemonsets,
}
app.Services = resource.Services
app.Ingresses = resource.Ingresses
return app, nil
}
......@@ -332,24 +358,13 @@ func (c *applicationOperator) getIng(namespace string, services []v1.Service) []
return ings
}
func (c *applicationOperator) CreateApplication(namespace string, request CreateClusterRequest) error {
ns, err := c.informers.Core().V1().Namespaces().Lister().Get(namespace)
if err != nil {
klog.Error(err)
return err
}
if runtimeId := ns.Annotations[constants.OpenPitrixRuntimeAnnotationKey]; runtimeId != "" {
request.RuntimeId = runtimeId
} else {
return fmt.Errorf("runtime not init: namespace %s", namespace)
}
_, err = c.opClient.CreateCluster(openpitrix.ContextWithUsername(request.Username), &pb.CreateClusterRequest{
func (c *applicationOperator) CreateApplication(clusterName, namespace string, request CreateClusterRequest) error {
_, err := c.opClient.CreateCluster(openpitrix.ContextWithUsername(request.Username), &pb.CreateClusterRequest{
AppId: &wrappers.StringValue{Value: request.AppId},
VersionId: &wrappers.StringValue{Value: request.VersionId},
RuntimeId: &wrappers.StringValue{Value: request.RuntimeId},
RuntimeId: &wrappers.StringValue{Value: clusterName},
Conf: &wrappers.StringValue{Value: request.Conf},
Zone: &wrappers.StringValue{Value: namespace},
})
if err != nil {
......@@ -380,8 +395,22 @@ func (c *applicationOperator) ModifyApplication(request ModifyClusterAttributesR
return nil
}
func (c *applicationOperator) DeleteApplication(clusterId string) error {
_, err := c.opClient.DeleteClusters(openpitrix.SystemContext(), &pb.DeleteClustersRequest{ClusterId: []string{clusterId}, Force: &wrappers.BoolValue{Value: true}})
func (c *applicationOperator) DeleteApplication(applicationId string) error {
_, err := c.opClient.DeleteClusters(openpitrix.SystemContext(), &pb.DeleteClustersRequest{ClusterId: []string{applicationId}, Force: &wrappers.BoolValue{Value: true}})
if err != nil {
klog.Errorln(err)
return err
}
return nil
}
func (c *applicationOperator) UpgradeApplication(request UpgradeClusterRequest) error {
_, err := c.opClient.UpgradeCluster(openpitrix.ContextWithUsername(request.Username), &pb.UpgradeClusterRequest{
ClusterId: &wrappers.StringValue{Value: request.ClusterId},
VersionId: &wrappers.StringValue{Value: request.VersionId},
})
if err != nil {
klog.Errorln(err)
......
/*
Copyright 2020 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.
......@@ -97,11 +94,12 @@ func TestApplicationOperator_CreateApplication(t *testing.T) {
VersionId: &wrappers.StringValue{Value: test.createClusterRequest.VersionId},
RuntimeId: &wrappers.StringValue{Value: test.createClusterRequest.RuntimeId},
Conf: &wrappers.StringValue{Value: test.createClusterRequest.Conf},
Zone: &wrappers.StringValue{Value: test.targetNamespace},
}).Return(&pb.CreateClusterResponse{}, nil).AnyTimes()
t.Run(test.description, func(t *testing.T) {
err := applicationOperator.CreateApplication(test.targetNamespace, test.createClusterRequest)
err := applicationOperator.CreateApplication(test.createClusterRequest.RuntimeId, test.targetNamespace, test.createClusterRequest)
if err != nil && err.Error() != test.expected.Error() {
t.Error(err)
......
/*
Copyright 2020 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.
......
/*
Copyright 2019 The KubeSphere Authors.
Copyright 2020 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.
......
/*
Copyright 2020 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.
......
/*
Copyright 2020 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.
......
/*
Copyright 2020 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.
......@@ -37,6 +34,7 @@ type RepoInterface interface {
ListRepos(conditions *params.Conditions, orderBy string, reverse bool, limit, offset int) (*models.PageableResponse, error)
ValidateRepo(request *ValidateRepoRequest) (*ValidateRepoResponse, error)
DoRepoAction(repoId string, request *RepoActionRequest) error
ListEvents(conditions *params.Conditions, orderBy string, reverse bool, limit, offset int) (*models.PageableResponse, error)
ListRepoEvents(repoId string, conditions *params.Conditions, limit, offset int) (*models.PageableResponse, error)
}
......@@ -267,3 +265,33 @@ func (c *repoOperator) ListRepoEvents(repoId string, conditions *params.Conditio
return &models.PageableResponse{Items: items, TotalCount: int(resp.TotalCount)}, nil
}
func (c *repoOperator) ListEvents(conditions *params.Conditions, orderBy string, reverse bool, limit, offset int) (*models.PageableResponse, error) {
describeRepoEventsRequest := &pb.DescribeRepoEventsRequest{}
if repoId := conditions.Match["repo_id"]; repoId != "" {
describeRepoEventsRequest.RepoId = strings.Split(repoId, "|")
}
if eventId := conditions.Match["repo_event_id"]; eventId != "" {
describeRepoEventsRequest.RepoEventId = strings.Split(eventId, "|")
}
if status := conditions.Match["status"]; status != "" {
describeRepoEventsRequest.Status = strings.Split(status, "|")
}
describeRepoEventsRequest.Limit = uint32(limit)
describeRepoEventsRequest.Offset = uint32(offset)
resp, err := c.opClient.DescribeRepoEvents(openpitrix.SystemContext(), describeRepoEventsRequest)
if err != nil {
klog.Error(err)
return nil, err
}
items := make([]interface{}, 0)
for _, item := range resp.RepoEventSet {
items = append(items, convertRepoEvent(item))
}
return &models.PageableResponse{Items: items, TotalCount: int(resp.TotalCount)}, nil
}
/*
Copyright 2020 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 openpitrix
import (
......@@ -737,6 +750,25 @@ type CreateClusterRequest struct {
Username string `json:"-"`
}
type UpgradeClusterRequest struct {
// cluster id
ClusterId string `json:"cluster_id"`
// advanced param
AdvancedParam []string `json:"advanced_param"`
// required, conf a json string, include cpu, memory info of cluster
Conf string `json:"conf,omitempty"`
// required, id of runtime
RuntimeId string `json:"runtime_id,omitempty"`
// required, id of app version
VersionId string `json:"version_id,omitempty"`
Username string `json:"-"`
}
type Cluster struct {
// additional info
......@@ -840,6 +872,7 @@ const (
CreateTime = "create_time"
StatusTime = "status_time"
RuntimeId = "runtime_id"
Zone = "zone"
VersionId = "version_id"
RepoId = "repo_id"
CategoryId = "category_id"
......
/*
Copyright 2019 The KubeSphere Authors.
Copyright 2020 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.
......
/*
Copyright 2019 The KubeSphere Authors.
Copyright 2020 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.
......@@ -20,6 +20,7 @@ package openpitrix
import (
"context"
"fmt"
"github.com/golang/protobuf/ptypes/wrappers"
"k8s.io/klog"
"openpitrix.io/openpitrix/pkg/manager"
"openpitrix.io/openpitrix/pkg/pb"
......@@ -48,6 +49,12 @@ type Client interface {
pb.CategoryManagerClient
pb.AttachmentManagerClient
pb.RepoIndexerClient
// upsert the openpitrix runtime when cluster is updated or created
UpsertRuntime(cluster string, kubeConfig string) error
// clean up the openpitrix runtime when cluster is deleted
CleanupRuntime(cluster string) error
// migrate the openpitrix runtime when upgrade ks2.x to ks3.x
MigrateRuntime(runtimeId string, cluster string) error
}
type client struct {
......@@ -60,6 +67,47 @@ type client struct {
pb.RepoIndexerClient
}
func (c *client) UpsertRuntime(cluster string, kubeConfig string) error {
ctx := SystemContext()
req := &pb.CreateRuntimeCredentialRequest{
Name: &wrappers.StringValue{Value: fmt.Sprintf("kubeconfig-%s", cluster)},
Provider: &wrappers.StringValue{Value: "kubernetes"},
Description: &wrappers.StringValue{Value: "kubeconfig"},
RuntimeUrl: &wrappers.StringValue{Value: "kubesphere"},
RuntimeCredentialContent: &wrappers.StringValue{Value: kubeConfig},
RuntimeCredentialId: &wrappers.StringValue{Value: cluster},
}
_, err := c.CreateRuntimeCredential(ctx, req)
if err != nil {
return err
}
_, err = c.CreateRuntime(ctx, &pb.CreateRuntimeRequest{
Name: &wrappers.StringValue{Value: cluster},
RuntimeCredentialId: &wrappers.StringValue{Value: cluster},
Provider: &wrappers.StringValue{Value: KubernetesProvider},
Zone: &wrappers.StringValue{Value: cluster},
})
return err
}
func (c *client) CleanupRuntime(cluster string) error {
ctx := SystemContext()
_, err := c.DeleteClusterInRuntime(ctx, &pb.DeleteClusterInRuntimeRequest{
RuntimeId: []string{cluster},
})
return err
}
func (c *client) MigrateRuntime(runtimeId string, cluster string) error {
ctx := SystemContext()
_, err := c.MigrateClusterInRuntime(ctx, &pb.MigrateClusterInRuntimeRequest{
FromRuntimeId: runtimeId,
ToRuntimeId: cluster,
})
return err
}
func parseToHostPort(endpoint string) (string, int, error) {
args := strings.Split(endpoint, ":")
if len(args) != 2 {
......
// +build ignore
package main
import (
"bytes"
"fmt"
"go/format"
"html/template"
"io/ioutil"
"log"
"path/filepath"
"strings"
"github.com/globalsign/mgo/internal/json"
)
func main() {
log.SetFlags(0)
log.SetPrefix(name + ": ")
var g Generator
fmt.Fprintf(&g, "// Code generated by \"%s.go\"; DO NOT EDIT\n\n", name)
src := g.generate()
err := ioutil.WriteFile(fmt.Sprintf("%s.go", strings.TrimSuffix(name, "_generator")), src, 0644)
if err != nil {
log.Fatalf("writing output: %s", err)
}
}
// Generator holds the state of the analysis. Primarily used to buffer
// the output for format.Source.
type Generator struct {
bytes.Buffer // Accumulated output.
}
// format returns the gofmt-ed contents of the Generator's buffer.
func (g *Generator) format() []byte {
src, err := format.Source(g.Bytes())
if err != nil {
// Should never happen, but can arise when developing this code.
// The user can compile the output to see the error.
log.Printf("warning: internal error: invalid Go generated: %s", err)
log.Printf("warning: compile the package to analyze the error")
return g.Bytes()
}
return src
}
// EVERYTHING ABOVE IS CONSTANT BETWEEN THE GENERATORS
const name = "bson_corpus_spec_test_generator"
func (g *Generator) generate() []byte {
testFiles, err := filepath.Glob("./specdata/specifications/source/bson-corpus/tests/*.json")
if err != nil {
log.Fatalf("error reading bson-corpus files: %s", err)
}
tests, err := g.loadTests(testFiles)
if err != nil {
log.Fatalf("error loading tests: %s", err)
}
tmpl, err := g.getTemplate()
if err != nil {
log.Fatalf("error loading template: %s", err)
}
tmpl.Execute(&g.Buffer, tests)
return g.format()
}
func (g *Generator) loadTests(filenames []string) ([]*testDef, error) {
var tests []*testDef
for _, filename := range filenames {
test, err := g.loadTest(filename)
if err != nil {
return nil, err
}
tests = append(tests, test)
}
return tests, nil
}
func (g *Generator) loadTest(filename string) (*testDef, error) {
content, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
var testDef testDef
err = json.Unmarshal(content, &testDef)
if err != nil {
return nil, err
}
names := make(map[string]struct{})
for i := len(testDef.Valid) - 1; i >= 0; i-- {
if testDef.BsonType == "0x05" && testDef.Valid[i].Description == "subtype 0x02" {
testDef.Valid = append(testDef.Valid[:i], testDef.Valid[i+1:]...)
continue
}
name := cleanupFuncName(testDef.Description + "_" + testDef.Valid[i].Description)
nameIdx := name
j := 1
for {
if _, ok := names[nameIdx]; !ok {
break
}
nameIdx = fmt.Sprintf("%s_%d", name, j)
}
names[nameIdx] = struct{}{}
testDef.Valid[i].TestDef = &testDef
testDef.Valid[i].Name = nameIdx
testDef.Valid[i].StructTest = testDef.TestKey != "" &&
(testDef.BsonType != "0x05" || strings.Contains(testDef.Valid[i].Description, "0x00")) &&
!testDef.Deprecated
}
for i := len(testDef.DecodeErrors) - 1; i >= 0; i-- {
if strings.Contains(testDef.DecodeErrors[i].Description, "UTF-8") {
testDef.DecodeErrors = append(testDef.DecodeErrors[:i], testDef.DecodeErrors[i+1:]...)
continue
}
name := cleanupFuncName(testDef.Description + "_" + testDef.DecodeErrors[i].Description)
nameIdx := name
j := 1
for {
if _, ok := names[nameIdx]; !ok {
break
}
nameIdx = fmt.Sprintf("%s_%d", name, j)
}
names[nameIdx] = struct{}{}
testDef.DecodeErrors[i].Name = nameIdx
}
return &testDef, nil
}
func (g *Generator) getTemplate() (*template.Template, error) {
content := `package bson_test
import (
"encoding/hex"
"time"
. "gopkg.in/check.v1"
"github.com/globalsign/mgo/bson"
)
func testValid(c *C, in []byte, expected []byte, result interface{}) {
err := bson.Unmarshal(in, result)
c.Assert(err, IsNil)
out, err := bson.Marshal(result)
c.Assert(err, IsNil)
c.Assert(string(expected), Equals, string(out), Commentf("roundtrip failed for %T, expected '%x' but got '%x'", result, expected, out))
}
func testDecodeSkip(c *C, in []byte) {
err := bson.Unmarshal(in, &struct{}{})
c.Assert(err, IsNil)
}
func testDecodeError(c *C, in []byte, result interface{}) {
err := bson.Unmarshal(in, result)
c.Assert(err, Not(IsNil))
}
{{range .}}
{{range .Valid}}
func (s *S) Test{{.Name}}(c *C) {
b, err := hex.DecodeString("{{.Bson}}")
c.Assert(err, IsNil)
{{if .CanonicalBson}}
cb, err := hex.DecodeString("{{.CanonicalBson}}")
c.Assert(err, IsNil)
{{else}}
cb := b
{{end}}
var resultD bson.D
testValid(c, b, cb, &resultD)
{{if .StructTest}}var resultS struct {
Element {{.TestDef.GoType}} ` + "`bson:\"{{.TestDef.TestKey}}\"`" + `
}
testValid(c, b, cb, &resultS){{end}}
testDecodeSkip(c, b)
}
{{end}}
{{range .DecodeErrors}}
func (s *S) Test{{.Name}}(c *C) {
b, err := hex.DecodeString("{{.Bson}}")
c.Assert(err, IsNil)
var resultD bson.D
testDecodeError(c, b, &resultD)
}
{{end}}
{{end}}
`
tmpl, err := template.New("").Parse(content)
if err != nil {
return nil, err
}
return tmpl, nil
}
func cleanupFuncName(name string) string {
return strings.Map(func(r rune) rune {
if (r >= 48 && r <= 57) || (r >= 65 && r <= 90) || (r >= 97 && r <= 122) {
return r
}
return '_'
}, name)
}
type testDef struct {
Description string `json:"description"`
BsonType string `json:"bson_type"`
TestKey string `json:"test_key"`
Valid []*valid `json:"valid"`
DecodeErrors []*decodeError `json:"decodeErrors"`
Deprecated bool `json:"deprecated"`
}
func (t *testDef) GoType() string {
switch t.BsonType {
case "0x01":
return "float64"
case "0x02":
return "string"
case "0x03":
return "bson.D"
case "0x04":
return "[]interface{}"
case "0x05":
return "[]byte"
case "0x07":
return "bson.ObjectId"
case "0x08":
return "bool"
case "0x09":
return "time.Time"
case "0x0E":
return "string"
case "0x10":
return "int32"
case "0x12":
return "int64"
case "0x13":
return "bson.Decimal"
default:
return "interface{}"
}
}
type valid struct {
Description string `json:"description"`
Bson string `json:"bson"`
CanonicalBson string `json:"canonical_bson"`
Name string
StructTest bool
TestDef *testDef
}
type decodeError struct {
Description string `json:"description"`
Bson string `json:"bson"`
Name string
}
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2017 The Go Authors. All rights reserved.
// Copyright 2016 The Go Authors. All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
......@@ -29,89 +29,65 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
Package remap handles tracking the locations of Go tokens in a source text
across a rewrite by the Go formatter.
*/
package remap
// Package descriptor provides functions for obtaining protocol buffer
// descriptors for generated Go types.
//
// These functions cannot go in package proto because they depend on the
// generated protobuf descriptor messages, which themselves depend on proto.
package descriptor
import (
"bytes"
"compress/gzip"
"fmt"
"go/scanner"
"go/token"
)
"io/ioutil"
// A Location represents a span of byte offsets in the source text.
type Location struct {
Pos, End int // End is exclusive
}
"github.com/golang/protobuf/proto"
protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor"
)
// A Map represents a mapping between token locations in an input source text
// and locations in the correspnding output text.
type Map map[Location]Location
// extractFile extracts a FileDescriptorProto from a gzip'd buffer.
func extractFile(gz []byte) (*protobuf.FileDescriptorProto, error) {
r, err := gzip.NewReader(bytes.NewReader(gz))
if err != nil {
return nil, fmt.Errorf("failed to open gzip reader: %v", err)
}
defer r.Close()
// Find reports whether the specified span is recorded by m, and if so returns
// the new location it was mapped to. If the input span was not found, the
// returned location is the same as the input.
func (m Map) Find(pos, end int) (Location, bool) {
key := Location{
Pos: pos,
End: end,
b, err := ioutil.ReadAll(r)
if err != nil {
return nil, fmt.Errorf("failed to uncompress descriptor: %v", err)
}
if loc, ok := m[key]; ok {
return loc, true
fd := new(protobuf.FileDescriptorProto)
if err := proto.Unmarshal(b, fd); err != nil {
return nil, fmt.Errorf("malformed FileDescriptorProto: %v", err)
}
return key, false
}
func (m Map) add(opos, oend, npos, nend int) {
m[Location{Pos: opos, End: oend}] = Location{Pos: npos, End: nend}
return fd, nil
}
// Compute constructs a location mapping from input to output. An error is
// reported if any of the tokens of output cannot be mapped.
func Compute(input, output []byte) (Map, error) {
itok := tokenize(input)
otok := tokenize(output)
if len(itok) != len(otok) {
return nil, fmt.Errorf("wrong number of tokens, %d ≠ %d", len(itok), len(otok))
}
m := make(Map)
for i, ti := range itok {
to := otok[i]
if ti.Token != to.Token {
return nil, fmt.Errorf("token %d type mismatch: %s ≠ %s", i+1, ti, to)
}
m.add(ti.pos, ti.end, to.pos, to.end)
}
return m, nil
// Message is a proto.Message with a method to return its descriptor.
//
// Message types generated by the protocol compiler always satisfy
// the Message interface.
type Message interface {
proto.Message
Descriptor() ([]byte, []int)
}
// tokinfo records the span and type of a source token.
type tokinfo struct {
pos, end int
token.Token
}
// ForMessage returns a FileDescriptorProto and a DescriptorProto from within it
// describing the given message.
func ForMessage(msg Message) (fd *protobuf.FileDescriptorProto, md *protobuf.DescriptorProto) {
gz, path := msg.Descriptor()
fd, err := extractFile(gz)
if err != nil {
panic(fmt.Sprintf("invalid FileDescriptorProto for %T: %v", msg, err))
}
func tokenize(src []byte) []tokinfo {
fs := token.NewFileSet()
var s scanner.Scanner
s.Init(fs.AddFile("src", fs.Base(), len(src)), src, nil, scanner.ScanComments)
var info []tokinfo
for {
pos, next, lit := s.Scan()
switch next {
case token.SEMICOLON:
continue
}
info = append(info, tokinfo{
pos: int(pos - 1),
end: int(pos + token.Pos(len(lit)) - 1),
Token: next,
})
if next == token.EOF {
break
}
md = fd.MessageType[path[0]]
for _, i := range path[1:] {
md = md.NestedType[i]
}
return info
return fd, md
}
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/protobuf/compiler/plugin.proto
/*
Package plugin_go is a generated protocol buffer package.
It is generated from these files:
google/protobuf/compiler/plugin.proto
It has these top-level messages:
Version
CodeGeneratorRequest
CodeGeneratorResponse
*/
package plugin_go
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import google_protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
// The version number of protocol compiler.
type Version struct {
Major *int32 `protobuf:"varint,1,opt,name=major" json:"major,omitempty"`
Minor *int32 `protobuf:"varint,2,opt,name=minor" json:"minor,omitempty"`
Patch *int32 `protobuf:"varint,3,opt,name=patch" json:"patch,omitempty"`
// A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should
// be empty for mainline stable releases.
Suffix *string `protobuf:"bytes,4,opt,name=suffix" json:"suffix,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Version) Reset() { *m = Version{} }
func (m *Version) String() string { return proto.CompactTextString(m) }
func (*Version) ProtoMessage() {}
func (*Version) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
func (m *Version) Unmarshal(b []byte) error {
return xxx_messageInfo_Version.Unmarshal(m, b)
}
func (m *Version) Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Version.Marshal(b, m, deterministic)
}
func (dst *Version) XXX_Merge(src proto.Message) {
xxx_messageInfo_Version.Merge(dst, src)
}
func (m *Version) XXX_Size() int {
return xxx_messageInfo_Version.Size(m)
}
func (m *Version) XXX_DiscardUnknown() {
xxx_messageInfo_Version.DiscardUnknown(m)
}
var xxx_messageInfo_Version proto.InternalMessageInfo
func (m *Version) GetMajor() int32 {
if m != nil && m.Major != nil {
return *m.Major
}
return 0
}
func (m *Version) GetMinor() int32 {
if m != nil && m.Minor != nil {
return *m.Minor
}
return 0
}
func (m *Version) GetPatch() int32 {
if m != nil && m.Patch != nil {
return *m.Patch
}
return 0
}
func (m *Version) GetSuffix() string {
if m != nil && m.Suffix != nil {
return *m.Suffix
}
return ""
}
// An encoded CodeGeneratorRequest is written to the plugin's stdin.
type CodeGeneratorRequest struct {
// The .proto files that were explicitly listed on the command-line. The
// code generator should generate code only for these files. Each file's
// descriptor will be included in proto_file, below.
FileToGenerate []string `protobuf:"bytes,1,rep,name=file_to_generate,json=fileToGenerate" json:"file_to_generate,omitempty"`
// The generator parameter passed on the command-line.
Parameter *string `protobuf:"bytes,2,opt,name=parameter" json:"parameter,omitempty"`
// FileDescriptorProtos for all files in files_to_generate and everything
// they import. The files will appear in topological order, so each file
// appears before any file that imports it.
//
// protoc guarantees that all proto_files will be written after
// the fields above, even though this is not technically guaranteed by the
// protobuf wire format. This theoretically could allow a plugin to stream
// in the FileDescriptorProtos and handle them one by one rather than read
// the entire set into memory at once. However, as of this writing, this
// is not similarly optimized on protoc's end -- it will store all fields in
// memory at once before sending them to the plugin.
//
// Type names of fields and extensions in the FileDescriptorProto are always
// fully qualified.
ProtoFile []*google_protobuf.FileDescriptorProto `protobuf:"bytes,15,rep,name=proto_file,json=protoFile" json:"proto_file,omitempty"`
// The version number of protocol compiler.
CompilerVersion *Version `protobuf:"bytes,3,opt,name=compiler_version,json=compilerVersion" json:"compiler_version,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *CodeGeneratorRequest) Reset() { *m = CodeGeneratorRequest{} }
func (m *CodeGeneratorRequest) String() string { return proto.CompactTextString(m) }
func (*CodeGeneratorRequest) ProtoMessage() {}
func (*CodeGeneratorRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
func (m *CodeGeneratorRequest) Unmarshal(b []byte) error {
return xxx_messageInfo_CodeGeneratorRequest.Unmarshal(m, b)
}
func (m *CodeGeneratorRequest) Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_CodeGeneratorRequest.Marshal(b, m, deterministic)
}
func (dst *CodeGeneratorRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_CodeGeneratorRequest.Merge(dst, src)
}
func (m *CodeGeneratorRequest) XXX_Size() int {
return xxx_messageInfo_CodeGeneratorRequest.Size(m)
}
func (m *CodeGeneratorRequest) XXX_DiscardUnknown() {
xxx_messageInfo_CodeGeneratorRequest.DiscardUnknown(m)
}
var xxx_messageInfo_CodeGeneratorRequest proto.InternalMessageInfo
func (m *CodeGeneratorRequest) GetFileToGenerate() []string {
if m != nil {
return m.FileToGenerate
}
return nil
}
func (m *CodeGeneratorRequest) GetParameter() string {
if m != nil && m.Parameter != nil {
return *m.Parameter
}
return ""
}
func (m *CodeGeneratorRequest) GetProtoFile() []*google_protobuf.FileDescriptorProto {
if m != nil {
return m.ProtoFile
}
return nil
}
func (m *CodeGeneratorRequest) GetCompilerVersion() *Version {
if m != nil {
return m.CompilerVersion
}
return nil
}
// The plugin writes an encoded CodeGeneratorResponse to stdout.
type CodeGeneratorResponse struct {
// Error message. If non-empty, code generation failed. The plugin process
// should exit with status code zero even if it reports an error in this way.
//
// This should be used to indicate errors in .proto files which prevent the
// code generator from generating correct code. Errors which indicate a
// problem in protoc itself -- such as the input CodeGeneratorRequest being
// unparseable -- should be reported by writing a message to stderr and
// exiting with a non-zero status code.
Error *string `protobuf:"bytes,1,opt,name=error" json:"error,omitempty"`
File []*CodeGeneratorResponse_File `protobuf:"bytes,15,rep,name=file" json:"file,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *CodeGeneratorResponse) Reset() { *m = CodeGeneratorResponse{} }
func (m *CodeGeneratorResponse) String() string { return proto.CompactTextString(m) }
func (*CodeGeneratorResponse) ProtoMessage() {}
func (*CodeGeneratorResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
func (m *CodeGeneratorResponse) Unmarshal(b []byte) error {
return xxx_messageInfo_CodeGeneratorResponse.Unmarshal(m, b)
}
func (m *CodeGeneratorResponse) Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_CodeGeneratorResponse.Marshal(b, m, deterministic)
}
func (dst *CodeGeneratorResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_CodeGeneratorResponse.Merge(dst, src)
}
func (m *CodeGeneratorResponse) XXX_Size() int {
return xxx_messageInfo_CodeGeneratorResponse.Size(m)
}
func (m *CodeGeneratorResponse) XXX_DiscardUnknown() {
xxx_messageInfo_CodeGeneratorResponse.DiscardUnknown(m)
}
var xxx_messageInfo_CodeGeneratorResponse proto.InternalMessageInfo
func (m *CodeGeneratorResponse) GetError() string {
if m != nil && m.Error != nil {
return *m.Error
}
return ""
}
func (m *CodeGeneratorResponse) GetFile() []*CodeGeneratorResponse_File {
if m != nil {
return m.File
}
return nil
}
// Represents a single generated file.
type CodeGeneratorResponse_File struct {
// The file name, relative to the output directory. The name must not
// contain "." or ".." components and must be relative, not be absolute (so,
// the file cannot lie outside the output directory). "/" must be used as
// the path separator, not "\".
//
// If the name is omitted, the content will be appended to the previous
// file. This allows the generator to break large files into small chunks,
// and allows the generated text to be streamed back to protoc so that large
// files need not reside completely in memory at one time. Note that as of
// this writing protoc does not optimize for this -- it will read the entire
// CodeGeneratorResponse before writing files to disk.
Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
// If non-empty, indicates that the named file should already exist, and the
// content here is to be inserted into that file at a defined insertion
// point. This feature allows a code generator to extend the output
// produced by another code generator. The original generator may provide
// insertion points by placing special annotations in the file that look
// like:
// @@protoc_insertion_point(NAME)
// The annotation can have arbitrary text before and after it on the line,
// which allows it to be placed in a comment. NAME should be replaced with
// an identifier naming the point -- this is what other generators will use
// as the insertion_point. Code inserted at this point will be placed
// immediately above the line containing the insertion point (thus multiple
// insertions to the same point will come out in the order they were added).
// The double-@ is intended to make it unlikely that the generated code
// could contain things that look like insertion points by accident.
//
// For example, the C++ code generator places the following line in the
// .pb.h files that it generates:
// // @@protoc_insertion_point(namespace_scope)
// This line appears within the scope of the file's package namespace, but
// outside of any particular class. Another plugin can then specify the
// insertion_point "namespace_scope" to generate additional classes or
// other declarations that should be placed in this scope.
//
// Note that if the line containing the insertion point begins with
// whitespace, the same whitespace will be added to every line of the
// inserted text. This is useful for languages like Python, where
// indentation matters. In these languages, the insertion point comment
// should be indented the same amount as any inserted code will need to be
// in order to work correctly in that context.
//
// The code generator that generates the initial file and the one which
// inserts into it must both run as part of a single invocation of protoc.
// Code generators are executed in the order in which they appear on the
// command line.
//
// If |insertion_point| is present, |name| must also be present.
InsertionPoint *string `protobuf:"bytes,2,opt,name=insertion_point,json=insertionPoint" json:"insertion_point,omitempty"`
// The file contents.
Content *string `protobuf:"bytes,15,opt,name=content" json:"content,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *CodeGeneratorResponse_File) Reset() { *m = CodeGeneratorResponse_File{} }
func (m *CodeGeneratorResponse_File) String() string { return proto.CompactTextString(m) }
func (*CodeGeneratorResponse_File) ProtoMessage() {}
func (*CodeGeneratorResponse_File) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} }
func (m *CodeGeneratorResponse_File) Unmarshal(b []byte) error {
return xxx_messageInfo_CodeGeneratorResponse_File.Unmarshal(m, b)
}
func (m *CodeGeneratorResponse_File) Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_CodeGeneratorResponse_File.Marshal(b, m, deterministic)
}
func (dst *CodeGeneratorResponse_File) XXX_Merge(src proto.Message) {
xxx_messageInfo_CodeGeneratorResponse_File.Merge(dst, src)
}
func (m *CodeGeneratorResponse_File) XXX_Size() int {
return xxx_messageInfo_CodeGeneratorResponse_File.Size(m)
}
func (m *CodeGeneratorResponse_File) XXX_DiscardUnknown() {
xxx_messageInfo_CodeGeneratorResponse_File.DiscardUnknown(m)
}
var xxx_messageInfo_CodeGeneratorResponse_File proto.InternalMessageInfo
func (m *CodeGeneratorResponse_File) GetName() string {
if m != nil && m.Name != nil {
return *m.Name
}
return ""
}
func (m *CodeGeneratorResponse_File) GetInsertionPoint() string {
if m != nil && m.InsertionPoint != nil {
return *m.InsertionPoint
}
return ""
}
func (m *CodeGeneratorResponse_File) GetContent() string {
if m != nil && m.Content != nil {
return *m.Content
}
return ""
}
func init() {
proto.RegisterType((*Version)(nil), "google.protobuf.compiler.Version")
proto.RegisterType((*CodeGeneratorRequest)(nil), "google.protobuf.compiler.CodeGeneratorRequest")
proto.RegisterType((*CodeGeneratorResponse)(nil), "google.protobuf.compiler.CodeGeneratorResponse")
proto.RegisterType((*CodeGeneratorResponse_File)(nil), "google.protobuf.compiler.CodeGeneratorResponse.File")
}
func init() { proto.RegisterFile("google/protobuf/compiler/plugin.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 417 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0xcf, 0x6a, 0x14, 0x41,
0x10, 0xc6, 0x19, 0x77, 0x63, 0x98, 0x8a, 0x64, 0x43, 0x13, 0xa5, 0x09, 0x39, 0x8c, 0x8b, 0xe2,
0x5c, 0x32, 0x0b, 0xc1, 0x8b, 0x78, 0x4b, 0x44, 0x3d, 0x78, 0x58, 0x1a, 0xf1, 0x20, 0xc8, 0x30,
0x99, 0xd4, 0x74, 0x5a, 0x66, 0xba, 0xc6, 0xee, 0x1e, 0xf1, 0x49, 0x7d, 0x0f, 0xdf, 0x40, 0xfa,
0xcf, 0x24, 0xb2, 0xb8, 0xa7, 0xee, 0xef, 0x57, 0xd5, 0xd5, 0x55, 0x1f, 0x05, 0x2f, 0x25, 0x91,
0xec, 0x71, 0x33, 0x1a, 0x72, 0x74, 0x33, 0x75, 0x9b, 0x96, 0x86, 0x51, 0xf5, 0x68, 0x36, 0x63,
0x3f, 0x49, 0xa5, 0xab, 0x10, 0x60, 0x3c, 0xa6, 0x55, 0x73, 0x5a, 0x35, 0xa7, 0x9d, 0x15, 0xbb,
0x05, 0x6e, 0xd1, 0xb6, 0x46, 0x8d, 0x8e, 0x4c, 0xcc, 0x5e, 0xb7, 0x70, 0xf8, 0x05, 0x8d, 0x55,
0xa4, 0xd9, 0x29, 0x1c, 0x0c, 0xcd, 0x77, 0x32, 0x3c, 0x2b, 0xb2, 0xf2, 0x40, 0x44, 0x11, 0xa8,
0xd2, 0x64, 0xf8, 0xa3, 0x44, 0xbd, 0xf0, 0x74, 0x6c, 0x5c, 0x7b, 0xc7, 0x17, 0x91, 0x06, 0xc1,
0x9e, 0xc1, 0x63, 0x3b, 0x75, 0x9d, 0xfa, 0xc5, 0x97, 0x45, 0x56, 0xe6, 0x22, 0xa9, 0xf5, 0x9f,
0x0c, 0x4e, 0xaf, 0xe9, 0x16, 0x3f, 0xa0, 0x46, 0xd3, 0x38, 0x32, 0x02, 0x7f, 0x4c, 0x68, 0x1d,
0x2b, 0xe1, 0xa4, 0x53, 0x3d, 0xd6, 0x8e, 0x6a, 0x19, 0x63, 0xc8, 0xb3, 0x62, 0x51, 0xe6, 0xe2,
0xd8, 0xf3, 0xcf, 0x94, 0x5e, 0x20, 0x3b, 0x87, 0x7c, 0x6c, 0x4c, 0x33, 0xa0, 0xc3, 0xd8, 0x4a,
0x2e, 0x1e, 0x00, 0xbb, 0x06, 0x08, 0xe3, 0xd4, 0xfe, 0x15, 0x5f, 0x15, 0x8b, 0xf2, 0xe8, 0xf2,
0x45, 0xb5, 0x6b, 0xcb, 0x7b, 0xd5, 0xe3, 0xbb, 0x7b, 0x03, 0xb6, 0x1e, 0x8b, 0x3c, 0x44, 0x7d,
0x84, 0x7d, 0x82, 0x93, 0xd9, 0xb8, 0xfa, 0x67, 0xf4, 0x24, 0x8c, 0x77, 0x74, 0xf9, 0xbc, 0xda,
0xe7, 0x70, 0x95, 0xcc, 0x13, 0xab, 0x99, 0x24, 0xb0, 0xfe, 0x9d, 0xc1, 0xd3, 0x9d, 0x99, 0xed,
0x48, 0xda, 0xa2, 0xf7, 0x0e, 0x8d, 0x49, 0x3e, 0xe7, 0x22, 0x0a, 0xf6, 0x11, 0x96, 0xff, 0x34,
0xff, 0x7a, 0xff, 0x8f, 0xff, 0x2d, 0x1a, 0x66, 0x13, 0xa1, 0xc2, 0xd9, 0x37, 0x58, 0x86, 0x79,
0x18, 0x2c, 0x75, 0x33, 0x60, 0xfa, 0x26, 0xdc, 0xd9, 0x2b, 0x58, 0x29, 0x6d, 0xd1, 0x38, 0x45,
0xba, 0x1e, 0x49, 0x69, 0x97, 0xcc, 0x3c, 0xbe, 0xc7, 0x5b, 0x4f, 0x19, 0x87, 0xc3, 0x96, 0xb4,
0x43, 0xed, 0xf8, 0x2a, 0x24, 0xcc, 0xf2, 0x4a, 0xc2, 0x79, 0x4b, 0xc3, 0xde, 0xfe, 0xae, 0x9e,
0x6c, 0xc3, 0x6e, 0x06, 0x7b, 0xed, 0xd7, 0x37, 0x52, 0xb9, 0xbb, 0xe9, 0xc6, 0x87, 0x37, 0x92,
0xfa, 0x46, 0xcb, 0x87, 0x65, 0x0c, 0x97, 0xf6, 0x42, 0xa2, 0xbe, 0x90, 0x94, 0x56, 0xfa, 0x6d,
0x3c, 0x6a, 0x49, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0xf7, 0x15, 0x40, 0xc5, 0xfe, 0x02, 0x00,
0x00,
}
// Code generated by protoc-gen-go.
// source: google/protobuf/compiler/plugin.proto
// DO NOT EDIT!
package google_protobuf_compiler
import proto "github.com/golang/protobuf/proto"
import "math"
import google_protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor"
// Reference proto and math imports to suppress error if they are not otherwise used.
var _ = proto.GetString
var _ = math.Inf
type CodeGeneratorRequest struct {
FileToGenerate []string `protobuf:"bytes,1,rep,name=file_to_generate" json:"file_to_generate,omitempty"`
Parameter *string `protobuf:"bytes,2,opt,name=parameter" json:"parameter,omitempty"`
ProtoFile []*google_protobuf.FileDescriptorProto `protobuf:"bytes,15,rep,name=proto_file" json:"proto_file,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (this *CodeGeneratorRequest) Reset() { *this = CodeGeneratorRequest{} }
func (this *CodeGeneratorRequest) String() string { return proto.CompactTextString(this) }
func (*CodeGeneratorRequest) ProtoMessage() {}
func (this *CodeGeneratorRequest) GetParameter() string {
if this != nil && this.Parameter != nil {
return *this.Parameter
}
return ""
}
type CodeGeneratorResponse struct {
Error *string `protobuf:"bytes,1,opt,name=error" json:"error,omitempty"`
File []*CodeGeneratorResponse_File `protobuf:"bytes,15,rep,name=file" json:"file,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (this *CodeGeneratorResponse) Reset() { *this = CodeGeneratorResponse{} }
func (this *CodeGeneratorResponse) String() string { return proto.CompactTextString(this) }
func (*CodeGeneratorResponse) ProtoMessage() {}
func (this *CodeGeneratorResponse) GetError() string {
if this != nil && this.Error != nil {
return *this.Error
}
return ""
}
type CodeGeneratorResponse_File struct {
Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
InsertionPoint *string `protobuf:"bytes,2,opt,name=insertion_point" json:"insertion_point,omitempty"`
Content *string `protobuf:"bytes,15,opt,name=content" json:"content,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (this *CodeGeneratorResponse_File) Reset() { *this = CodeGeneratorResponse_File{} }
func (this *CodeGeneratorResponse_File) String() string { return proto.CompactTextString(this) }
func (*CodeGeneratorResponse_File) ProtoMessage() {}
func (this *CodeGeneratorResponse_File) GetName() string {
if this != nil && this.Name != nil {
return *this.Name
}
return ""
}
func (this *CodeGeneratorResponse_File) GetInsertionPoint() string {
if this != nil && this.InsertionPoint != nil {
return *this.InsertionPoint
}
return ""
}
func (this *CodeGeneratorResponse_File) GetContent() string {
if this != nil && this.Content != nil {
return *this.Content
}
return ""
}
func init() {
}
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
//
// WARNING: The plugin interface is currently EXPERIMENTAL and is subject to
// change.
//
// protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is
// just a program that reads a CodeGeneratorRequest from stdin and writes a
// CodeGeneratorResponse to stdout.
//
// Plugins written using C++ can use google/protobuf/compiler/plugin.h instead
// of dealing with the raw protocol defined here.
//
// A plugin executable needs only to be placed somewhere in the path. The
// plugin should be named "protoc-gen-$NAME", and will then be used when the
// flag "--${NAME}_out" is passed to protoc.
syntax = "proto2";
package google.protobuf.compiler;
option java_package = "com.google.protobuf.compiler";
option java_outer_classname = "PluginProtos";
option go_package = "github.com/golang/protobuf/protoc-gen-go/plugin;plugin_go";
import "google/protobuf/descriptor.proto";
// The version number of protocol compiler.
message Version {
optional int32 major = 1;
optional int32 minor = 2;
optional int32 patch = 3;
// A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should
// be empty for mainline stable releases.
optional string suffix = 4;
}
// An encoded CodeGeneratorRequest is written to the plugin's stdin.
message CodeGeneratorRequest {
// The .proto files that were explicitly listed on the command-line. The
// code generator should generate code only for these files. Each file's
// descriptor will be included in proto_file, below.
repeated string file_to_generate = 1;
// The generator parameter passed on the command-line.
optional string parameter = 2;
// FileDescriptorProtos for all files in files_to_generate and everything
// they import. The files will appear in topological order, so each file
// appears before any file that imports it.
//
// protoc guarantees that all proto_files will be written after
// the fields above, even though this is not technically guaranteed by the
// protobuf wire format. This theoretically could allow a plugin to stream
// in the FileDescriptorProtos and handle them one by one rather than read
// the entire set into memory at once. However, as of this writing, this
// is not similarly optimized on protoc's end -- it will store all fields in
// memory at once before sending them to the plugin.
//
// Type names of fields and extensions in the FileDescriptorProto are always
// fully qualified.
repeated FileDescriptorProto proto_file = 15;
// The version number of protocol compiler.
optional Version compiler_version = 3;
}
// The plugin writes an encoded CodeGeneratorResponse to stdout.
message CodeGeneratorResponse {
// Error message. If non-empty, code generation failed. The plugin process
// should exit with status code zero even if it reports an error in this way.
//
// This should be used to indicate errors in .proto files which prevent the
// code generator from generating correct code. Errors which indicate a
// problem in protoc itself -- such as the input CodeGeneratorRequest being
// unparseable -- should be reported by writing a message to stderr and
// exiting with a non-zero status code.
optional string error = 1;
// Represents a single generated file.
message File {
// The file name, relative to the output directory. The name must not
// contain "." or ".." components and must be relative, not be absolute (so,
// the file cannot lie outside the output directory). "/" must be used as
// the path separator, not "\".
//
// If the name is omitted, the content will be appended to the previous
// file. This allows the generator to break large files into small chunks,
// and allows the generated text to be streamed back to protoc so that large
// files need not reside completely in memory at one time. Note that as of
// this writing protoc does not optimize for this -- it will read the entire
// CodeGeneratorResponse before writing files to disk.
optional string name = 1;
// If non-empty, indicates that the named file should already exist, and the
// content here is to be inserted into that file at a defined insertion
// point. This feature allows a code generator to extend the output
// produced by another code generator. The original generator may provide
// insertion points by placing special annotations in the file that look
// like:
// @@protoc_insertion_point(NAME)
// The annotation can have arbitrary text before and after it on the line,
// which allows it to be placed in a comment. NAME should be replaced with
// an identifier naming the point -- this is what other generators will use
// as the insertion_point. Code inserted at this point will be placed
// immediately above the line containing the insertion point (thus multiple
// insertions to the same point will come out in the order they were added).
// The double-@ is intended to make it unlikely that the generated code
// could contain things that look like insertion points by accident.
//
// For example, the C++ code generator places the following line in the
// .pb.h files that it generates:
// // @@protoc_insertion_point(namespace_scope)
// This line appears within the scope of the file's package namespace, but
// outside of any particular class. Another plugin can then specify the
// insertion_point "namespace_scope" to generate additional classes or
// other declarations that should be placed in this scope.
//
// Note that if the line containing the insertion point begins with
// whitespace, the same whitespace will be added to every line of the
// inserted text. This is useful for languages like Python, where
// indentation matters. In these languages, the insertion point comment
// should be indented the same amount as any inserted code will need to be
// in order to work correctly in that context.
//
// The code generator that generates the initial file and the one which
// inserts into it must both run as part of a single invocation of protoc.
// Code generators are executed in the order in which they appear on the
// command line.
//
// If |insertion_point| is present, |name| must also be present.
optional string insertion_point = 2;
// The file contents.
optional string content = 15;
}
repeated File file = 15;
}
......@@ -26,6 +26,7 @@ proto_library(
deps = [
"@com_google_protobuf//:any_proto",
"@com_google_protobuf//:descriptor_proto",
"@com_google_protobuf//:struct_proto",
],
)
......
......@@ -27,11 +27,12 @@ go_library(
deps = [
"//internal:go_default_library",
"//utilities:go_default_library",
"@com_github_golang_protobuf//descriptor:go_default_library_gen",
"@com_github_golang_protobuf//jsonpb:go_default_library_gen",
"@com_github_golang_protobuf//proto:go_default_library",
"@com_github_golang_protobuf//protoc-gen-go/generator:go_default_library_gen",
"@go_googleapis//google/api:httpbody_go_proto",
"@io_bazel_rules_go//proto/wkt:any_go_proto",
"@io_bazel_rules_go//proto/wkt:descriptor_go_proto",
"@io_bazel_rules_go//proto/wkt:duration_go_proto",
"@io_bazel_rules_go//proto/wkt:field_mask_go_proto",
"@io_bazel_rules_go//proto/wkt:timestamp_go_proto",
......@@ -48,6 +49,7 @@ go_test(
size = "small",
srcs = [
"context_test.go",
"convert_test.go",
"errors_test.go",
"fieldmask_test.go",
"handler_test.go",
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
......@@ -83,7 +83,8 @@ func (r *RuntimeProviderConfig) GetPort() int {
if r.Port > 0 {
return r.Port
} else {
return constants.RuntimeProviderManagerPort
//todo attention
return constants.KubernetesProviderPort
}
}
......
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册