diff --git a/.gitattributes b/.gitattributes index ec5482eee06..c3b4dc5b325 100644 --- a/.gitattributes +++ b/.gitattributes @@ -8,4 +8,6 @@ # coverage-excluded is an attribute used to explicitly exclude a path from being included in code # coverage. If a path is marked as linguist-generated already, it will be implicitly excluded and # there is no need to add the coverage-excluded attribute -#/pkg/controller/testing/** coverage-excluded=true +/pkg/**/testing/** coverage-excluded=true +/vendor/** coverage-excluded=true +/test/** coverage-excluded=true diff --git a/.gitignore b/.gitignore index 31e2a94a206..5366a3c8d79 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ bazel-* .idea/ .vscode/ .DS_Store +*.swp diff --git a/Gopkg.lock b/Gopkg.lock index b4e0ecd4bbb..209221172b3 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -2,26 +2,19 @@ [[projects]] - digest = "1:97bdeb31587a8bee3e13eb4519db4cc592bff017632bb07cbcd7c02925d8d621" + digest = "1:f8ad8a53fa865a70efbe215b0ca34735523f50ea39e0efde319ab6fc80089b44" name = "cloud.google.com/go" - packages = [ - "compute/metadata", - "iam", - "internal/optional", - "internal/version", - "pubsub", - "pubsub/apiv1", - "pubsub/internal/distribution", - ] + packages = ["compute/metadata"] pruneopts = "NUT" revision = "90f2606161ee6a14efe2ca79fc05ac2b8efe250b" [[projects]] - digest = "1:f2bb07cb70ceaecfffa034919e418793eef0960480474c276173b725449fdb1f" + digest = "1:a074ae0f4788ea4c4c7045ab37f21943920bc20cf6ff8afcb2d971154cfa87ab" name = "github.com/Shopify/sarama" packages = ["."] pruneopts = "NUT" - revision = "46cf3e2cf1acef7876068f66cf69ec31aad2d0b2" + revision = "ec843464b50d4c8b56403ec9d589cf41ea30e722" + version = "v1.19.0" [[projects]] branch = "master" @@ -32,12 +25,12 @@ revision = "3a771d992973f24aa725d07868b467d1ddfceafb" [[projects]] - digest = "1:4fb088ed7f384178cfc4552661e280a12ccc93be7f30a1ca994958a61a8e1d13" + digest = "1:be1e32779b5150a3e4341f584f14282db95feff53f60d49b17134a5710ac8ff9" name = "github.com/bsm/sarama-cluster" packages = ["."] pruneopts = "NUT" - revision = "cf455bc755fe41ac9bb2861e7a961833d9c2ecc3" - version = "v2.1.13" + revision = "c618e605e15c0d7535f6c96ff8efbb0dba4fd66c" + version = "v2.1.15" [[projects]] digest = "1:a2c1d0e43bd3baaa071d1b9ed72c27d78169b2b269f71c105ac4ba34b1be4a39" @@ -57,11 +50,11 @@ [[projects]] branch = "master" - digest = "1:0b70d299db64766a4ee7128f0f94944f2356ca9d3499c79123dbc3a1d2ba803e" + digest = "1:d3430c048e919ed27813d20dc65a32d4e3bae3ad05b83700e244a81eaaf48e2a" name = "github.com/eapache/go-xerial-snappy" packages = ["."] pruneopts = "NUT" - revision = "bb955e01b9346ac19dc29eb16586c90ded99a98c" + revision = "776d5712da21bc4762676d614db1d8a64f4238b0" [[projects]] digest = "1:0d36a2b325b9e75f8057f7f9fbe778d348d70ba652cb9335485b69d1a5c4e038" @@ -71,6 +64,14 @@ revision = "44cc805cf13205b55f69e14bcb69867d1ae92f98" version = "v1.1.0" +[[projects]] + digest = "1:32598368f409bbee79deb9d43569fcd92b9fb27f39155f5e166b3371217f051f" + name = "github.com/evanphx/json-patch" + packages = ["."] + pruneopts = "NUT" + revision = "72bf35d0ff611848c1dc9df0f976c81192392fa5" + version = "v4.1.0" + [[projects]] digest = "1:1b91ae0dc69a41d4c2ed23ea5cffb721ea63f5037ca4b81e6d6771fbb8f45129" name = "github.com/fsnotify/fsnotify" @@ -103,6 +104,14 @@ pruneopts = "NUT" revision = "7536572e8d55209135cd5e7ccf7fce43dca217ab" +[[projects]] + digest = "1:e885f703ddf302286f6bae494d0602010c6ac8e724503f3306e18f3350802d32" + name = "github.com/gobuffalo/envy" + packages = ["."] + pruneopts = "NUT" + revision = "e0b181c424e7ca1a36f6f2db4bdfd25ef3421e77" + version = "v1.6.7" + [[projects]] digest = "1:1b3dd24f14a5280710fc7a3aa2480b6e4d20fdfc905841de9a3aa2aa2f1d4ee9" name = "github.com/gogo/protobuf" @@ -131,15 +140,13 @@ revision = "24b0969c4cb722950103eed87108c8d291a8df00" [[projects]] - digest = "1:0f7f0d9512487860d967bd31b4a9668316e53630fd71cb57a84ccf97c852df84" + digest = "1:03e14cff610a8a58b774e36bd337fa979482be86aab01be81fb8bbd6d0f07fc8" name = "github.com/golang/protobuf" packages = [ "proto", - "protoc-gen-go/descriptor", "ptypes", "ptypes/any", "ptypes/duration", - "ptypes/empty", "ptypes/timestamp", ] pruneopts = "NUT" @@ -176,22 +183,6 @@ revision = "3af367b6b30c263d47e8895973edcca9a49cf029" version = "v0.2.0" -[[projects]] - digest = "1:51bee9f1987dcdb9f9a1b4c20745d78f6bf6f5f14ad4e64ca883eb64df4c0045" - name = "github.com/google/go-github" - packages = ["github"] - pruneopts = "NUT" - revision = "e48060a28fac52d0f1cb758bc8b87c07bac4a87d" - version = "v15.0.0" - -[[projects]] - branch = "master" - digest = "1:a63cff6b5d8b95638bfe300385d93b2a6d9d687734b863da8e09dc834510a690" - name = "github.com/google/go-querystring" - packages = ["query"] - pruneopts = "NUT" - revision = "53e6ce116135b80d037921a7fdd5138cf32d7a8a" - [[projects]] branch = "master" digest = "1:52c5834e2bebac9030c97cc0798ac11c3aa8a39f098aeb419f142533da6cd3cc" @@ -200,6 +191,21 @@ pruneopts = "NUT" revision = "24818f796faf91cd76ec7bddd72458fbced7a6c1" +[[projects]] + branch = "master" + digest = "1:0d5e3798bfa2642ac268341c96710b8def1f3cbc3bc803c421d90704d72107d8" + name = "github.com/google/licenseclassifier" + packages = [ + ".", + "internal/sets", + "stringclassifier", + "stringclassifier/internal/pq", + "stringclassifier/searchset", + "stringclassifier/searchset/tokenizer", + ] + pruneopts = "NUT" + revision = "e979a0b10eebe748549c702a25e997c556349da6" + [[projects]] digest = "1:1bb197a3b5db4e06e00b7560f8e89836c486627f2a0338332ed37daa003d259e" name = "github.com/google/uuid" @@ -208,14 +214,6 @@ revision = "064e2069ce9c359c118179501254f67d7d37ba24" version = "0.2" -[[projects]] - digest = "1:fe852c57b4fc4d11e6ef79bce1e930ee2f2f7d148b370afef8f8d012a80960ea" - name = "github.com/googleapis/gax-go" - packages = ["."] - pruneopts = "NUT" - revision = "317e0006254c44a0ac427cc52a0e083ff0b9622f" - version = "v2.0.0" - [[projects]] digest = "1:06a7dadb7b760767341ffb6c8d377238d68a1226f2b21b5d497d2e3f6ecf6b4e" name = "github.com/googleapis/gnostic" @@ -258,6 +256,14 @@ revision = "9f23e2d6bd2a77f959b2bf6acdbefd708a83a4a4" version = "v0.3.6" +[[projects]] + digest = "1:da62aa6632d04e080b8a8b85a59ed9ed1550842a0099a55f3ae3a20d02a3745a" + name = "github.com/joho/godotenv" + packages = ["."] + pruneopts = "NUT" + revision = "23d116af351c84513e1946b527c88823e476be13" + version = "v1.3.0" + [[projects]] digest = "1:0243cffa4a3410f161ee613dfdd903a636d07e838a42d341da95d81f42cd1d41" name = "github.com/json-iterator/go" @@ -266,17 +272,31 @@ revision = "f2b4162afba35581b6d4a50d3b8f34e33c144682" [[projects]] - digest = "1:3b8adce8bbe5865d7155ddfadbd063915265f04a22ab47a3f5cddd7b32333d1e" + digest = "1:345bbba667abadd6263391c915251ede8d9fa6f6852839c60bb6738b6122b89c" name = "github.com/knative/build" packages = [ "pkg/apis/build", "pkg/apis/build/v1alpha1", ] pruneopts = "NUT" - revision = "5c1d8c8469d1ed34b2aecf4c2305b3a57fff2ee3" + revision = "94859753e2c6724df2be86f6a254f810895fa3eb" + version = "v0.2.0" + +[[projects]] + branch = "master" + digest = "1:e1ae53a5b5dc5fa6f8cb5fa4596a4436d2754921510766569386efc9c07d839c" + name = "github.com/knative/eventing-sources" + packages = [ + "pkg/apis/sources/v1alpha1", + "pkg/client/clientset/versioned", + "pkg/client/clientset/versioned/scheme", + "pkg/client/clientset/versioned/typed/sources/v1alpha1", + ] + pruneopts = "NUT" + revision = "aa113a015beb91c94a8e173c8f0ac18512a83954" [[projects]] - digest = "1:aac2721aace98ec22ca32041a292bdb42edec971684e831e3e24c4f5a8d4d893" + digest = "1:9870368d47209c3a52b9000fd00420c51832604c00a65aa0a56b6e60a2ff3664" name = "github.com/knative/pkg" packages = [ "apis", @@ -287,6 +307,7 @@ "apis/istio/authentication/v1alpha1", "apis/istio/common/v1alpha1", "apis/istio/v1alpha3", + "changeset", "client/clientset/versioned", "client/clientset/versioned/scheme", "client/clientset/versioned/typed/authentication/v1alpha1", @@ -299,42 +320,59 @@ "client/informers/externalversions/istio/v1alpha3", "client/listers/authentication/v1alpha1", "client/listers/istio/v1alpha3", + "cloudevents", "configmap", + "kmeta", "logging", "logging/logkey", "signals", "test", "test/logging", "test/spoof", + "test/zipkin", "webhook", ] pruneopts = "NUT" - revision = "ba1a828cd571f605684f9a4506e85bc13cb65b8d" + revision = "4b704fa7948ad9ae8ec90d1cd5b4a34516b252ea" [[projects]] - digest = "1:63f3974f3afe3dc5b6a115c0d53b0897cd01be6880c4bf5d014fc69a95db6ed1" + digest = "1:cf62a9e49c586f87503a2ca683f636afae817333b6056c7529f2643ec285ed7e" name = "github.com/knative/serving" packages = [ - "pkg/apis/istio", - "pkg/apis/istio/v1alpha3", + "pkg/apis/autoscaling", + "pkg/apis/autoscaling/v1alpha1", + "pkg/apis/networking", + "pkg/apis/networking/v1alpha1", "pkg/apis/serving", "pkg/apis/serving/v1alpha1", "pkg/client/clientset/versioned", "pkg/client/clientset/versioned/scheme", - "pkg/client/clientset/versioned/typed/istio/v1alpha3", + "pkg/client/clientset/versioned/typed/autoscaling/v1alpha1", + "pkg/client/clientset/versioned/typed/networking/v1alpha1", "pkg/client/clientset/versioned/typed/serving/v1alpha1", ] pruneopts = "NUT" - revision = "37c640555a3241ed707962ba6b29d6c7fe68f937" - version = "v0.1.1" + revision = "1036f34badadfa711d88378a1c09a3527bb1584b" + version = "v0.2.1" [[projects]] branch = "master" - digest = "1:00f434f614520a4b48ef3f6d3ed5c7a1a4f89be1bed98c250711413f6da2eb51" + digest = "1:a8f096af01ca3ef74546e412d0ffc5ad526bd17ae88495c04e6042200fc7fabc" name = "github.com/knative/test-infra" + packages = [ + "scripts", + "tools/dep-collector", + ] + pruneopts = "UT" + revision = "f710a703baf3ac7e5e9005693fb1c8d61c4eccbb" + +[[projects]] + digest = "1:56dbf15e091bf7926cb33a57cb6bdfc658fc6d3498d2f76f10a97ce7856f1fde" + name = "github.com/markbates/inflect" packages = ["."] - pruneopts = "T" - revision = "c21d3a832727d5d4334e734c0878eac3a5a07ae7" + pruneopts = "NUT" + revision = "24b83195037b3bc61fcda2d28b7b0518bce293b6" + version = "v1.0.4" [[projects]] branch = "master" @@ -393,15 +431,15 @@ version = "v2.0.1" [[projects]] - digest = "1:43830c167ef48755903a1bb81e37f73b8f522c5fbecc80f269e2e25d741aa8ee" + digest = "1:1d920dce8e11bfff65b5709e883a8ece131b63a5bc4b2cd404f9ef7eb445f73f" name = "github.com/pierrec/lz4" packages = [ ".", "internal/xxh32", ] pruneopts = "NUT" - revision = "6b9367c9ff401dbc54fabce3fb8d972e799b702d" - version = "v2.0.2" + revision = "635575b42742856941dbc767b44905bb9ba083f6" + version = "v2.0.7" [[projects]] digest = "1:03bca087b180bf24c4f9060775f137775550a0834e18f0bca0520a868679dbd7" @@ -449,11 +487,19 @@ [[projects]] branch = "master" - digest = "1:7c522337040d4ec9a136cd9d64fe4677ee1d3eae4a7f8831c2108f9bec43fa48" + digest = "1:120b256a4d3cd2946ffa4b87102731c2f004aed6d836dc2fba400ed9398696e7" name = "github.com/rcrowley/go-metrics" packages = ["."] pruneopts = "NUT" - revision = "e2704e165165ec55d062f5919b4b29494e9fa790" + revision = "3113b8401b8a98917cde58f8bbd42a1b1c03b1fd" + +[[projects]] + digest = "1:d917313f309bda80d27274d53985bc65651f81a5b66b820749ac7f8ef061fd04" + name = "github.com/sergi/go-diff" + packages = ["diffmatchpatch"] + pruneopts = "NUT" + revision = "1744e2970ca51c86172c8190fadad617561ed6e7" + version = "v1.0.0" [[projects]] digest = "1:15e5c398fbd9d2c439b635a08ac161b13d04f0c2aa587fe256b65dc0c3efe8b7" @@ -463,13 +509,11 @@ revision = "583c0c0531f06d5278b7d917446061adc344b5cd" [[projects]] - digest = "1:773b6907f497ea5abddc9ee90cdde179b119c0c8a04b0f02cb2fff955ed8cab4" + digest = "1:e4faec5275202abbc4e023e0e8930a9acf43194563d2032cdffa41940650f3e8" name = "go.opencensus.io" packages = [ - "exporter/stackdriver/propagation", "internal", "internal/tagencoding", - "plugin/ocgrpc", "plugin/ochttp", "plugin/ochttp/propagation/b3", "stats", @@ -525,7 +569,7 @@ [[projects]] branch = "master" - digest = "1:7e7c436f75db05dc112521a34811f383e5656abd083f678c5a6df2bf42ea6b2c" + digest = "1:e51ab843adff8d5de8889d7ad0488df404af09df8926e3e5a7b5ee1ef53af988" name = "golang.org/x/net" packages = [ "context", @@ -534,8 +578,6 @@ "http2", "http2/hpack", "idna", - "internal/timeseries", - "trace", ] pruneopts = "NUT" revision = "1e491301e022f8f977054da4c2d852decd59571f" @@ -555,12 +597,9 @@ [[projects]] branch = "master" - digest = "1:c313aef534e493304f3666fbd24dca5932ebf776a82b7a40f961c9355794a1b1" + digest = "1:39ebcc2b11457b703ae9ee2e8cca0f68df21969c6102cb3b705f76cca0ea0239" name = "golang.org/x/sync" - packages = [ - "errgroup", - "semaphore", - ] + packages = ["errgroup"] pruneopts = "NUT" revision = "1d60e4601c6fd243af51cc01ddf169918a5407ca" @@ -619,24 +658,7 @@ revision = "a5b4c53f6e8bdcafa95a94671bf2d1203365858b" [[projects]] - branch = "master" - digest = "1:cbb9ee36efb225152642c14192700636ae231d632315179129d79d2b6391acf9" - name = "google.golang.org/api" - packages = [ - "googleapi/transport", - "internal", - "iterator", - "option", - "support/bundler", - "transport", - "transport/grpc", - "transport/http", - ] - pruneopts = "NUT" - revision = "f71c6d4abd9757df4168c39856698c341d07251f" - -[[projects]] - digest = "1:626ac4e70ef18262989f8c52503259109e1a2e5580d23aeae0f0e0349819dade" + digest = "1:7206d98ec77c90c72ec2c405181a1dcf86965803b6dbc4f98ceab7a5047c37a9" name = "google.golang.org/appengine" packages = [ ".", @@ -647,74 +669,13 @@ "internal/log", "internal/modules", "internal/remote_api", - "internal/socket", "internal/urlfetch", - "socket", "urlfetch", ] pruneopts = "NUT" revision = "150dc57a1b433e64154302bdc40b6bb8aefa313a" version = "v1.0.0" -[[projects]] - branch = "master" - digest = "1:94bda8ad0190a989ad7768ce0df06e4c384a8fa7bca1cf0ce63501a4b26fe51e" - name = "google.golang.org/genproto" - packages = [ - "googleapis/api/annotations", - "googleapis/iam/v1", - "googleapis/pubsub/v1", - "googleapis/rpc/status", - "protobuf/field_mask", - ] - pruneopts = "NUT" - revision = "4065a77fc542a455295382a23a996a08ed18813a" - -[[projects]] - digest = "1:60d6a8209da1f48bd268d21ea37ddf8936913ee0b35a6eacf741e1bb8791ae5d" - name = "google.golang.org/grpc" - packages = [ - ".", - "balancer", - "balancer/base", - "balancer/roundrobin", - "channelz", - "codes", - "connectivity", - "credentials", - "credentials/oauth", - "encoding", - "encoding/proto", - "grpclb/grpc_lb_v1/messages", - "grpclog", - "internal", - "keepalive", - "metadata", - "naming", - "peer", - "resolver", - "resolver/dns", - "resolver/passthrough", - "stats", - "status", - "tap", - "transport", - ] - pruneopts = "NUT" - revision = "41344da2231b913fa3d983840a57a6b1b7b631a1" - version = "v1.12.0" - -[[projects]] - digest = "1:c776b8566e3415e9a434756ea1d3b96a3059be221555ff177666ba9edb2a38b5" - name = "gopkg.in/go-playground/webhooks.v3" - packages = [ - ".", - "github", - ] - pruneopts = "NUT" - revision = "be944ed461fc75c52f0f149acfa011f8da721f6c" - version = "v3.12.0" - [[projects]] digest = "1:2d1fbdc6777e5408cabeb02bf336305e724b925ff4546ded0fa8715a7267922a" name = "gopkg.in/inf.v0" @@ -1020,7 +981,7 @@ revision = "8a9b82f00b3a86eac24681da3f9fe6c34c01cea2" [[projects]] - digest = "1:b18104b0089c9483846dfcd124fd25a65361697004684b03d4de86546e9808d6" + digest = "1:63139e4089c9b034ec98d8ae54e87c91cd3f5ce5bf9d50dba412c08a363659c4" name = "sigs.k8s.io/controller-runtime" packages = [ "pkg/cache", @@ -1042,6 +1003,7 @@ "pkg/recorder", "pkg/runtime/inject", "pkg/runtime/log", + "pkg/runtime/scheme", "pkg/runtime/signals", "pkg/source", "pkg/source/internal", @@ -1056,23 +1018,22 @@ analyzer-name = "dep" analyzer-version = 1 input-imports = [ - "cloud.google.com/go/pubsub", "github.com/Shopify/sarama", "github.com/bsm/sarama-cluster", - "github.com/davecgh/go-spew/spew", "github.com/fsnotify/fsnotify", "github.com/golang/glog", "github.com/google/go-cmp/cmp", "github.com/google/go-cmp/cmp/cmpopts", - "github.com/google/go-github/github", "github.com/google/uuid", + "github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1", + "github.com/knative/eventing-sources/pkg/client/clientset/versioned", "github.com/knative/pkg/apis", "github.com/knative/pkg/apis/duck", "github.com/knative/pkg/apis/duck/v1alpha1", "github.com/knative/pkg/apis/istio/v1alpha3", "github.com/knative/pkg/client/clientset/versioned", "github.com/knative/pkg/client/informers/externalversions", - "github.com/knative/pkg/client/listers/istio/v1alpha3", + "github.com/knative/pkg/cloudevents", "github.com/knative/pkg/configmap", "github.com/knative/pkg/logging", "github.com/knative/pkg/logging/logkey", @@ -1083,22 +1044,15 @@ "github.com/knative/serving/pkg/apis/serving/v1alpha1", "github.com/knative/serving/pkg/client/clientset/versioned", "github.com/knative/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1", - "github.com/knative/test-infra", + "github.com/knative/test-infra/scripts", + "github.com/knative/test-infra/tools/dep-collector", "github.com/prometheus/client_golang/prometheus/promhttp", "go.opencensus.io/trace", "go.uber.org/atomic", "go.uber.org/zap", "go.uber.org/zap/zapcore", - "golang.org/x/net/context", - "golang.org/x/oauth2", "golang.org/x/sync/errgroup", - "google.golang.org/grpc/codes", - "google.golang.org/grpc/status", - "gopkg.in/go-playground/webhooks.v3", - "gopkg.in/go-playground/webhooks.v3/github", "gopkg.in/yaml.v2", - "k8s.io/api/apps/v1", - "k8s.io/api/batch/v1", "k8s.io/api/core/v1", "k8s.io/api/rbac/v1beta1", "k8s.io/apimachinery/pkg/api/equality", @@ -1112,10 +1066,8 @@ "k8s.io/apimachinery/pkg/runtime/serializer", "k8s.io/apimachinery/pkg/types", "k8s.io/apimachinery/pkg/util/intstr", - "k8s.io/apimachinery/pkg/util/runtime", "k8s.io/apimachinery/pkg/util/sets", "k8s.io/apimachinery/pkg/util/sets/types", - "k8s.io/apimachinery/pkg/util/validation", "k8s.io/apimachinery/pkg/util/wait", "k8s.io/apimachinery/pkg/util/yaml", "k8s.io/apimachinery/pkg/watch", @@ -1124,13 +1076,8 @@ "k8s.io/client-go/dynamic", "k8s.io/client-go/dynamic/fake", "k8s.io/client-go/informers", - "k8s.io/client-go/informers/core/v1", "k8s.io/client-go/kubernetes", "k8s.io/client-go/kubernetes/scheme", - "k8s.io/client-go/kubernetes/typed/core/v1", - "k8s.io/client-go/listers/apps/v1", - "k8s.io/client-go/listers/core/v1", - "k8s.io/client-go/listers/rbac/v1beta1", "k8s.io/client-go/plugin/pkg/client/auth/gcp", "k8s.io/client-go/rest", "k8s.io/client-go/testing", @@ -1138,7 +1085,6 @@ "k8s.io/client-go/tools/clientcmd", "k8s.io/client-go/tools/record", "k8s.io/client-go/util/flowcontrol", - "k8s.io/client-go/util/workqueue", "k8s.io/code-generator/cmd/client-gen", "k8s.io/code-generator/cmd/deepcopy-gen", "k8s.io/code-generator/cmd/defaulter-gen", diff --git a/Gopkg.toml b/Gopkg.toml index acc13ba9695..c0c91e568a2 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -8,7 +8,8 @@ required = [ "k8s.io/code-generator/cmd/client-gen", "k8s.io/code-generator/cmd/lister-gen", "k8s.io/code-generator/cmd/informer-gen", - "github.com/knative/test-infra", + "github.com/knative/test-infra/scripts", + "github.com/knative/test-infra/tools/dep-collector", ] [prune] @@ -23,7 +24,6 @@ required = [ [[prune.project]] name = "github.com/knative/test-infra" - unused-packages = false non-go = false # Use HEAD (2018-04-21) to pick up: @@ -31,6 +31,7 @@ required = [ [[override]] name = "github.com/spf13/cobra" revision = "615425954c3b0d9485a7027d4d451fdcdfdee84e" + [[override]] name = "github.com/spf13/pflag" revision = "583c0c0531f06d5278b7d917446061adc344b5cd" @@ -69,27 +70,18 @@ required = [ name = "golang.org/x/oauth2" revision = "cdc340f7c179dbbfa4afd43b7614e8fcadde4269" -[[override]] - name = "cloud.google.com/go" - revision = "90f2606161ee6a14efe2ca79fc05ac2b8efe250b" - [[override]] name = "github.com/knative/pkg" - # HEAD as of 2018-10-09 - revision = "ba1a828cd571f605684f9a4506e85bc13cb65b8d" + # HEAD as of 2018-11-08 + revision = "4b704fa7948ad9ae8ec90d1cd5b4a34516b252ea" [[constraint]] name = "github.com/knative/serving" - version = "v0.1.1" + version = "v0.2.1" [[override]] name = "github.com/Shopify/sarama" - revision = "46cf3e2cf1acef7876068f66cf69ec31aad2d0b2" # includes higher level admin client -# version = "1.17.0" - -[[constraint]] - name = "github.com/bsm/sarama-cluster" - version = "2.1.13" + version = "1.19.0" [[constraint]] name = "sigs.k8s.io/controller-runtime" diff --git a/Makefile b/Makefile new file mode 100644 index 00000000000..46355fe6e18 --- /dev/null +++ b/Makefile @@ -0,0 +1,17 @@ +#This makefile is used by ci-operator + +CGO_ENABLED=0 +GOOS=linux + +install: + go install ./cmd/controller/ ./cmd/webhook/ ./pkg/provisioners/kafka ./cmd/fanoutsidecar + go build -o $(GOPATH)/bin/in-memory-channel-controller ./pkg/controller/eventing/inmemory/controller +.PHONY: install + +test-install: + go install ./test/test_images/k8sevents +.PHONY: test-install + +test-e2e: + sh openshift/e2e-tests-openshift.sh +.PHONY: test-e2e diff --git a/cmd/controller/controller-runtime-main.go b/cmd/controller/controller-runtime-main.go index bac956c5037..f36858b6482 100644 --- a/cmd/controller/controller-runtime-main.go +++ b/cmd/controller/controller-runtime-main.go @@ -16,19 +16,12 @@ limitations under the License. package main import ( - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" - feedsv1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - flowsv1alpha1 "github.com/knative/eventing/pkg/apis/flows/v1alpha1" - "github.com/knative/eventing/pkg/controller/eventing/subscription" - "github.com/knative/eventing/pkg/controller/feed" - "github.com/knative/eventing/pkg/controller/flow" - "go.uber.org/zap" "strings" + eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + "github.com/knative/eventing/pkg/controller/eventing/subscription" istiov1alpha3 "github.com/knative/pkg/apis/istio/v1alpha3" - - "github.com/knative/eventing/pkg/controller/eventtype" + "go.uber.org/zap" "k8s.io/apimachinery/pkg/runtime" _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" "sigs.k8s.io/controller-runtime/pkg/client/config" @@ -65,9 +58,6 @@ func controllerRuntimeStart(logger *zap.SugaredLogger, experimental string) erro // Add custom types to this array to get them into the manager's scheme. schemeFuncs := []SchemeFunc{ - channelsv1alpha1.AddToScheme, - feedsv1alpha1.AddToScheme, - flowsv1alpha1.AddToScheme, istiov1alpha3.AddToScheme, eventingv1alpha1.AddToScheme, } @@ -77,12 +67,7 @@ func controllerRuntimeStart(logger *zap.SugaredLogger, experimental string) erro // Add each controller's ProvideController func to this list to have the // manager run it. - providers := []ProvideFunc{ - eventtype.ProvideController, - feed.ProvideController, - flow.ProvideController, - } - + providers := []ProvideFunc{} providers = append(providers, getExperimentalControllers(logger, experimental)...) for _, provider := range providers { diff --git a/cmd/controller/kodata/HEAD b/cmd/controller/kodata/HEAD new file mode 120000 index 00000000000..8f63681d362 --- /dev/null +++ b/cmd/controller/kodata/HEAD @@ -0,0 +1 @@ +../../../.git/HEAD \ No newline at end of file diff --git a/cmd/controller/main.go b/cmd/controller/main.go index 16c1678fabf..21ab69c5221 100644 --- a/cmd/controller/main.go +++ b/cmd/controller/main.go @@ -23,31 +23,19 @@ import ( "net/http" "time" - controllerruntime "sigs.k8s.io/controller-runtime/pkg/client/config" - - kubeinformers "k8s.io/client-go/informers" - "k8s.io/client-go/kubernetes" - // Uncomment the following line to load the gcp plugin (only required to authenticate against GKE clusters). _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" - clientset "github.com/knative/eventing/pkg/client/clientset/versioned" - informers "github.com/knative/eventing/pkg/client/informers/externalversions" - "github.com/knative/eventing/pkg/controller" - "github.com/knative/eventing/pkg/controller/bus" - "github.com/knative/eventing/pkg/controller/channel" - "github.com/knative/eventing/pkg/controller/clusterbus" - sharedclientset "github.com/knative/pkg/client/clientset/versioned" - sharedinformers "github.com/knative/pkg/client/informers/externalversions" - "github.com/knative/pkg/signals" - "github.com/knative/eventing/pkg/logconfig" "github.com/knative/eventing/pkg/system" "github.com/knative/pkg/configmap" "github.com/knative/pkg/logging" "github.com/knative/pkg/logging/logkey" + "github.com/knative/pkg/signals" "github.com/prometheus/client_golang/prometheus/promhttp" "go.uber.org/zap" + "k8s.io/client-go/kubernetes" + controllerruntime "sigs.k8s.io/controller-runtime/pkg/client/config" ) const ( @@ -79,6 +67,7 @@ func main() { // set up signals so we handle the first shutdown signal gracefully stopCh := signals.SetupSignalHandler() + cfg, err := controllerruntime.GetConfig() if err != nil { logger.Fatalf("Error building kubeconfig: %v", err) @@ -89,20 +78,6 @@ func main() { logger.Fatalf("Error building kubernetes clientset: %v", err) } - client, err := clientset.NewForConfig(cfg) - if err != nil { - logger.Fatalf("Error building clientset: %v", err) - } - - sharedClient, err := sharedclientset.NewForConfig(cfg) - if err != nil { - logger.Fatalf("Error building shared clientset: %v", err) - } - - kubeInformerFactory := kubeinformers.NewSharedInformerFactory(kubeClient, time.Second*30) - informerFactory := informers.NewSharedInformerFactory(client, time.Second*30) - sharedInformerFactory := sharedinformers.NewSharedInformerFactory(sharedClient, time.Second*30) - // Watch the logging config map and dynamically update logging levels. configMapWatcher := configmap.NewInformedWatcher(kubeClient, system.Namespace) configMapWatcher.Watch(logconfig.ConfigName, logging.UpdateLevelFromConfigMap(logger, atomicLevel, logconfig.Controller, logconfig.Controller)) @@ -110,37 +85,6 @@ func main() { logger.Fatalf("failed to start controller config map watcher: %v", err) } - // Add new controllers here, except controllers that use controller-runtime. - // Those should be added to controller-runtime-main.go. - ctors := []controller.Constructor{ - bus.NewController, - clusterbus.NewController, - channel.NewController, - } - - // TODO(n3wscott): Send the logger to the controllers. - // Build all of our controllers, with the clients constructed above. - controllers := make([]controller.Interface, 0, len(ctors)) - for _, ctor := range ctors { - controllers = append(controllers, - ctor(kubeClient, client, sharedClient, cfg, kubeInformerFactory, informerFactory, sharedInformerFactory)) - } - - go kubeInformerFactory.Start(stopCh) - go informerFactory.Start(stopCh) - go sharedInformerFactory.Start(stopCh) - - // Start all of the controllers. - for _, ctrlr := range controllers { - go func(ctrlr controller.Interface) { - // We don't expect this to return until stop is called, - // but if it does, propagate it back. - if err := ctrlr.Run(threadsPerController, stopCh); err != nil { - logger.Fatalf("Error running controller: %v", err) - } - }(ctrlr) - } - // Start the controller-runtime controllers. go func() { if err := controllerRuntimeStart(logger, experimentalControllers); err != nil { diff --git a/cmd/fanoutsidecar/kodata/HEAD b/cmd/fanoutsidecar/kodata/HEAD new file mode 120000 index 00000000000..8f63681d362 --- /dev/null +++ b/cmd/fanoutsidecar/kodata/HEAD @@ -0,0 +1 @@ +../../../.git/HEAD \ No newline at end of file diff --git a/cmd/sendevent/kodata/HEAD b/cmd/sendevent/kodata/HEAD new file mode 120000 index 00000000000..8f63681d362 --- /dev/null +++ b/cmd/sendevent/kodata/HEAD @@ -0,0 +1 @@ +../../../.git/HEAD \ No newline at end of file diff --git a/cmd/sendevent/main.go b/cmd/sendevent/main.go index 491434fa398..b3f7cd80ad2 100644 --- a/cmd/sendevent/main.go +++ b/cmd/sendevent/main.go @@ -26,13 +26,13 @@ import ( "os" "time" - "github.com/knative/eventing/pkg/event" + "github.com/knative/pkg/cloudevents" "github.com/google/uuid" ) var ( - context event.EventContext + context cloudevents.EventContext webhook string data string ) @@ -61,7 +61,7 @@ func main() { } fillEventContext(&context) - req, err := event.NewRequest(webhook, untyped, context) + req, err := cloudevents.NewRequest(webhook, untyped, context) if err != nil { fmt.Printf("Failed to create request: %s", err) os.Exit(1) @@ -79,7 +79,7 @@ func main() { } } -func fillEventContext(ctx *event.EventContext) { +func fillEventContext(ctx *cloudevents.EventContext) { ctx.CloudEventsVersion = "0.1" ctx.EventTime = time.Now().UTC() diff --git a/cmd/webhook/kodata/HEAD b/cmd/webhook/kodata/HEAD new file mode 120000 index 00000000000..8f63681d362 --- /dev/null +++ b/cmd/webhook/kodata/HEAD @@ -0,0 +1 @@ +../../../.git/HEAD \ No newline at end of file diff --git a/cmd/webhook/main.go b/cmd/webhook/main.go index 8388bb45502..e35ff3d7304 100644 --- a/cmd/webhook/main.go +++ b/cmd/webhook/main.go @@ -19,6 +19,8 @@ import ( "flag" "log" + "github.com/knative/eventing/pkg/channeldefaulter" + "go.uber.org/zap" "github.com/knative/pkg/configmap" @@ -27,10 +29,7 @@ import ( "github.com/knative/pkg/signals" "github.com/knative/pkg/webhook" - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" - feedsv1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - flowsv1alpha1 "github.com/knative/eventing/pkg/apis/flows/v1alpha1" "github.com/knative/eventing/pkg/logconfig" "github.com/knative/eventing/pkg/system" @@ -73,6 +72,13 @@ func main() { configMapWatcher := configmap.NewInformedWatcher(kubeClient, system.Namespace) configMapWatcher.Watch(logconfig.ConfigName, logging.UpdateLevelFromConfigMap(logger, atomicLevel, logconfig.Webhook, logconfig.Webhook)) + + // Watch the default-channel-webhook ConfigMap and dynamically update the default + // ClusterChannelProvisioner. + channelDefaulter := channeldefaulter.New(logger.Desugar()) + eventingv1alpha1.ChannelDefaulterSingleton = channelDefaulter + configMapWatcher.Watch(channeldefaulter.ConfigMapName, channelDefaulter.UpdateConfigMap) + if err = configMapWatcher.Start(stopCh); err != nil { logger.Fatalf("failed to start webhook configmap watcher: %v", err) } @@ -90,26 +96,9 @@ func main() { Options: options, Handlers: map[schema.GroupVersionKind]webhook.GenericCRD{ // For group eventing.knative.dev, - eventingv1alpha1.SchemeGroupVersion.WithKind("Channel"): &eventingv1alpha1.Channel{}, - eventingv1alpha1.SchemeGroupVersion.WithKind("ClusterProvisioner"): &eventingv1alpha1.ClusterProvisioner{}, - eventingv1alpha1.SchemeGroupVersion.WithKind("Source"): &eventingv1alpha1.Source{}, - eventingv1alpha1.SchemeGroupVersion.WithKind("Subscription"): &eventingv1alpha1.Subscription{}, - - // For group channels.knative.dev, - channelsv1alpha1.SchemeGroupVersion.WithKind("Bus"): &channelsv1alpha1.Bus{}, - channelsv1alpha1.SchemeGroupVersion.WithKind("ClusterBus"): &channelsv1alpha1.ClusterBus{}, - channelsv1alpha1.SchemeGroupVersion.WithKind("Channel"): &channelsv1alpha1.Channel{}, - channelsv1alpha1.SchemeGroupVersion.WithKind("Subscription"): &channelsv1alpha1.Subscription{}, - - // For group feeds.knative.dev, - feedsv1alpha1.SchemeGroupVersion.WithKind("EventSource"): &feedsv1alpha1.EventSource{}, - feedsv1alpha1.SchemeGroupVersion.WithKind("ClusterEventSource"): &feedsv1alpha1.ClusterEventSource{}, - feedsv1alpha1.SchemeGroupVersion.WithKind("EventType"): &feedsv1alpha1.EventType{}, - feedsv1alpha1.SchemeGroupVersion.WithKind("ClusterEventType"): &feedsv1alpha1.ClusterEventType{}, - feedsv1alpha1.SchemeGroupVersion.WithKind("Feed"): &feedsv1alpha1.Feed{}, - - // For group flows.knative.dev, - flowsv1alpha1.SchemeGroupVersion.WithKind("Flow"): &flowsv1alpha1.Flow{}, + eventingv1alpha1.SchemeGroupVersion.WithKind("Channel"): &eventingv1alpha1.Channel{}, + eventingv1alpha1.SchemeGroupVersion.WithKind("ClusterChannelProvisioner"): &eventingv1alpha1.ClusterChannelProvisioner{}, + eventingv1alpha1.SchemeGroupVersion.WithKind("Subscription"): &eventingv1alpha1.Subscription{}, }, Logger: logger, } diff --git a/config/200-clusterrole.yaml b/config/200-clusterrole.yaml deleted file mode 100644 index d9700d299f9..00000000000 --- a/config/200-clusterrole.yaml +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright 2018 The Knative 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. -kind: ClusterRole -apiVersion: rbac.authorization.k8s.io/v1 -metadata: - name: knative-channels-bus -rules: -- apiGroups: ["channels.knative.dev"] - resources: ["buses", "clusterbuses"] - verbs: ["get", "watch", "list"] -- apiGroups: ["channels.knative.dev"] - resources: ["channels", "subscriptions"] - verbs: ["get", "watch", "list", "update", "patch"] -- apiGroups: [""] - resources: ["events"] - verbs: ["create", "patch"] diff --git a/config/200-serviceaccount.yaml b/config/200-serviceaccount.yaml index 7fcb5bdca24..994c753bb0f 100644 --- a/config/200-serviceaccount.yaml +++ b/config/200-serviceaccount.yaml @@ -16,10 +16,3 @@ kind: ServiceAccount metadata: name: eventing-controller namespace: knative-eventing - ---- -apiVersion: v1 -kind: ServiceAccount -metadata: - name: bus-operator - namespace: knative-eventing diff --git a/config/201-clusterrolebinding.yaml b/config/201-clusterrolebinding.yaml index df10a93d2e8..ddf212a4cac 100644 --- a/config/201-clusterrolebinding.yaml +++ b/config/201-clusterrolebinding.yaml @@ -23,17 +23,3 @@ roleRef: kind: ClusterRole name: cluster-admin apiGroup: rbac.authorization.k8s.io - ---- -apiVersion: rbac.authorization.k8s.io/v1beta1 -kind: ClusterRoleBinding -metadata: - name: bus-operator-manage -subjects: - - kind: ServiceAccount - name: bus-operator - namespace: knative-eventing -roleRef: - kind: ClusterRole - name: knative-channels-bus - apiGroup: rbac.authorization.k8s.io diff --git a/config/300-bus.yaml b/config/300-bus.yaml deleted file mode 100644 index 3aa3d9bc245..00000000000 --- a/config/300-bus.yaml +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright 2018 The Knative 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. -apiVersion: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - name: buses.channels.knative.dev -spec: - group: channels.knative.dev - version: v1alpha1 - names: - kind: Bus - plural: buses - singular: bus - categories: - - all - - knative - - kbus - - eventing - scope: Namespaced diff --git a/config/300-channel.yaml b/config/300-channel.yaml index d5ddc7f370c..add65209481 100644 --- a/config/300-channel.yaml +++ b/config/300-channel.yaml @@ -14,9 +14,9 @@ apiVersion: apiextensions.k8s.io/v1beta1 kind: CustomResourceDefinition metadata: - name: channels.channels.knative.dev + name: channels.eventing.knative.dev spec: - group: channels.knative.dev + group: eventing.knative.dev version: v1alpha1 names: kind: Channel diff --git a/config/300-channeleventing.yaml b/config/300-channeleventing.yaml deleted file mode 100644 index add65209481..00000000000 --- a/config/300-channeleventing.yaml +++ /dev/null @@ -1,31 +0,0 @@ -# Copyright 2018 The Knative 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. -apiVersion: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - name: channels.eventing.knative.dev -spec: - group: eventing.knative.dev - version: v1alpha1 - names: - kind: Channel - plural: channels - singular: channel - categories: - - all - - knative - - eventing - shortNames: - - chan - scope: Namespaced diff --git a/config/300-clusterbus.yaml b/config/300-clusterbus.yaml deleted file mode 100644 index 1c3d290b3e4..00000000000 --- a/config/300-clusterbus.yaml +++ /dev/null @@ -1,32 +0,0 @@ -# Copyright 2018 The Knative 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. -apiVersion: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - name: clusterbuses.channels.knative.dev -spec: - group: channels.knative.dev - version: v1alpha1 - names: - kind: ClusterBus - plural: clusterbuses - singular: clusterbus - categories: - - all - - knative - - kbus - - eventing - shortNames: - - cbus - scope: Cluster diff --git a/config/300-clusterprovisioner.yaml b/config/300-clusterchannelprovisioner.yaml similarity index 80% rename from config/300-clusterprovisioner.yaml rename to config/300-clusterchannelprovisioner.yaml index e8e75547c3f..d02f068f27b 100644 --- a/config/300-clusterprovisioner.yaml +++ b/config/300-clusterchannelprovisioner.yaml @@ -14,16 +14,18 @@ apiVersion: apiextensions.k8s.io/v1beta1 kind: CustomResourceDefinition metadata: - name: clusterprovisioners.eventing.knative.dev + name: clusterchannelprovisioners.eventing.knative.dev spec: group: eventing.knative.dev version: v1alpha1 names: - kind: ClusterProvisioner - plural: clusterprovisioners - singular: clusterprovisioner + kind: ClusterChannelProvisioner + plural: clusterchannelprovisioners + singular: clusterchannelprovisioner categories: - all - knative - eventing + shortNames: + - ccp scope: Cluster diff --git a/config/300-clustereventsource.yaml b/config/300-clustereventsource.yaml deleted file mode 100644 index 8537e37c1ed..00000000000 --- a/config/300-clustereventsource.yaml +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright 2018 The Knative 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. -apiVersion: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - name: clustereventsources.feeds.knative.dev -spec: - group: feeds.knative.dev - version: v1alpha1 - names: - kind: ClusterEventSource - plural: clustereventsources - singular: clustereventsource - categories: - - all - - knative - - keventsource - - eventing - scope: Cluster diff --git a/config/300-clustereventtype.yaml b/config/300-clustereventtype.yaml deleted file mode 100644 index 2aeeac477c0..00000000000 --- a/config/300-clustereventtype.yaml +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright 2018 The Knative 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. -apiVersion: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - name: clustereventtypes.feeds.knative.dev -spec: - group: feeds.knative.dev - version: v1alpha1 - names: - kind: ClusterEventType - plural: clustereventtypes - singular: clustereventsource - categories: - - all - - knative - - keventtype - - eventing - scope: Cluster diff --git a/config/300-eventsource.yaml b/config/300-eventsource.yaml deleted file mode 100644 index e03079fe292..00000000000 --- a/config/300-eventsource.yaml +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright 2018 The Knative 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. -apiVersion: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - name: eventsources.feeds.knative.dev -spec: - group: feeds.knative.dev - version: v1alpha1 - names: - kind: EventSource - plural: eventsources - singular: eventsource - categories: - - all - - knative - - keventsource - - eventing - scope: Namespaced diff --git a/config/300-eventtype.yaml b/config/300-eventtype.yaml deleted file mode 100644 index ce2f4c8aa24..00000000000 --- a/config/300-eventtype.yaml +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright 2018 The Knative 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. -apiVersion: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - name: eventtypes.feeds.knative.dev -spec: - group: feeds.knative.dev - version: v1alpha1 - names: - kind: EventType - plural: eventtypes - singular: eventtype - categories: - - all - - knative - - keventtype - - eventing - scope: Namespaced diff --git a/config/300-feed.yaml b/config/300-feed.yaml deleted file mode 100644 index 4fdcc0d5d90..00000000000 --- a/config/300-feed.yaml +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright 2018 The Knative 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. -apiVersion: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - name: feeds.feeds.knative.dev -spec: - group: feeds.knative.dev - version: v1alpha1 - names: - kind: Feed - plural: feeds - singular: feed - categories: - - all - - knative - - eventing - scope: Namespaced diff --git a/config/300-flow.yaml b/config/300-flow.yaml deleted file mode 100644 index 3d699bb70e3..00000000000 --- a/config/300-flow.yaml +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright 2018 The Knative 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. -apiVersion: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - name: flows.flows.knative.dev -spec: - group: flows.knative.dev - version: v1alpha1 - names: - kind: Flow - plural: flows - singular: flow - categories: - - all - - knative - - eventing - scope: Namespaced diff --git a/config/300-source.yaml b/config/300-source.yaml deleted file mode 100644 index 6e63f85dbfc..00000000000 --- a/config/300-source.yaml +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright 2018 The Knative 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. -apiVersion: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - name: sources.eventing.knative.dev -spec: - group: eventing.knative.dev - version: v1alpha1 - names: - kind: Source - plural: sources - singular: source - categories: - - all - - knative - - eventing - scope: Namespaced diff --git a/config/300-subscription.yaml b/config/300-subscription.yaml index 94ac409e743..cc974f51254 100644 --- a/config/300-subscription.yaml +++ b/config/300-subscription.yaml @@ -14,9 +14,9 @@ apiVersion: apiextensions.k8s.io/v1beta1 kind: CustomResourceDefinition metadata: - name: subscriptions.channels.knative.dev + name: subscriptions.eventing.knative.dev spec: - group: channels.knative.dev + group: eventing.knative.dev version: v1alpha1 names: kind: Subscription diff --git a/config/300-subscriptioneventing.yaml b/config/300-subscriptioneventing.yaml deleted file mode 100644 index cc974f51254..00000000000 --- a/config/300-subscriptioneventing.yaml +++ /dev/null @@ -1,31 +0,0 @@ -# Copyright 2018 The Knative 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. -apiVersion: apiextensions.k8s.io/v1beta1 -kind: CustomResourceDefinition -metadata: - name: subscriptions.eventing.knative.dev -spec: - group: eventing.knative.dev - version: v1alpha1 - names: - kind: Subscription - plural: subscriptions - singular: subscription - categories: - - all - - knative - - eventing - shortNames: - - sub - scope: Namespaced diff --git a/config/400-flow-controller-config.yaml b/config/400-default-channel-config.yaml similarity index 57% rename from config/400-flow-controller-config.yaml rename to config/400-default-channel-config.yaml index a3b3e56e0e4..cffed22d32d 100644 --- a/config/400-flow-controller-config.yaml +++ b/config/400-default-channel-config.yaml @@ -11,11 +11,22 @@ # 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. + apiVersion: v1 kind: ConfigMap metadata: - name: flow-controller-config + name: default-channel-webhook namespace: knative-eventing data: - # Configuration for the flow controller - default-cluster-bus: stub + # Configuration for defaulting channels that do not specify provisioners. All field names are + # lowercase. + default-channel-config: | + clusterdefault: + apiversion: eventing.knative.dev/v1alpha1 + kind: ClusterChannelProvisioner + name: in-memory-channel + namespacedefaults: + some-namespace: + apiversion: eventing.knative.dev/v1alpha1 + kind: ClusterChannelProvisioner + name: some-other-provisioner diff --git a/config/500-webhook.yaml b/config/500-webhook.yaml index da8d81404eb..5db9f5b1972 100644 --- a/config/500-webhook.yaml +++ b/config/500-webhook.yaml @@ -40,4 +40,4 @@ spec: volumes: - name: config-logging configMap: - name: config-logging \ No newline at end of file + name: config-logging diff --git a/config/buses/gcppubsub/README.md b/config/buses/gcppubsub/README.md deleted file mode 100644 index ca07926534c..00000000000 --- a/config/buses/gcppubsub/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# GCP Cloud Pub/Sub - Knative Bus - -Deployment steps: -1. Setup [Knative Eventing](../../../DEVELOPMENT.md) -1. [Create a service account](https://console.cloud.google.com/iam-admin/serviceaccounts/project) with the 'Pub/Sub Editor' role, and download a new JSON private key. -1. Create a secret for the downloaded key `kubectl -n knative-eventing create secret generic gcppubsub-bus-key --from-file=key.json=PATH-TO-KEY-FILE.json` -1. Configure the bus, replacing `$PROJECT_ID` with your GCP Project ID, `kubectl -n knative-eventing create configmap gcppubsub-bus-config --from-literal=GOOGLE_CLOUD_PROJECT=$PROJECT_ID` -1. For cluster wide deployment, change the kind in `config/buses/gcppubsub/gcppubsub-bus.yaml` from `Bus` to `ClusterBus`. -1. Apply the 'gcppubsub' Bus `ko apply -f config/buses/gcppubsub/` -1. If you want to set the default Knative Bus to GCP Cloud Pub/Sub run the following command to edit the Knative Eventing configuration (requires the above change in kind from `Bus` to `ClusterBus`): - ```shell - kubectl get cm flow-controller-config -n knative-eventing -oyaml \ - | sed -e 's/default-cluster-bus: stub/ default-cluster-bus: gcppubsub/' \ - | kubectl replace -f - - ``` -1. Create Channels that reference the 'gcppubsub' Bus -1. (Optional) Install [Kail](https://github.com/boz/kail) - Kubernetes tail - -The bus has an independent provisioner and dispatcher. - -The provisioner will create GCP Pub/Sub Topics and Subscriptions for each Knative Channel and Subscription (respectively) targeting the Bus. Clients should avoid interacting with topics and subscriptions provisioned by the Bus. - -The dispatcher receives events via a Channel's Service from inside the cluster and sends them to the Pub/Sub Topic. Events on the Pub/Sub topic for an active subscription are forwarded via HTTP to the subscribers. HTTP responses with a 2xx status code are ack'ed while all other status codes will nack the event, delivery will be reattempted up to the limits defined by Cloud Pub/Sub. - -Note: Cloud Pub/Sub does not guarantee exactly once delivery, subscribers must guard against multiple deliveries of the same event. - -To view logs: -- for the dispatcher `kail -d gcppubsub-[namespace]-bus-dispatcher -c dispatcher` -- for the provisioner `kail -d gcppubsub-[namespace]-bus-provisioner -c provisioner` diff --git a/config/buses/gcppubsub/gcppubsub-bus.yaml b/config/buses/gcppubsub/gcppubsub-bus.yaml deleted file mode 100644 index 3921ba6a94e..00000000000 --- a/config/buses/gcppubsub/gcppubsub-bus.yaml +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright 2018 The Knative 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. -apiVersion: channels.knative.dev/v1alpha1 -kind: Bus -metadata: - name: gcppubsub -spec: - provisioner: - name: provisioner - image: github.com/knative/eventing/pkg/buses/gcppubsub/provisioner - args: [ - "-logtostderr", - "-stderrthreshold", "INFO", - ] - env: &env - - name: GOOGLE_CLOUD_PROJECT - valueFrom: - configMapKeyRef: - name: gcppubsub-bus-config - key: GOOGLE_CLOUD_PROJECT - - name: GOOGLE_APPLICATION_CREDENTIALS - value: /var/secrets/google/key.json - volumeMounts: - - name: google-cloud-key - mountPath: /var/secrets/google - dispatcher: - name: dispatcher - image: github.com/knative/eventing/pkg/buses/gcppubsub/dispatcher - args: [ - "-logtostderr", - "-stderrthreshold", "INFO", - ] - env: *env - volumeMounts: - - name: google-cloud-key - mountPath: /var/secrets/google - volumes: - - name: google-cloud-key - secret: - secretName: gcppubsub-bus-key diff --git a/config/buses/gcppubsub/gcppubsub-serviceentry.yaml b/config/buses/gcppubsub/gcppubsub-serviceentry.yaml deleted file mode 100644 index ee82c10bc12..00000000000 --- a/config/buses/gcppubsub/gcppubsub-serviceentry.yaml +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright 2018 The Knative 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. -apiVersion: networking.istio.io/v1alpha3 -kind: ServiceEntry -metadata: - name: gcppubsub-bus-ext -spec: - hosts: - - "*.googleapis.com" - - "accounts.google.com" - ports: - - number: 443 - name: https - protocol: HTTPS - location: MESH_EXTERNAL diff --git a/config/buses/kafka/README.md b/config/buses/kafka/README.md deleted file mode 100644 index 0f3ea4fe044..00000000000 --- a/config/buses/kafka/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# Apache Kafka - Knative Bus - -Deployment steps: -1. Setup [Knative Eventing](../../../DEVELOPMENT.md) -1. Install an Apache Kafka cluster. There are two choices: - * Simple installation of [Apache Kafka](broker). - * A production grade installation using the [Strimzi Kafka Operator](strimzi). - -1. Now that the Apache Kafka is installed, configure the bus to use the Kafka broker, replace the broker URL if not using the provided broker: - ``` - kubectl -n knative-eventing create configmap kafka-bus-config --from-literal=KAFKA_BOOTSTRAP_SERVERS=kafkabroker.kafka:9092 - ``` - > Note: If you are using Strimzi, the value for the URL is `my-cluster-kafka-bootstrap.kafka.9092`. -1. For cluster wide deployment, change the kind in `config/buses/kafka/kafka-bus.yaml` from `Bus` to `ClusterBus`. -1. Apply the Kafka Bus: - ``` - ko apply -f config/buses/kafka/ - ``` -1. If you want to set the default Knative Bus to Kafka run the following command to edit the Knative Eventing configuration (requires the above change in kind from `Bus` to `ClusterBus`): - ```shell - kubectl get cm flow-controller-config -n knative-eventing -oyaml \ - | sed -e 's/default-cluster-bus: stub/ default-cluster-bus: kafka/' \ - | kubectl replace -f - - ``` -1. Create Channels that reference the 'kafka' Bus -1. (Optional) Install [Kail](https://github.com/boz/kail) - Kubernetes tail - -The bus has an independent provisioner and dispatcher. - -The provisioner will create Kafka topics for each Knative Channel -targeting the Bus (named `.`. -Clients should avoid interacting with topics provisioned by the bus. - -The dispatcher -- receives events via a Channel's Service from inside the cluster and -writes them to the corresponding Kafka topic -- creates a Kafka consumer for each `Subscription`, that reads events -from the subscription's channel and forwards them over HTTP to the -subscriber. - -To view logs: -- for the dispatcher `kail -d kafka-[namespace]-bus-dispatcher -c dispatcher` -- for the provisioner `kail -d kafka-[namespace]-bus-provisioner -c provisioner` diff --git a/config/buses/kafka/kafka-bus.yaml b/config/buses/kafka/kafka-bus.yaml deleted file mode 100644 index 7bc6c07ff00..00000000000 --- a/config/buses/kafka/kafka-bus.yaml +++ /dev/null @@ -1,31 +0,0 @@ -apiVersion: channels.knative.dev/v1alpha1 -kind: Bus -metadata: - name: kafka -spec: - parameters: - subscription: - - name: "initialOffset" - description: "The initial offset to use when subscribing, either Oldest or Newest. Defaults to Newest." - default: "Newest" - provisioner: - name: provisioner - image: github.com/knative/eventing/pkg/buses/kafka/provisioner - args: [ - "-logtostderr", - "-stderrthreshold", "INFO", - ] - env: &env - - name: KAFKA_BOOTSTRAP_SERVERS - valueFrom: - configMapKeyRef: - name: kafka-bus-config - key: KAFKA_BOOTSTRAP_SERVERS - dispatcher: - name: dispatcher - image: github.com/knative/eventing/pkg/buses/kafka/dispatcher - args: [ - "-logtostderr", - "-stderrthreshold", "INFO", - ] - env: *env diff --git a/config/buses/kafka/strimzi/README.md b/config/buses/kafka/strimzi/README.md deleted file mode 100644 index efd7d5437df..00000000000 --- a/config/buses/kafka/strimzi/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# Strimzi - Apache Kafka Operator - -[Strimzi](http://strimzi.io) makes it easy to run a production grade Apache Kafka installation on OpenShift or Kubernetes. It implements the _Kubernetes Operator pattern_ for mananging `clusters`, `topics` or `users` based on custom resource files. - -Installing the Strimzi Cluster Operator is simple and requires only a few steps. - -1. Create the `kafka` namespace in your Kubernetes cluster: - ``` - kubectl create namespace kafka - ``` - -1. Install the Strimzi _Cluster Operator_: - - * Applying yaml files from the [Strimzi release bundle](https://github.com/strimzi/strimzi-kafka-operator/releases/latest) - * Using the Strimzi Helm Chart - - Both ways for installing the _Cluster Operator_ are described in the [Strimzi documentation](http://strimzi.io/docs/master/#cluster-operator-str) itself - - > Note: Once this is done, you will have a `strimzi-cluster-operator` pod, which is able to install the Apache Kafka broker based on a `Kafka` custom resource file. - -1. Install the Apache Kafka cluster by providing the `kafka-persistent.yaml` Strimzi resource file from _this_ folder: - ``` - kubectl apply -f kafka-persistent.yaml -n kafka - ``` - > Note: If you want to use ephemeral storage, you have to use the `kafka-ephemeral.yaml` file. - - This provisions the complete installation of your Apache Kafka cluster. - -> Note: For learning more about Strimiz, please consult its [website](http://strimzi.io). - -Continue the configuration of Knative Eventing with [step `3`](../). diff --git a/config/buses/kafka/strimzi/kafka-ephemeral.yaml b/config/buses/kafka/strimzi/kafka-ephemeral.yaml deleted file mode 100644 index 6423bd39de9..00000000000 --- a/config/buses/kafka/strimzi/kafka-ephemeral.yaml +++ /dev/null @@ -1,23 +0,0 @@ -apiVersion: kafka.strimzi.io/v1alpha1 -kind: Kafka -metadata: - name: my-cluster -spec: - kafka: - replicas: 1 - listeners: - plain: {} - tls: {} - config: - offsets.topic.replication.factor: 3 - transaction.state.log.replication.factor: 3 - transaction.state.log.min.isr: 2 - storage: - type: ephemeral - zookeeper: - replicas: 1 - storage: - type: ephemeral - entityOperator: - topicOperator: {} - userOperator: {} diff --git a/config/buses/kafka/strimzi/kafka-persistent.yaml b/config/buses/kafka/strimzi/kafka-persistent.yaml deleted file mode 100644 index ea5fd60ce4d..00000000000 --- a/config/buses/kafka/strimzi/kafka-persistent.yaml +++ /dev/null @@ -1,27 +0,0 @@ -apiVersion: kafka.strimzi.io/v1alpha1 -kind: Kafka -metadata: - name: my-cluster -spec: - kafka: - replicas: 1 - listeners: - plain: {} - tls: {} - config: - offsets.topic.replication.factor: 3 - transaction.state.log.replication.factor: 3 - transaction.state.log.min.isr: 2 - storage: - type: persistent-claim - size: 1Gi - deleteClaim: false - zookeeper: - replicas: 1 - storage: - type: persistent-claim - size: 1Gi - deleteClaim: false - entityOperator: - topicOperator: {} - userOperator: {} diff --git a/config/buses/stub/README.md b/config/buses/stub/README.md deleted file mode 100644 index 4f44fe8f111..00000000000 --- a/config/buses/stub/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# Stub - Knative Bus - -Deployment steps: -1. Setup [Knative Eventing](../../../DEVELOPMENT.md) -1. For cluster wide deployment, change the kind in `config/buses/stub/stub-bus.yaml` from `Bus` to `ClusterBus`. -1. Apply the 'stub' Bus `ko apply -f config/buses/stub/` -1. Create Channels that reference the 'stub' Bus -1. (Optional) Install [Kail](https://github.com/boz/kail) - Kubernetes tail - -The bus is only a dispatcher. - -The dispatcher receives events via a Channel's Service from inside the cluster and forwarded via HTTP to the subscribers. - -Note: The stub bus does not guarantee delivery, errors will not be reattempted. - -To view logs: `kail -d stub-[namespace]-bus-dispatcher -c dispatcher` diff --git a/config/buses/stub/stub-bus.yaml b/config/buses/stub/stub-bus.yaml deleted file mode 100644 index 27cffb43c15..00000000000 --- a/config/buses/stub/stub-bus.yaml +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright 2018 The Knative 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. -apiVersion: channels.knative.dev/v1alpha1 -kind: Bus -metadata: - name: stub -spec: - dispatcher: - name: dispatcher - image: github.com/knative/eventing/pkg/buses/stub/dispatcher - args: [ - "-logtostderr", - "-stderrthreshold", "INFO", - ] diff --git a/config/provisioners/in-memory-channel/README.md b/config/provisioners/in-memory-channel/README.md index d895f9b32c4..814a592bce9 100644 --- a/config/provisioners/in-memory-channel/README.md +++ b/config/provisioners/in-memory-channel/README.md @@ -18,9 +18,9 @@ They differ from most Channels in that they have: ### Deployment steps: 1. Setup [Knative Eventing](../../../DEVELOPMENT.md). -1. Apply the 'in-memory-channel' ClusterProvisioner, Controller, and Dispatcher. +1. Apply the 'in-memory-channel' ClusterChannelProvisioner, Controller, and Dispatcher. ```shell - ko apply -f config/providers/in-memory-channel/in-memory-channel.yaml + ko apply -f config/provisioners/in-memory-channel/in-memory-channel.yaml ```` 1. Create Channels that reference the 'in-memory-channel'. @@ -31,21 +31,20 @@ They differ from most Channels in that they have: name: foo spec: provisioner: - ref: - apiVersion: eventing.knative.dev/v1alpha1 - kind: ClusterProvisioner - name: in-memory-channel + apiVersion: eventing.knative.dev/v1alpha1 + kind: ClusterChannelProvisioner + name: in-memory-channel ``` ### Components The major components are: -* ClusterProvisioner Controller +* ClusterChannelProvisioner Controller * Channel Controller * Channel Dispatcher * Channel Dispatcher Config Map. -The ClusterProvisioner Controller and the Channel Controller are colocated in one Pod. +The ClusterChannelProvisioner Controller and the Channel Controller are colocated in one Pod. ```shell kubectl get deployment -n knative-eventing in-memory-channel-controller ``` diff --git a/config/provisioners/in-memory-channel/in-memory-channel.yaml b/config/provisioners/in-memory-channel/in-memory-channel.yaml index 44a15c66175..941da4fd30e 100644 --- a/config/provisioners/in-memory-channel/in-memory-channel.yaml +++ b/config/provisioners/in-memory-channel/in-memory-channel.yaml @@ -13,13 +13,10 @@ # limitations under the License. apiVersion: eventing.knative.dev/v1alpha1 -kind: ClusterProvisioner +kind: ClusterChannelProvisioner metadata: name: in-memory-channel -spec: - reconciles: - group: eventing.knative.dev/v1alpha1 - kind: Channel +spec: {} --- @@ -40,12 +37,18 @@ rules: - eventing.knative.dev resources: - channels - - clusterprovisioners + - clusterchannelprovisioners verbs: - get - list - watch - update + - apiGroups: + - eventing.knative.dev + resources: + - channels/finalizers + verbs: + - update - apiGroups: - "" # Core API group. resources: @@ -101,7 +104,7 @@ spec: replicas: 1 selector: matchLabels: &labels - clusterProvisioner: in-memory-channel + clusterChannelProvisioner: in-memory-channel role: controller template: metadata: @@ -164,7 +167,7 @@ spec: replicas: 1 selector: matchLabels: &labels - clusterProvisioner: in-memory-channel + clusterChannelProvisioner: in-memory-channel role: dispatcher template: metadata: diff --git a/config/provisioners/kafka/README.md b/config/provisioners/kafka/README.md new file mode 100644 index 00000000000..4e5206dca22 --- /dev/null +++ b/config/provisioners/kafka/README.md @@ -0,0 +1,78 @@ +# Apache Kafka Channels + +Deployment steps: +1. Setup [Knative Eventing](../../../DEVELOPMENT.md) +1. If not done already, install an Apache Kafka cluster. There are two choices: + * Simple installation of [Apache Kafka](broker). + * A production grade installation using the [Strimzi Kafka Operator](strimzi). + Installation [guides](http://strimzi.io/quickstarts/) are provided for + kubernetes and Openshift. + +1. Now that Apache Kafka is installed, you need to configure the +`bootstrap_servers` value in the `kafka-channel-controller-config` ConfigMap, +located inside the `config/provisioners/kafka/kafka-channel.yaml` file: + ``` + ... + apiVersion: v1 + kind: ConfigMap + metadata: + name: kafka-channel-controller-config + namespace: knative-eventing + data: + # Broker URL's for the provisioner + bootstrap_servers: kafkabroker.kafka:9092 + ... + ``` + > Note: The `bootstrap_servers` needs to contain the address of at least + one broker of your Apache Kafka cluster. If you are using Strimzi, you need + to update the `bootstrap_servers` value to + `my-cluster-kafka-bootstrap.mynamespace:9092`. +1. Apply the 'Kafka' ClusterChannelProvisioner, Controller, and Dispatcher: + ``` + ko apply -f config/provisioners/kafka/kafka-channel.yaml + ``` +1. Create Channels that reference the 'kafka-channel'. + + ```yaml + apiVersion: eventing.knative.dev/v1alpha1 + kind: Channel + metadata: + name: my-kafka-channel + spec: + provisioner: + apiVersion: eventing.knative.dev/v1alpha1 + kind: ClusterChannelProvisioner + name: kafka-channel + ``` + +## Components + +The major components are: +* ClusterChannelProvisioner Controller +* Channel Controller +* Channel Controller Config Map. +* Channel Dispatcher +* Channel Dispatcher Config Map. + +The ClusterChannelProvisioner Controller and the Channel Controller are colocated +in one Pod: +```shell +kubectl get deployment -n knative-eventing kafka-channel-controller +``` + +The Channel Controller Config Map is used to configure the `bootstrap_servers` +of your Apache Kafka installation: +```shell +kubectl get configmap -n knative-eventing kafka-channel-dispatcher-config-map +``` + +The Channel Dispatcher receives and distributes all events: +```shell +kubectl get statefulset -n knative-eventing kafka-channel-dispatcher +``` + +The Channel Dispatcher Config Map is used to send information about Channels and +Subscriptions from the Channel Controller to the Channel Dispatcher: +```shell +kubectl get configmap -n knative-eventing kafka-channel-dispatcher-config-map +``` diff --git a/config/buses/kafka/broker/README.md b/config/provisioners/kafka/broker/README.md similarity index 74% rename from config/buses/kafka/broker/README.md rename to config/provisioners/kafka/broker/README.md index fe6dcff648f..b47d0945734 100644 --- a/config/buses/kafka/broker/README.md +++ b/config/provisioners/kafka/broker/README.md @@ -1,6 +1,6 @@ -# Apache Kakfa - simple installation +# Apache Kafka - simple installation -1. For an installation of a simple Apache Kafka cluster, a setup is provided: +1. For an installation of a simple (**non production**) Apache Kafka cluster, a setup is provided: ``` kubectl create namespace kafka kubectl apply -n kafka -f kafka-broker.yaml diff --git a/config/buses/kafka/broker/kafka-broker.yaml b/config/provisioners/kafka/broker/kafka-broker.yaml similarity index 100% rename from config/buses/kafka/broker/kafka-broker.yaml rename to config/provisioners/kafka/broker/kafka-broker.yaml diff --git a/config/provisioners/kafka/kafka-channel.yaml b/config/provisioners/kafka/kafka-channel.yaml new file mode 100644 index 00000000000..94eb1f53f9d --- /dev/null +++ b/config/provisioners/kafka/kafka-channel.yaml @@ -0,0 +1,198 @@ +# Copyright 2018 The Knative 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 +# +# https://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. + +apiVersion: eventing.knative.dev/v1alpha1 +kind: ClusterChannelProvisioner +metadata: + name: kafka-channel +spec: {} +--- + +apiVersion: v1 +kind: ServiceAccount +metadata: + name: kafka-channel-controller + namespace: knative-eventing +--- + +kind: ClusterRole +apiVersion: rbac.authorization.k8s.io/v1 +metadata: + name: kafka-channel-controller +rules: + - apiGroups: + - eventing.knative.dev + resources: + - channels + - clusterchannelprovisioners + verbs: + - get + - list + - watch + - update + - apiGroups: + - "" # Core API group. + resources: + - services + - configmaps + verbs: + - get + - list + - watch + - create + - apiGroups: + - "" # Core API Group. + resources: + - configmaps + resourceNames: + - kafka-channel-dispatcher + verbs: + - update + - apiGroups: + - networking.istio.io + resources: + - virtualservices + verbs: + - get + - list + - watch + - create +--- + +apiVersion: rbac.authorization.k8s.io/v1beta1 +kind: ClusterRoleBinding +metadata: + name: kafka-channel-controller-manage +subjects: + - kind: ServiceAccount + name: kafka-channel-controller + namespace: knative-eventing +roleRef: + kind: ClusterRole + name: kafka-channel-controller + apiGroup: rbac.authorization.k8s.io +--- + +apiVersion: v1 +kind: ConfigMap +metadata: + name: kafka-channel-controller-config + namespace: knative-eventing +data: + # Broker URL's for the provisioner. Replace this with the URL's for your kafka cluster. + bootstrap_servers: kafkabroker.kafka:9092 +--- + +apiVersion: apps/v1beta1 +kind: Deployment +metadata: + name: kafka-channel-controller + namespace: knative-eventing +spec: + replicas: 1 + template: + metadata: + labels: + app: kafka-channel-controller + spec: + serviceAccountName: kafka-channel-controller + containers: + - name: kafka-channel-controller-controller + image: github.com/knative/eventing/pkg/provisioners/kafka/cmd/controller + volumeMounts: + - name: kafka-channel-controller-config + mountPath: /etc/config-provisioner + volumes: + - name: kafka-channel-controller-config + configMap: + name: kafka-channel-controller-config +--- + +apiVersion: v1 +kind: ServiceAccount +metadata: + name: kafka-channel-dispatcher + namespace: knative-eventing + +--- + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: kafka-channel-dispatcher + namespace: knative-eventing +rules: + - apiGroups: + - "" # Core API group. + resources: + - configmaps + verbs: + - get + - list + - watch + +--- + +apiVersion: rbac.authorization.k8s.io/v1beta1 +kind: ClusterRoleBinding +metadata: + name: kafka-channel-dispatcher + namespace: knative-eventing +subjects: + - kind: ServiceAccount + name: kafka-channel-dispatcher + namespace: knative-eventing +roleRef: + kind: ClusterRole + name: kafka-channel-dispatcher + apiGroup: rbac.authorization.k8s.io + +--- + +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: kafka-channel-dispatcher + namespace: knative-eventing +spec: + replicas: 1 + selector: + matchLabels: &labels + clusterChannelProvisioner: kafka-channel + role: dispatcher + serviceName: kafka-channel-dispatcher-service + template: + metadata: + annotations: + sidecar.istio.io/inject: "true" + labels: *labels + spec: + serviceAccountName: kafka-channel-dispatcher + containers: + - name: dispatcher + image: github.com/knative/eventing/pkg/provisioners/kafka/cmd/dispatcher + env: + - name: DISPATCHER_CONFIGMAP_NAME + value: kafka-channel-dispatcher + - name: DISPATCHER_CONFIGMAP_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + volumeMounts: + - name: kafka-channel-controller-config + mountPath: /etc/config-provisioner + volumes: + - name: kafka-channel-controller-config + configMap: + name: kafka-channel-controller-config diff --git a/docs/spec/interfaces.md b/docs/spec/interfaces.md index 3142554fb24..37fc779c3fd 100644 --- a/docs/spec/interfaces.md +++ b/docs/spec/interfaces.md @@ -1,88 +1,68 @@ # Interface Contracts -## Subscribable - -A **Subscribable** resource contains a list of subscribers and is responsible -for delivering events to each of them. Subscriptions only allow Channels to be -Subscribable (via `spec.from` on the Subscription) at the moment, but this may -be revisited with future experience. _Channel_ as the target of a -_Subscription_'s `from` field. +## Addressable +An **Addressable** resource receives events over a network transport +(currently only HTTP is supported). The _Addressable_ returns success when it +has successfully handled the event (for example, by committing it to stable +storage). When used as an _Addressable_, only the acknowledgement or return +code is used to determine whether the event was handled successfully. One +example of an _Addressable_ is a _Channel_. ### Control Plane -The **Subscribable** resource stores a list of resolved _Subscriptions_ in the -resource's `spec.subscribers` field. The Subscription Controller is responsible -for resolving any ObjectReferences (such as _call_ and _result_) in the -_Subscription_ to network addresses. +An **Addressable** resource MUST expose a `status.address.hostname` field. +The _hostname_ value is a cluster-resolvable DNS name which is capable of +receiving event deliveries. _Addressable_ resources may be referenced in the +`reply` section of a _Subscription_, and also by other custom resources acting +as an event Source. ### Data Plane -**Subscribable** resources will attempt delivery to each of the _subscribers_ -at least once, and retry if the subscriber returns errors. - - +An **Addressable** resource will only respond to requests with success or +failure. Any payload (including a valid CloudEvent) returned to the sender +will be ignored. An _Addressable_ may receive the same event multiple times +even if it previously indicated success. --- -## Targetable +## Callable -A **Targetable** resource represents an endpoint that receives events and -optionally returns events to forward downstream. One example of a _Targetable_ -is a function. +A **Callable** resource represents an _Addressable_ endpoint which receives +events and optionally returns events to forward downstream. One example of a +_Callable_ is a function. Note that all _Callable_ resources are _Addressable_ +(they accept an event and return a status code when completed), but not all +_Addressable_ resources are _Callable_. ### Control Plane -A **Targetable** resource MUST expose a _status.targetable.domainInternal_ -field. The _domainInternal_ value is an internal domain name that is capable of -receiving event deliveries. _Targetable_ resources may be referenced in the -_call_ section of a _Subscription_. +A **Callable** resource MUST expose a `status.address.hostname` field (like +_Addressable_). The _hostname_ value is a cluster-resolvable DNS name which is +capable of receiving event deliveries and returning a resulting event in the +reply.. _Callable_ resources may be referenced in the `subscriber` section of +a _Subscription_. + + ### Data Plane -The **Targetable** resource receives one event and returns zero or more events +The **Callable** resource receives one event and returns zero or more events in response. The returned events are not required to be related to the received -event. The _Targetable_ should return a successful response if the event was +event. The _Callable_ should return a successful response if the event was processed successfully. -The _Targetable_ is not responsible for ensuring successful delivery of any +The _Callable_ is not responsible for ensuring successful delivery of any received or returned event. It may receive the same event multiple times even if it previously indicated success. --- -## Sinkable - -A **Sinkable** resource receives events and takes responsibility for further -delivery. Unlike _Targetable_, a _Sinkable_ cannot return events in its -response. One example of a _Sinkable_ is a _Channel_ as the target of a -_Subscription_'s _result_ field. - - - -### Control Plane - -A **Sinkable** resource MUST expose a _status.sinkable.domainInternal_ field. -The _domainInternal_ value is an internal domain name that is capable of -receiving event deliveries. _Sinkable_ resources may be referenced in the -_result_ section of a _Subscription_, and also by other custom resources acting as an event Source. - -### Data Plane - -A **Sinkable** resource will only respond to requests with success of failure. -Any payload (including a valid CloudEvent) returned to the sender will be -ignored. It may receive the same event multiple times even if it previously -indicated success. - ---- - _Navigation_: - [Motivation and goals](motivation.md) diff --git a/docs/spec/overview.md b/docs/spec/overview.md index f111164d321..dfb136224fe 100644 --- a/docs/spec/overview.md +++ b/docs/spec/overview.md @@ -1,25 +1,25 @@ # Resource Types The API defines and provides a complete implementation for -[Subscription](spec.md#kind-subscription), and abstract resource definitions +[Subscription](spec.md#kind-subscription) and abstract resource definitions for [Channels](spec.md#kind-channel) and -[ClusterChannelProvisioners](spec.md#kind-clusterchannelprovisioner) which may -be fulfilled by multiple backing implementations (much like the Kubernetes -Ingress resource). +[ClusterChannelProvisioners](spec.md#kind-clusterchannelprovisioner) which +may be fulfilled by multiple backing implementations (much like the +Kubernetes Ingress resource). -With extendibility and compostability as a goal of Knative Eventing, the -eventing API defines several resources that can be reduced down to a well +With extensibility and composability as a goal of Knative Eventing, the +eventing API defines several resources that can be reduced down to well understood contracts. These eventing resource interfaces may be fulfilled by -other Kubernetes objects and then composed in the same way as the concreate -objects. The interfaces are ([Sinkable](interfaces.md#sinkable), +other Kubernetes objects and then composed in the same way as the concrete +objects. The interfaces are ([Addressable](interfaces.md#addressable), [Subscribable](interfaces.md#Subscribable), -[Targetable](interfaces.md#targetable)). For more details, see +[Callable](interfaces.md#callable)). For more details, see [Interface Contracts](interfaces.md). - A **Subscription** describes the transformation of an event and optional forwarding of a returned event. -- A **Channel** provides event persistance and fanout of events from a +- A **Channel** provides event persistence and fanout of events from a well-known input address to multiple outputs described by _Subscriptions_. @@ -40,28 +40,28 @@ Sources](https://github.com/knative/eventing-sources). ## Subscription -**Subscriptions** describe a flow of events from one _Channel_) to the next +**Subscriptions** describe a flow of events from one _Channel_ to the next Channel\* through transformations (such as a Knative Service which processes CloudEvents over HTTP). A _Subscription_ controller resolves the addresses of -transformations (`call`) and destination storage (`result`) through the -_Targetable_ and _Sinkable_ interface contracts, and writes the resolved -addresses to the _Channel_ in the `from` reference. _Subscriptions_ do not need -to specify both a transformation and a storage destination, but at least one -must be provided. +transformations (`subscriber`) and destination storage (`result`) through the +_Callable_ and _Addressable_ interface contracts, and writes the resolved +addresses to the _Channel_ in the `channel` reference. _Subscriptions_ do not +need to specify both a transformation and a storage destination, but at least +one must be provided. All event delivery linkage from a **Subscription** is 1:1 – only a single -`from`, `call`, and `result` may be provided. +`channel`, `subscriber`, and `result` may be provided. For more details, see [Kind: Subscription](spec.md#kind-subscription). ## Channel -**Channel** provides an at least once event delivery mechanism which can fan -out received events to multiple destinations via _Subscriptions_. A _Channel_ -has a single inbound _Sinkable_ interface which may accept events from multiple -_Subscriptions_ or even direct delivery from external systems. Different -_Channels_ may implement different degrees of persistence. Event delivery order -is dependent on the backing implementation of the _Channel_ provided by the +**Channel** provides an event delivery mechanism which can fan out received +events to multiple destinations via _Subscriptions_. A _Channel_ has a single +inbound _Addressable_ interface which may accept events delivered directly or +forwarded from multiple _Subscriptions_. Different _Channels_ may implement +different degrees of persistence. Event delivery order is dependent on the +backing implementation of the _Channel_ provided by the _ClusterChannelProvisioner_. Event selection on a _Channel_ is 1:N – a single _Channel_ may fan out to diff --git a/docs/spec/spec.md b/docs/spec/spec.md index d0f4a328bc2..5ff623fc712 100644 --- a/docs/spec/spec.md +++ b/docs/spec/spec.md @@ -24,11 +24,11 @@ its subscribers._ #### Spec -| Field | Type | Description | Constraints | -| ------------- | ---------------------------------- | -------------------------------------------------------------------------- | -------------------------------------- | -| provisioner\* | ProvisionerReference | The name of the provisioner to create the resources that back the Channel. | Immutable. | -| arguments | runtime.RawExtension (JSON object) | Arguments to be passed to the provisioner. | | -| subscribers | ChannelSubscriberSpec[] | Information about subscriptions used to implement message forwarding. | Filled out by Subscription Controller. | +| Field | Type | Description | Constraints | +| ------------------------ | ---------------------------------- | -------------------------------------------------------------------------- | -------------------------------------- | +| provisioner\* | ObjectReference | The name of the provisioner to create the resources that back the Channel. | Immutable. | +| arguments | runtime.RawExtension (JSON object) | Arguments to be passed to the provisioner. | | +| subscribable.subscribers | ChannelSubscriberSpec[] | Information about subscriptions used to implement message forwarding. | Filled out by Subscription Controller. | \*: Required @@ -41,10 +41,10 @@ its subscribers._ #### Status -| Field | Type | Description | Constraints | -| ---------- | ---------- | --------------------------------------------------------------------------------------------------------------------------- | ----------- | -| sinkable | Sinkable | Address to the endpoint as top-level domain that will distribute traffic over the provided targets from inside the cluster. | | -| conditions | Conditions | Channel conditions. | | +| Field | Type | Description | Constraints | +| ---------- | ----------- | -------------------------------------------------------------------------------------------- | ----------- | +| address | Addressable | Address of the endpoint which meets the [_Addressable_ contract](interfaces.md#addressable). | | +| conditions | Conditions | Channel conditions. | | ##### Conditions @@ -70,21 +70,21 @@ its subscribers._ ### group: eventing.knative.dev/v1alpha1 -_Describes a linkage between a Channel and a Targetable and/or Sinkable._ +_Describes a linkage between a Channel and a Callable and/or Addressable channel._ ### Object Schema #### Spec -| Field | Type | Description | Constraints | -| ------------------ | -------------- | ---------------------------------------------------------------------------- | ------------------ | -| from\* | ObjectRef | The originating _Subscribable_ for the link. | Must be a Channel. | -| call1 | EndpointSpec | Optional processing on the event. The result of call will be sent to result. | | -| result1 | ResultStrategy | The continuation for the link. | | +| Field | Type | Description | Constraints | +| ---------------------- | -------------- | --------------------------------------------------------------------------------- | ------------------ | +| channel\* | ObjectRef | The originating _Subscribable_ for the link. | Must be a Channel. | +| subscriber1 | SubscriberSpec | Optional processing on the event. The result of subscriber will be sent to reply. | | +| reply1 | ReplyStrategy | The continuation for the link. | | \*: Required -1: At Least One(call, result) +1: At Least One(subscriber, reply) #### Metadata @@ -97,7 +97,7 @@ _Describes a linkage between a Channel and a Targetable and/or Sinkable._ - **Ready.** - **FromReady.** -- **Resolved.** True if `from`, `call`, and `result` all resolve into valid object references which implement the appropriate spec. +- **Resolved.** True if `channel`, `subscriber`, and `reply` all resolve into valid object references which implement the appropriate spec. #### Events @@ -106,11 +106,11 @@ _Describes a linkage between a Channel and a Targetable and/or Sinkable._ ### Life Cycle -| Action | Reactions | Constraints | -| ------ | ------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| Create | The subscription controller adds the resolved URIs of `call` and `result` to the `subscribers` field in the `from` _Subscribable_ resource. | | -| Update | | | -| Delete | | | +| Action | Reactions | Constraints | +| ------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | +| Create | The subscription controller adds the resolved URIs of `subscriber` and `reply` to the `subscribers` field in the `channel` _Subscribable_ resource. | | +| Update | | | +| Delete | | | --- @@ -125,9 +125,9 @@ or a Channel system that receives and delivers events._ #### Spec -| Field | Type | Description | Constraints | -| ---------- | ---------------------------------- | ------------------------------------------------------------------------------------------------- | ---------------- | -| parameters | runtime.RawExtension (JSON object) | Description of the arguments able to be passed by the provisioned resource (not enforced in 0.1). | JSON Schema | +| Field | Type | Description | Constraints | +| ---------- | ---------------------------------- | ------------------------------------------------------------------------------------------------- | ----------- | +| parameters | runtime.RawExtension (JSON object) | Description of the arguments able to be passed by the provisioned resource (not enforced in 0.1). | JSON Schema | \*: Required @@ -150,34 +150,27 @@ or a Channel system that receives and delivers events._ ## Shared Object Schema -### ProvisionerReference +### SubscriberSpec -| Field | Type | Description | Constraints | -| ----- | --------------- | ----------- | ----------- | -| ref\* | ObjectReference | | | +| Field | Type | Description | Constraints | +| ------------------- | --------------- | ----------- | ------------------------ | +| ref1 | ObjectReference | | Must adhere to Callable. | +| dnsName1 | String | | | -\*: Required - -### EndpointSpec - -| Field | Type | Description | Constraints | -| --------------------- | --------------- | ----------- | -------------------------- | -| targetRef1 | ObjectReference | | Must adhere to Targetable. | -| dnsName1 | String | | | - -1: One of (targetRef, dnsName), Required. +1: One of (ref, dnsName), Required. ### ChannelSubscriberSpec -| Field | Type | Description | Constraints | -| ----------- | ------ | -------------------------------------------- | -------------- | -| callableURI | String | The URI name of the endpoint for the call. | Must be a URL. | -| sinkableURI | String | The URI name of the endpoint for the result. | Must be a URL. | +| Field | Type | Description | Constraints | +| ------------- | --------------- | -------------------------------------------------------------- | -------------- | +| ref | ObjectReference | The Subscription this ChannelSubscriberSpec was resolved from. | | +| subscriberURI | String | The URI name of the endpoint for the subscriber. | Must be a URL. | +| replyURI | String | The URI name of the endpoint for the reply. | Must be a URL. | -### ResultStrategy +### ReplyStrategy -| Field | Type | Description | Constraints | -| -------- | --------- | -------------------------------------- | ------------------ | -| target\* | ObjectRef | The continuation Channel for the link. | Must be a Channel. | +| Field | Type | Description | Constraints | +| --------- | --------- | -------------------------------------- | ------------------ | +| channel\* | ObjectRef | The continuation Channel for the link. | Must be a Channel. | \*: Required diff --git a/hack/README.md b/hack/README.md index a1eb457e45d..eff43a7c50f 100644 --- a/hack/README.md +++ b/hack/README.md @@ -3,7 +3,7 @@ This directory contains several scripts useful in the development process of Knative Eventing. * `boilerplate/add-boilerplate.sh` Adds license boilerplate to *txt* or *go* files in a directory, recursively. -* `release.sh` Builds (and optionally tags and publishes) a new release of Knative Eventing. -* `update-codegen.sh` Update auto-generated client libraries. -* `update-deps.sh` Update Go dependencies. -* `verify-codegen.sh` Verify that auto-generated client libraries are up-to-date. +* `release.sh` Creates a new [release](release.md) of Knative Eventing. +* `update-codegen.sh` Updates auto-generated client libraries. +* `update-deps.sh` Updates Go dependencies. +* `verify-codegen.sh` Verifies that auto-generated client libraries are up-to-date. diff --git a/hack/release.md b/hack/release.md new file mode 100644 index 00000000000..68417894428 --- /dev/null +++ b/hack/release.md @@ -0,0 +1,72 @@ +# Creating a new Knative Eventing release + +The `release.sh` script automates the creation of Knative Eventing releases, +either nightly or versioned ones. + +By default, the script creates a nightly release but does not publish anywhere. + +## Common flags for cutting releases + +The following flags affect the behavior of the script, no matter the type of +the release. + +* `--skip-tests` Do not run tests before building the release. Otherwise, +build, unit and end-to-end tests are run and they all must pass for the +release to be built. +* `--tag-release`, `--notag-release` Tag (or not) the generated images +with either `vYYYYMMDD-` (for nightly releases) or +`vX.Y.Z` for versioned releases. These are docker tags. *For versioned +releases, a tag is always added.* +* `--publish`, `--nopublish` Whether the generated images should be published +to a GCR, and the generated manifests written to a GCS bucket or not. If yes, +the destination GCR is defined by the environment variable +`$EVENTING_RELEASE_GCR` (defaults to `gcr.io/knative-releases`) and +the destination GCS bucket is defined by the environment variable +`$EVENTING_RELEASE_GCS` (defaults to `knative-releases/eventing`). If no, the +images will be pushed to the `ko.local` registry, and the manifests written to +the local disk only (in the repository root directory). + +## Creating nightly releases + +Nightly releases are built against the current git tree. The behavior of the +script is defined by the common flags. You must have write access to the GCR +and GCS bucket the release will be pushed to, unless `--nopublish` is used. + +Examples: + +```bash +# Create and publish a nightly, tagged release. +./hack/release.sh --publish --tag-release + +# Create release, but don't test, publish or tag it. +./hack/release.sh --skip-tests --nopublish --notag-release +``` + +## Creating versioned releases + +*Note: only Knative admins can create versioned releases.* + +To specify a versioned release to be cut, you must use the `--version` flag. +Versioned releases are usually built against a branch in the Knative Eventing +repository, specified by the `--branch` flag. + +* `--version` Defines the version of the release, and must be in the form +`X.Y.Z`, where X, Y and Z are numbers. +* `--branch` Defines the branch in Knative Eventing repository from which the +release will be built. If not passed, the `master` branch at HEAD will be used. +This branch must be created before the script is executed, and must be in the +form `release-X.Y`, where X and Y must match the numbers used in the version +passed in the `--version` flag. This flag has no effect unless `--version` is +also passed. +* `--release-notes` Points to a markdown file containing a description of the +release. This is optional but highly recommended. It has no effect unless +`--version` is also passed. + +If this is the first time you're cutting a versioned release, you'll be prompted +for your GitHub username, password, and possibly 2-factor authentication +challenge before the release is published. + +The release will be published in the *Releases* page of the Knative Eventing +repository, with the title *Knative Eventing release vX.Y.Z* and the given +release notes. It will also be tagged *vX.Y.Z* (both on GitHub and as a git +annotated tag). diff --git a/hack/release.sh b/hack/release.sh index 7c381279dae..5885e1687a8 100755 --- a/hack/release.sh +++ b/hack/release.sh @@ -23,26 +23,26 @@ readonly EVENTING_RELEASE_GCS readonly EVENTING_RELEASE_GCR # Yaml files to generate, and the source config dir for them. +declare -A COMPONENTS +COMPONENTS=( + ["eventing.yaml"]="config" + ["in-memory-channel.yaml"]="config/provisioners/in-memory-channel" + ["kafka-channel.yaml"]="config/provisioners/kafka" +) +readonly COMPONENTS + declare -A RELEASES -RELEASES["release.yaml"]="config" -RELEASES["release-bus-stub.yaml"]="config/buses/stub" -RELEASES["release-bus-gcppubsub.yaml"]="config/buses/gcppubsub" -RELEASES["release-bus-kafka.yaml"]="config/buses/kafka" -RELEASES["release-source-k8sevents.yaml"]="pkg/sources/k8sevents" -RELEASES["release-source-gcppubsub.yaml"]="pkg/sources/gcppubsub" -RELEASES["release-source-github.yaml"]="pkg/sources/github" +RELEASES=( + ["release.yaml"]="eventing.yaml in-memory-channel.yaml" +) readonly RELEASES -# Yaml files that will be also released as ClusterBuses from Buses -readonly CLUSTERBUS_YAMLS=( - release-bus-stub.yaml - release-bus-gcppubsub.yaml - release-bus-kafka.yaml -) +# Set the repository +export KO_DOCKER_REPO=${EVENTING_RELEASE_GCR} # Script entry point. -parse_flags $@ +initialize $@ set -o errexit set -o pipefail @@ -51,33 +51,34 @@ run_validation_tests ./test/presubmit-tests.sh banner "Building the release" -# Set the repository -export KO_DOCKER_REPO=${EVENTING_RELEASE_GCR} - +echo "- Destination GCR: ${KO_DOCKER_REPO}" if (( PUBLISH_RELEASE )); then - echo "- Destination GCR: ${EVENTING_RELEASE_GCR}" echo "- Destination GCS: ${EVENTING_RELEASE_GCS}" fi -# Build the release +# Build the components all_yamls=() -for yaml in "${!RELEASES[@]}"; do - config="${RELEASES[${yaml}]}" +for yaml in "${!COMPONENTS[@]}"; do + config="${COMPONENTS[${yaml}]}" echo "Building Knative Eventing - ${config}" ko resolve ${KO_FLAGS} -f ${config}/ > ${yaml} - tag_images_in_yaml ${yaml} ${EVENTING_RELEASE_GCR} ${TAG} + tag_images_in_yaml ${yaml} ${KO_DOCKER_REPO} ${TAG} all_yamls+=(${yaml}) done -for yaml in ${CLUSTERBUS_YAMLS[@]}; do - clusterbus_yaml=${yaml/-bus-/-clusterbus-} - config="${RELEASES[${yaml}]}" - echo "Building Knative Eventing - ${config} (${clusterbus_yaml})" - sed -e 's/^kind: Bus$/kind: ClusterBus/g' ${yaml} > ${clusterbus_yaml} - tag_images_in_yaml ${clusterbus_yaml} ${EVENTING_RELEASE_GCR} ${TAG} - all_yamls+=(${clusterbus_yaml}) +# Assemble the release +for yaml in "${!RELEASES[@]}"; do + echo "Assembling Knative Eventing - ${yaml}" + echo "" > ${yaml} + for component in ${RELEASES[${yaml}]}; do + echo "---" >> ${yaml} + echo "# ${component}" >> ${yaml} + cat ${component} >> ${yaml} + done + tag_images_in_yaml ${yaml} ${KO_DOCKER_REPO} ${TAG} + all_yamls+=(${yaml}) done echo "New release built successfully" @@ -93,4 +94,6 @@ for yaml in ${all_yamls[@]}; do publish_yaml ${yaml} ${EVENTING_RELEASE_GCS} ${TAG} done +branch_release "Knative Eventing" "${all_yamls[*]}" + echo "New release published successfully" diff --git a/hack/update-codegen.sh b/hack/update-codegen.sh index 9301dc91d9d..b651c1fc19a 100755 --- a/hack/update-codegen.sh +++ b/hack/update-codegen.sh @@ -28,7 +28,13 @@ CODEGEN_PKG=${CODEGEN_PKG:-$(cd ${REPO_ROOT_DIR}; ls -d -1 ./vendor/k8s.io/code- # instead of the $GOPATH directly. For normal projects this can be dropped. ${CODEGEN_PKG}/generate-groups.sh "deepcopy,client,informer,lister" \ github.com/knative/eventing/pkg/client github.com/knative/eventing/pkg/apis \ - "channels:v1alpha1 feeds:v1alpha1 flows:v1alpha1 eventing:v1alpha1" \ + "eventing:v1alpha1" \ + --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt + +# Only deepcopy the Duck types, as they are not real resources. +${CODEGEN_PKG}/generate-groups.sh "deepcopy" \ + github.com/knative/eventing/pkg/client github.com/knative/eventing/pkg/apis \ + "duck:v1alpha1" \ --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt # Make sure our dependencies are up-to-date diff --git a/hack/update-deps.sh b/hack/update-deps.sh index f95efc0dbd1..5d7bd82fc59 100755 --- a/hack/update-deps.sh +++ b/hack/update-deps.sh @@ -28,7 +28,5 @@ dep ensure rm -rf $(find vendor/ -name 'BUILD') rm -rf $(find vendor/ -name 'BUILD.bazel') -# Keep the only dir in knative/test-infra we're interested in -find vendor/github.com/knative/test-infra -mindepth 1 -maxdepth 1 ! -name scripts -exec rm -fr {} \; - -update_licenses third_party/VENDOR-LICENSE "./cmd/*" +update_licenses third_party/VENDOR-LICENSE \ + $(find . -name "*.go" | grep -v vendor | xargs grep "package main" | cut -d: -f1 | xargs -n1 dirname | uniq) diff --git a/openshift/admission-webhooks.yaml b/openshift/admission-webhooks.yaml new file mode 100644 index 00000000000..7a89bdcf5d1 --- /dev/null +++ b/openshift/admission-webhooks.yaml @@ -0,0 +1,37 @@ +--- +- hosts: all + become: yes + become_user: root + tasks: + - name: Backup master-config.yaml to master-config.yaml.prepatch + copy: + src: /etc/origin/master/master-config.yaml + dest: /etc/origin/master/master-config.yaml.prepatch + remote_src: yes + backup: yes + - name: Set master_patch variable + set_fact: + master_patch: | + admissionConfig: + pluginConfig: + MutatingAdmissionWebhook: + configuration: + apiVersion: apiserver.config.k8s.io/v1alpha1 + kubeConfigFile: /dev/null + kind: WebhookAdmission + ValidatingAdmissionWebhook: + configuration: + apiVersion: apiserver.config.k8s.io/v1alpha1 + kubeConfigFile: /dev/null + kind: WebhookAdmission + - name: Apply patch for admission webhooks + shell: oc ex config patch /etc/origin/master/master-config.yaml.prepatch -p "{{ master_patch }}" > /etc/origin/master/master-config.yaml + - name: Restart API server and constollers + shell: /usr/local/bin/master-restart api && /usr/local/bin/master-restart controllers + - name: Wait for API server to be available + command: oc login -u system:admin + register: login_res + until: login_res.rc == 0 + ignore_errors: yes + retries: 30 + delay: 1 diff --git a/openshift/ci-operator/knative-images/controller/Dockerfile b/openshift/ci-operator/knative-images/controller/Dockerfile new file mode 100644 index 00000000000..65920c14e73 --- /dev/null +++ b/openshift/ci-operator/knative-images/controller/Dockerfile @@ -0,0 +1,5 @@ +FROM gcr.io/distroless/base:latest +LABEL maintainer="mgencur@redhat.com" + +ADD controller /usr/bin/controller +ENTRYPOINT ["/usr/bin/controller"] diff --git a/openshift/ci-operator/knative-images/fanoutsidecar/Dockerfile b/openshift/ci-operator/knative-images/fanoutsidecar/Dockerfile new file mode 100644 index 00000000000..547cf14dbab --- /dev/null +++ b/openshift/ci-operator/knative-images/fanoutsidecar/Dockerfile @@ -0,0 +1,5 @@ +FROM gcr.io/distroless/base:latest +LABEL maintainer="mgencur@redhat.com" + +ADD fanoutsidecar /usr/bin/fanoutsidecar +ENTRYPOINT ["/usr/bin/fanoutsidecar"] diff --git a/openshift/ci-operator/knative-images/in-memory-channel-controller/Dockerfile b/openshift/ci-operator/knative-images/in-memory-channel-controller/Dockerfile new file mode 100644 index 00000000000..0ccb723cc9e --- /dev/null +++ b/openshift/ci-operator/knative-images/in-memory-channel-controller/Dockerfile @@ -0,0 +1,5 @@ +FROM gcr.io/distroless/base:latest +LABEL maintainer="mgencur@redhat.com" + +ADD in-memory-channel-controller /usr/bin/in-memory-channel-controller +ENTRYPOINT ["/usr/bin/in-memory-channel-controller"] diff --git a/openshift/ci-operator/knative-images/kafka/Dockerfile b/openshift/ci-operator/knative-images/kafka/Dockerfile new file mode 100644 index 00000000000..01fc7b7cc95 --- /dev/null +++ b/openshift/ci-operator/knative-images/kafka/Dockerfile @@ -0,0 +1,5 @@ +FROM gcr.io/distroless/base:latest +LABEL maintainer="mgencur@redhat.com" + +ADD kafka /usr/bin/kafka +ENTRYPOINT ["/usr/bin/kafka"] diff --git a/openshift/ci-operator/knative-images/webhook/Dockerfile b/openshift/ci-operator/knative-images/webhook/Dockerfile new file mode 100644 index 00000000000..5d646708945 --- /dev/null +++ b/openshift/ci-operator/knative-images/webhook/Dockerfile @@ -0,0 +1,5 @@ +FROM gcr.io/distroless/base:latest +LABEL maintainer="mgencur@redhat.com" + +ADD webhook /usr/bin/webhook +ENTRYPOINT ["/usr/bin/webhook"] diff --git a/openshift/ci-operator/knative-test-images/k8sevents/Dockerfile b/openshift/ci-operator/knative-test-images/k8sevents/Dockerfile new file mode 100644 index 00000000000..2de7aa620f8 --- /dev/null +++ b/openshift/ci-operator/knative-test-images/k8sevents/Dockerfile @@ -0,0 +1,5 @@ +FROM gcr.io/distroless/base:latest +LABEL maintainer="mgencur@redhat.com" + +ADD k8sevents /usr/bin/k8sevents +ENTRYPOINT ["/usr/bin/k8sevents"] diff --git a/openshift/e2e-tests-openshift.sh b/openshift/e2e-tests-openshift.sh new file mode 100644 index 00000000000..97ee7eb5efa --- /dev/null +++ b/openshift/e2e-tests-openshift.sh @@ -0,0 +1,277 @@ +#!/bin/sh + +source $(dirname $0)/../vendor/github.com/knative/test-infra/scripts/e2e-tests.sh + +set -x + +readonly K8S_CLUSTER_OVERRIDE=$(oc config current-context | awk -F'/' '{print $2}') +readonly API_SERVER=$(oc config view --minify | grep server | awk -F'//' '{print $2}' | awk -F':' '{print $1}') +readonly INTERNAL_REGISTRY="docker-registry.default.svc:5000" +readonly USER=$KUBE_SSH_USER #satisfy e2e_flags.go#initializeFlags() +readonly OPENSHIFT_REGISTRY=registry.svc.ci.openshift.org +readonly KNATIVE_EVENTING_SOURCES_RELEASE=https://knative-releases.storage.googleapis.com/eventing-sources/latest/release.yaml +readonly EVENTING_NAMESPACE=knative-eventing +readonly TEST_NAMESPACE=e2etest +readonly TEST_FUNCTION_NAMESPACE=e2etestfn3 + +env + +function enable_admission_webhooks(){ + header "Enabling admission webhooks" + add_current_user_to_etc_passwd + disable_strict_host_checking + echo "API_SERVER=$API_SERVER" + echo "KUBE_SSH_USER=$KUBE_SSH_USER" + chmod 600 ~/.ssh/google_compute_engine + echo "$API_SERVER ansible_ssh_private_key_file=~/.ssh/google_compute_engine" > inventory.ini + ansible-playbook ${REPO_ROOT_DIR}/openshift/admission-webhooks.yaml -i inventory.ini -u $KUBE_SSH_USER + rm inventory.ini +} + +function add_current_user_to_etc_passwd(){ + if ! whoami &>/dev/null; then + echo "${USER:-default}:x:$(id -u):$(id -g):Default User:$HOME:/sbin/nologin" >> /etc/passwd + fi + cat /etc/passwd +} + +function disable_strict_host_checking(){ + cat >> ~/.ssh/config <>> Setting SSL_CERT_FILE for Knative Serving Controller" + oc set env -n knative-serving deployment/controller SSL_CERT_FILE=/var/run/secrets/kubernetes.io/serviceaccount/service-ca.crt + + echo ">> Patching knative-ingressgateway" + oc patch hpa -n istio-system knative-ingressgateway --patch '{"spec": {"maxReplicas": 1}}' + + wait_until_pods_running knative-build || return 1 + wait_until_pods_running knative-serving || return 1 + wait_until_service_has_external_ip istio-system knative-ingressgateway || fail_test "Ingress has no external IP" + header "Knative Installed successfully" +} + +function install_knative_eventing_sources(){ + header "Installing Knative Eventing Sources" + oc apply -f ${KNATIVE_EVENTING_SOURCES_RELEASE} + wait_until_pods_running knative-sources || return 1 +} + +function install_knative_eventing(){ + header "Installing Knative Eventing" + + # Create knative-eventing namespace, needed for imagestreams + oc create namespace $EVENTING_NAMESPACE + + # Grant the necessary privileges to the service accounts Knative will use: + oc annotate clusterrolebinding.rbac cluster-admin 'rbac.authorization.kubernetes.io/autoupdate=false' --overwrite + oc annotate clusterrolebinding.rbac cluster-admins 'rbac.authorization.kubernetes.io/autoupdate=false' --overwrite + + oc adm policy add-scc-to-user anyuid -z eventing-controller -n $EVENTING_NAMESPACE + oc adm policy add-scc-to-user anyuid -z in-memory-channel-dispatcher -n $EVENTING_NAMESPACE + oc adm policy add-scc-to-user anyuid -z in-memory-channel-controller -n $EVENTING_NAMESPACE + + resolve_resources config/ $EVENTING_NAMESPACE eventing-resolved.yaml + oc apply -f eventing-resolved.yaml + + oc adm policy add-cluster-role-to-user cluster-admin -z eventing-controller -n $EVENTING_NAMESPACE + oc adm policy add-cluster-role-to-user cluster-admin -z in-memory-channel-dispatcher -n $EVENTING_NAMESPACE + oc adm policy add-cluster-role-to-user cluster-admin -z in-memory-channel-controller -n $EVENTING_NAMESPACE + oc adm policy add-cluster-role-to-user cluster-admin -z default -n knative-sources + + echo ">>> Setting SSL_CERT_FILE for Knative Eventing Controller" + oc set env -n $EVENTING_NAMESPACE deployment/eventing-controller SSL_CERT_FILE=/var/run/secrets/kubernetes.io/serviceaccount/service-ca.crt + + wait_until_pods_running $EVENTING_NAMESPACE +} + +function install_in_memory_channel_provisioner(){ + header "Standing up In-Memory ClusterChannelProvisioner" + resolve_resources config/provisioners/in-memory-channel/ $EVENTING_NAMESPACE channel-resolved.yaml + oc apply -f channel-resolved.yaml +} + +function create_test_resources() { + echo ">> Creating imagestream tags for all test images" + tag_test_images test/test_images + + echo ">> Ensuring pods in test namespaces can access test images" + oc policy add-role-to-group system:image-puller system:serviceaccounts:$TEST_NAMESPACE --namespace=$EVENTING_NAMESPACE + oc policy add-role-to-group system:image-puller system:serviceaccounts:$TEST_FUNCTION_NAMESPACE --namespace=$EVENTING_NAMESPACE + + #Grant additional privileges + oc adm policy add-scc-to-user anyuid -z default -n $TEST_FUNCTION_NAMESPACE + oc adm policy add-scc-to-user privileged -z default -n $TEST_FUNCTION_NAMESPACE + oc adm policy add-scc-to-user anyuid -z e2e-receive-adapter -n $TEST_FUNCTION_NAMESPACE + oc adm policy add-scc-to-user privileged -z e2e-receive-adapter -n $TEST_FUNCTION_NAMESPACE +} + +function resolve_resources(){ + local dir=$1 + local resolved_file_name=$3 + > $resolved_file_name + for yaml in $(find $dir -maxdepth 1 -name "*.yaml"); do + echo "---" >> $resolved_file_name + #first prefix all test images with "test-", then replace all image names with proper repository + sed -e 's/\(.* image: \)\(github.com\)\(.*\/\)\(test\/\)\(.*\)/\1\2 \3\4test-\5/' $yaml | \ + sed -e 's%github.com/knative/eventing/pkg/controller/eventing/inmemory/controller%'"$INTERNAL_REGISTRY"'\/'"$EVENTING_NAMESPACE"'\/eventing-in-memory-channel-controller%' | \ + sed -e 's/\(.* image: \)\(github.com\)\(.*\/\)\(.*\)/\1 '"$INTERNAL_REGISTRY"'\/'"$EVENTING_NAMESPACE"'\/eventing-\4/' >> $resolved_file_name + done + + echo ">> Creating imagestream tags for images referenced in yaml files" + IMAGE_NAMES=$(cat $resolved_file_name | grep -i "image:" | grep "$INTERNAL_REGISTRY" | awk '{print $2}' | awk -F '/' '{print $3}') + for name in $IMAGE_NAMES; do + tag_built_image ${name} ${name} + done +} + +function enable_docker_schema2(){ + oc set env -n default dc/docker-registry REGISTRY_MIDDLEWARE_REPOSITORY_OPENSHIFT_ACCEPTSCHEMA2=true +} + +function create_test_namespace(){ + oc new-project $TEST_NAMESPACE + oc adm policy add-scc-to-user privileged -z default -n $TEST_NAMESPACE + oc new-project $TEST_FUNCTION_NAMESPACE + oc adm policy add-scc-to-user privileged -z default -n $TEST_FUNCTION_NAMESPACE +} + +function run_e2e_tests(){ + header "Running tests" + options="" + (( EMIT_METRICS )) && options="-emitmetrics" + report_go_test \ + -v -tags=e2e -count=1 -timeout=20m \ + ./test/e2e \ + --tag latest \ + --kubeconfig $KUBECONFIG \ + --dockerrepo ${INTERNAL_REGISTRY}/${EVENTING_NAMESPACE} \ + ${options} || return 1 +} + +function delete_istio_openshift(){ + echo ">> Bringing down Istio" + oc delete --ignore-not-found=true -f ${KNATIVE_ISTIO_CRD_YAML} + oc delete --ignore-not-found=true -f ${KNATIVE_ISTIO_YAML} +} + +function delete_serving_openshift() { + echo ">> Bringing down Serving" + oc delete --ignore-not-found=true -f ${KNATIVE_SERVING_RELEASE} +} + +function delete_test_namespace(){ + echo ">> Deleting test namespace $TEST_NAMESPACE" + oc adm policy remove-scc-from-user privileged -z default -n $TEST_NAMESPACE + oc delete project $TEST_NAMESPACE + echo ">> Deleting test namespace $TEST_FUNCTION_NAMESPACE" + oc adm policy remove-scc-from-user privileged -z default -n $TEST_FUNCTION_NAMESPACE + oc delete project $TEST_FUNCTION_NAMESPACE +} + +function delete_knative_eventing_sources(){ + header "Brinding down Knative Eventing Sources" + oc delete --ignore-not-found=true -f ${KNATIVE_EVENTING_SOURCES_RELEASE} +} + +function delete_knative_eventing(){ + header "Bringing down Eventing" + oc delete --ignore-not-found=true -f eventing-resolved.yaml +} + +function delete_in_memory_channel_provisioner(){ + header "Bringing down In-Memory ClusterChannelProvisioner" + oc delete --ignore-not-found=true -f channel-resolved.yaml +} + +function teardown() { + delete_test_namespace + delete_in_memory_channel_provisioner + delete_knative_eventing + delete_knative_eventing_sources + delete_serving_openshift + delete_istio_openshift +} + +function tag_test_images() { + local dir=$1 + image_dirs="$(find ${dir} -mindepth 1 -maxdepth 1 -type d)" + + for image_dir in ${image_dirs}; do + name=$(basename ${image_dir}) + tag_built_image eventing-test-${name} ${name} + done +} + +function tag_built_image() { + local remote_name=$1 + local local_name=$2 + oc tag -n ${EVENTING_NAMESPACE} ${OPENSHIFT_REGISTRY}/${OPENSHIFT_BUILD_NAMESPACE}/stable:${remote_name} ${local_name}:latest +} + +enable_admission_webhooks + +teardown + +install_istio + +enable_docker_schema2 + +install_knative_serving + +install_knative_eventing_sources + +install_knative_eventing + +install_in_memory_channel_provisioner + +create_test_namespace + +create_test_resources + +run_e2e_tests || fail_test + +success \ No newline at end of file diff --git a/pkg/apis/channels/logkey/constants.go b/pkg/apis/channels/logkey/constants.go deleted file mode 100644 index f0071154a8e..00000000000 --- a/pkg/apis/channels/logkey/constants.go +++ /dev/null @@ -1,30 +0,0 @@ -/* -Copyright 2018 The Knative 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 logkey - -const ( - kNative = "knative.dev/" - - // ClusterBus is the key used for cluster scoped bus name in structured logs - ClusterBus = kNative + "clusterbus" - - // Bus is the key used for bus name in structured logs - Bus = kNative + "bus" - - // Channel is the key used for channel name in structured logs - Channel = kNative + "channel" -) diff --git a/pkg/apis/channels/register.go b/pkg/apis/channels/register.go deleted file mode 100644 index 44b041cde02..00000000000 --- a/pkg/apis/channels/register.go +++ /dev/null @@ -1,21 +0,0 @@ -/* -Copyright 2018 The Knative 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 channels - -const ( - GroupName = "channels.knative.dev" -) diff --git a/pkg/apis/channels/v1alpha1/bus_defaults.go b/pkg/apis/channels/v1alpha1/bus_defaults.go deleted file mode 100644 index d28033a3cc8..00000000000 --- a/pkg/apis/channels/v1alpha1/bus_defaults.go +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -// TODO(n3wscott): This is staging work, the plan is another pass to bring up -// the test coverage, then remove unused after each type is stubbed. -// This is all prep for new serving style webhook integration. - -func (b *Bus) SetDefaults() { - b.Spec.SetDefaults() -} - -func (bs *BusSpec) SetDefaults() { - bs.Parameters.SetDefaults() -} - -func (bp *BusParameters) SetDefaults() { - // TODO anything? -} diff --git a/pkg/apis/channels/v1alpha1/bus_types.go b/pkg/apis/channels/v1alpha1/bus_types.go deleted file mode 100644 index 85e80600588..00000000000 --- a/pkg/apis/channels/v1alpha1/bus_types.go +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright 2018 The Knative Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package v1alpha1 - -import ( - "encoding/json" - - "github.com/knative/pkg/apis" - "github.com/knative/pkg/webhook" - kapi "k8s.io/api/core/v1" - meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" -) - -// +genclient -// +genclient:noStatus -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +k8s:defaulter-gen=true - -// Bus represents how channels and subscriptions should be managed and -// corresponds to the buses.channels.knative.dev CRD. Buses will frequently, but -// not always, be backed by an event broker. -type Bus struct { - meta_v1.TypeMeta `json:",inline"` - meta_v1.ObjectMeta `json:"metadata"` - Spec BusSpec `json:"spec"` - Status BusStatus `json:"status,omitempty"` -} - -// Check that Bus can be validated, can be defaulted, and has immutable fields. -var _ apis.Validatable = (*Bus)(nil) -var _ apis.Defaultable = (*Bus)(nil) -var _ apis.Immutable = (*Bus)(nil) -var _ runtime.Object = (*Bus)(nil) -var _ webhook.GenericCRD = (*Bus)(nil) - -// BusSpec specifies the Bus' parameters for Channels and Subscriptions, how the -// provisioner and dispatcher for a bus should be run, and which volumes should -// be mounted into them. -type BusSpec struct { - // TODO: Generation does not work correctly with CRD. They are scrubbed - // by the APIserver (https://github.com/kubernetes/kubernetes/issues/58778) - // So, we add Generation here. Once that gets fixed, remove this and use - // ObjectMeta.Generation instead. - // +optional - Generation int64 `json:"generation,omitempty"` - - // Parameters defines the parameters that must be passed by this Bus' - // Channels and their Subscriptions. Channels and Subscriptions fulfill - // these parameters with Arguments. - Parameters *BusParameters `json:"parameters,omitempty"` - - // Provisioner defines how the provisioner container for this bus should be - // run. Provisioners are responsible for provisioning the underlying - // infrastructure for Channels and Subscriptions. The exact work done by the - // provisioner varies by Bus; one example of work done by a provisioner - // could be creating a messaging topic that backs a channel. - Provisioner *kapi.Container `json:"provisioner,omitempty"` - - // Dispatcher defines how the dispatcher container for this bus should be - // run. Dispatchers are responsible for performing two types of event - // dispatch: dispatching incoming events to the Bus' Channels and - // dispatching events in the Channel to the Channel's Subscriptions. - Dispatcher kapi.Container `json:"dispatcher"` - - // Volumes to be mounted inside the provisioner or dispatcher containers - Volumes *[]kapi.Volume `json:"volumes,omitempty"` -} - -// BusParameters represents the arguments that must be passed by Channels and -// Subscriptions. -type BusParameters struct { - // Channel configuration params for channels on the bus - Channel *[]Parameter `json:"channel,omitempty"` - - // Subscription configuration params for subscriptions on the bus - Subscription *[]Parameter `json:"subscription,omitempty"` -} - -type BusConditionType string - -const ( - // Ready is set when all other conditions are met and the bus is ready to accept traffic. - BusReady BusConditionType = "Ready" - - // Serviceable means the service addressing the bus exists. - BusServiceable BusConditionType = "Serviceable" - - // Provisioning means the deployment for the bus provisioner exists. - BusProvisioning BusConditionType = "Provisioning" - - // Dispatching means the deployment for the bus dispatcher exists. - BusDispatching = "Dispatching" -) - -// BusCondition describes the state of a bus at a point in time. -type BusCondition struct { - // Type of bus condition. - Type BusConditionType `json:"type"` - // Status of the condition, one of True, False, Unknown. - Status kapi.ConditionStatus `json:"status"` - // The last time this condition was updated. - LastUpdateTime meta_v1.Time `json:"lastUpdateTime,omitempty"` - // Last time the condition transitioned from one status to another. - LastTransitionTime meta_v1.Time `json:"lastTransitionTime,omitempty"` - // The reason for the condition's last transition. - Reason string `json:"reason,omitempty"` - // A human readable message indicating details about the transition. - Message string `json:"message,omitempty"` -} - -// BusStatus (computed) for a bus -type BusStatus struct { - // A reference to the k8s Service fronting this bus, if successfully synced. - Service *kapi.LocalObjectReference `json:"service,omitempty"` - - // Represents the latest available observations of a bus's current state. - // +patchMergeKey=type - // +patchStrategy=merge - Conditions []BusCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` -} - -func (b *Bus) BacksChannel(channel *Channel) bool { - return b.Namespace == channel.Namespace && b.Name == channel.Spec.Bus -} - -func (b *Bus) GetSpec() *BusSpec { - return &b.Spec -} - -func (b *Bus) GetStatus() *BusStatus { - return &b.Status -} - -func (b *Bus) GetSpecJSON() ([]byte, error) { - return json.Marshal(b.Spec) -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// BusList returned in list operations -type BusList struct { - meta_v1.TypeMeta `json:",inline"` - meta_v1.ListMeta `json:"metadata"` - Items []Bus `json:"items"` -} - -// GenericBus may be backed by Bus or ClusterBus -type GenericBus interface { - runtime.Object - meta_v1.ObjectMetaAccessor - BacksChannel(channel *Channel) bool - GetSpec() *BusSpec - GetStatus() *BusStatus - - // Needed for generic webhook support - apis.Defaultable - apis.Immutable - apis.Validatable -} diff --git a/pkg/apis/channels/v1alpha1/bus_validation.go b/pkg/apis/channels/v1alpha1/bus_validation.go deleted file mode 100644 index 66fd785f9d0..00000000000 --- a/pkg/apis/channels/v1alpha1/bus_validation.go +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "fmt" - "github.com/knative/pkg/apis" - "k8s.io/apimachinery/pkg/util/validation" -) - -// TODO(n3wscott): This is staging work, the plan is another pass to bring up -// the test coverage, then remove unused after each type is stubbed. -// This is all prep for new serving style webhook integration. - -func (b *Bus) Validate() *apis.FieldError { - return b.Spec.Validate().ViaField("spec") -} - -func (bs *BusSpec) Validate() *apis.FieldError { - if bs.Parameters != nil { - return bs.Parameters.Validate().ViaField("parameters") - } - return nil -} - -func (bp *BusParameters) Validate() *apis.FieldError { - if bp.Channel != nil { - for i, p := range *bp.Channel { - errs := validation.IsConfigMapKey(p.Name) - if len(errs) > 0 { - return apis.ErrInvalidKeyName(p.Name, "name", errs...).ViaField(fmt.Sprintf("channel[%d]", i)) - } - } - } - if bp.Subscription != nil { - for i, p := range *bp.Subscription { - errs := validation.IsConfigMapKey(p.Name) - if len(errs) > 0 { - return apis.ErrInvalidKeyName(p.Name, "name", errs...).ViaField(fmt.Sprintf("subscription[%d]", i)) - } - } - } - return nil -} - -func (current *Bus) CheckImmutableFields(og apis.Immutable) *apis.FieldError { - // TODO(n3wscott): Anything to check? - return nil -} diff --git a/pkg/apis/channels/v1alpha1/bus_validation_test.go b/pkg/apis/channels/v1alpha1/bus_validation_test.go deleted file mode 100644 index e74ed356315..00000000000 --- a/pkg/apis/channels/v1alpha1/bus_validation_test.go +++ /dev/null @@ -1,140 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "fmt" - "github.com/google/go-cmp/cmp" - "github.com/knative/pkg/apis" - "strings" - "testing" -) - -var longName = strings.Repeat("A", 255) - -// TODO: add the following tests: -// 1. Multiple parameters to the same Bus. -// 2. Two parameters with the same Name in the same list. -// 3. Multiple errors in the same object. - -func TestBusSpecValidation(t *testing.T) { - tests := []struct { - name string - bs *BusSpec - want *apis.FieldError - }{{ - name: "valid", - bs: &BusSpec{ - Parameters: &BusParameters{ - Channel: &[]Parameter{ - { - Name: "foo", - Description: "bar", - }, - }, - Subscription: &[]Parameter{ - { - Name: "foo", - Description: "bar", - }, - }, - }, - }, - }, { - name: "valid no description", - bs: &BusSpec{ - Parameters: &BusParameters{ - Channel: &[]Parameter{ - { - Name: "foo", - }, - }, - Subscription: &[]Parameter{ - { - Name: "foo", - }, - }, - }, - }, - }, { - name: "invalid channel parameter", - bs: &BusSpec{ - Parameters: &BusParameters{ - Channel: &[]Parameter{ - { - Name: "foo@bar", - }, - }, - }, - }, - want: &apis.FieldError{ - Message: `invalid key name "foo@bar"`, - Paths: []string{ - "parameters.channel[0].name", - }, - Details: "a valid config key must consist of alphanumeric characters, '-', '_' or '.' (e.g. 'key.name', or 'KEY_NAME', or 'key-name', regex used for validation is '[-._a-zA-Z0-9]+')", - }, - }, { - name: "invalid subscription parameter", - bs: &BusSpec{ - Parameters: &BusParameters{ - Subscription: &[]Parameter{ - { - Name: "foo@bar", - }, - }, - }, - }, - want: &apis.FieldError{ - Message: `invalid key name "foo@bar"`, - Paths: []string{ - "parameters.subscription[0].name", - }, - Details: "a valid config key must consist of alphanumeric characters, '-', '_' or '.' (e.g. 'key.name', or 'KEY_NAME', or 'key-name', regex used for validation is '[-._a-zA-Z0-9]+')", - }, - }, { - name: "invalid channel too long", - bs: &BusSpec{ - Parameters: &BusParameters{ - Channel: &[]Parameter{ - { - Name: longName, - }, - }, - }, - }, - want: &apis.FieldError{ - Message: fmt.Sprintf("invalid key name %q", longName), - Paths: []string{ - "parameters.channel[0].name", - }, - Details: "must be no more than 253 characters", - }, - }, { - name: "empty bus", - bs: &BusSpec{}, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.bs.Validate() - if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { - t.Errorf("validateBus (-want, +got) = %v", diff) - } - }) - } -} diff --git a/pkg/apis/channels/v1alpha1/channel_types.go b/pkg/apis/channels/v1alpha1/channel_types.go deleted file mode 100644 index 150243f2771..00000000000 --- a/pkg/apis/channels/v1alpha1/channel_types.go +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright 2018 The Knative Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package v1alpha1 - -import ( - "encoding/json" - - "github.com/knative/pkg/apis" - "github.com/knative/pkg/webhook" - "k8s.io/api/core/v1" - meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" -) - -// +genclient -// +genclient:noStatus -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +k8s:defaulter-gen=true - -// Channel represents a named endpoint on which a Bus accepts event delivery and -// corresponds to the channels.channels.knative.dev CRD. The Bus handles -// provisioning channels, delivering events to Channels, and delivering events -// from Channels to their Subscriptions. -type Channel struct { - meta_v1.TypeMeta `json:",inline"` - meta_v1.ObjectMeta `json:"metadata"` - Spec ChannelSpec `json:"spec"` - Status ChannelStatus `json:"status,omitempty"` -} - -// Check that Channel can be validated, can be defaulted, and has immutable fields. -var _ apis.Validatable = (*Channel)(nil) -var _ apis.Defaultable = (*Channel)(nil) -var _ apis.Immutable = (*Channel)(nil) -var _ runtime.Object = (*Channel)(nil) -var _ webhook.GenericCRD = (*Channel)(nil) - -// ChannelSpec specifies the Bus backing a channel and the configuration -// arguments for the channel. -type ChannelSpec struct { - // TODO: Generation does not work correctly with CRD. They are scrubbed - // by the APIserver (https://github.com/kubernetes/kubernetes/issues/58778) - // So, we add Generation here. Once that gets fixed, remove this and use - // ObjectMeta.Generation instead. - // +optional - Generation int64 `json:"generation,omitempty"` - - // Name of the bus backing this channel (optional) - Bus string `json:"bus,omitempty"` - - // ClusterBus name of the clusterbus backing this channel (mutually exclusive with Bus) - ClusterBus string `json:"clusterBus,omitempty"` - - // Arguments is a list of configuration arguments for the Channel. The - // Arguments for a channel must contain values for each of the Parameters - // specified by the Bus' spec.parameters.Channels field except the - // Parameters that have a default value. If a Parameter has a default value - // and it is not in the list of Arguments, the default value will be used; a - // Parameter without a default value that does not have an Argument will - // result in an error setting up the Channel. - Arguments *[]Argument `json:"arguments,omitempty"` -} - -type ChannelConditionType string - -const ( - - // Ready is set when all other conditions are met and the channel is ready to accept traffic. - ChannelReady ChannelConditionType = "Ready" - - // Serviceable means the service addressing the channel exists. - ChannelServiceable ChannelConditionType = "Serviceable" - - // Routable means the virtual service forwarding traffic from the channel service to the - // bus is created. - ChannelRoutable ChannelConditionType = "Routeable" - - // Provisioned means the channel backing construct on the bus middleware has been set up. - ChannelProvisioned ChannelConditionType = "Provisioned" -) - -// ChannelCondition describes the state of a channel at a point in time. -type ChannelCondition struct { - // Type of channel condition. - Type ChannelConditionType `json:"type"` - // Status of the condition, one of True, False, Unknown. - Status v1.ConditionStatus `json:"status"` - // The last time this condition was updated. - LastUpdateTime meta_v1.Time `json:"lastUpdateTime,omitempty"` - // Last time the condition transitioned from one status to another. - LastTransitionTime meta_v1.Time `json:"lastTransitionTime,omitempty"` - // The reason for the condition's last transition. - Reason string `json:"reason,omitempty"` - // A human readable message indicating details about the transition. - Message string `json:"message,omitempty"` -} - -// ChannelStatus (computed) for a channel -type ChannelStatus struct { - // A reference to the k8s Service backing this channel, if successfully synced. - Service *v1.LocalObjectReference `json:"service,omitempty"` - - // A reference to the istio VirtualService backing this channel, if successfully synced. - VirtualService *v1.LocalObjectReference `json:"virtualService,omitempty"` - - // Represents the latest available observations of a channel's current state. - // +patchMergeKey=type - // +patchStrategy=merge - Conditions []ChannelCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` - - // DomainInternal holds the top-level domain that will distribute traffic - // over the provided targets from inside the cluster. It generally has the - // form {channel}.{namespace}.svc.cluster.local - // +optional - DomainInternal string `json:"domainInternal,omitempty"` -} - -func (cs *ChannelStatus) GetCondition(t ChannelConditionType) *ChannelCondition { - for _, cond := range cs.Conditions { - if cond.Type == t { - return &cond - } - } - return nil -} - -func (c *Channel) GetSpecJSON() ([]byte, error) { - return json.Marshal(c.Spec) -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// ChannelList returned in list operations -type ChannelList struct { - meta_v1.TypeMeta `json:",inline"` - meta_v1.ListMeta `json:"metadata"` - Items []Channel `json:"items"` -} diff --git a/pkg/apis/channels/v1alpha1/channel_validation.go b/pkg/apis/channels/v1alpha1/channel_validation.go deleted file mode 100644 index 338f122a7c0..00000000000 --- a/pkg/apis/channels/v1alpha1/channel_validation.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "github.com/google/go-cmp/cmp" - "github.com/google/go-cmp/cmp/cmpopts" - "github.com/knative/pkg/apis" - - "k8s.io/apimachinery/pkg/util/validation" -) - -func (c *Channel) Validate() *apis.FieldError { - return c.Spec.Validate().ViaField("spec") -} - -func (cs *ChannelSpec) Validate() *apis.FieldError { - switch { - case len(cs.Bus) != 0 && len(cs.ClusterBus) != 0: - return apis.ErrMultipleOneOf("bus", "clusterBus") - case len(cs.Bus) != 0: - if errs := validation.IsQualifiedName(cs.Bus); len(errs) > 0 { - return apis.ErrInvalidKeyName(cs.Bus, "bus", errs...) - } - return nil - case len(cs.ClusterBus) != 0: - if errs := validation.IsQualifiedName(cs.ClusterBus); len(errs) > 0 { - return apis.ErrInvalidKeyName(cs.ClusterBus, "clusterBus", errs...) - } - return nil - default: - return apis.ErrMissingOneOf("bus", "clusterBus") - } -} - -func (current *Channel) CheckImmutableFields(og apis.Immutable) *apis.FieldError { - original, ok := og.(*Channel) - if !ok { - return &apis.FieldError{Message: "The provided original was not a Channel"} - } - if original == nil { - return nil - } - - ignoreArguments := cmpopts.IgnoreFields(ChannelSpec{}, "Arguments") - if diff := cmp.Diff(original.Spec, current.Spec, ignoreArguments); diff != "" { - return &apis.FieldError{ - Message: "Immutable fields changed (-old +new)", - Paths: []string{"spec"}, - Details: diff, - } - } - return nil -} diff --git a/pkg/apis/channels/v1alpha1/clusterbus_types.go b/pkg/apis/channels/v1alpha1/clusterbus_types.go deleted file mode 100644 index 4d891400983..00000000000 --- a/pkg/apis/channels/v1alpha1/clusterbus_types.go +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2018 The Knative Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package v1alpha1 - -import ( - "encoding/json" - - "github.com/knative/pkg/apis" - "github.com/knative/pkg/webhook" - meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" -) - -// +genclient -// +genclient:noStatus -// +genclient:nonNamespaced -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +k8s:defaulter-gen=true - -// ClusterBus represents the clusterbuses.channels.knative.dev CRD -type ClusterBus struct { - meta_v1.TypeMeta `json:",inline"` - meta_v1.ObjectMeta `json:"metadata"` - Spec ClusterBusSpec `json:"spec"` - Status ClusterBusStatus `json:"status,omitempty"` -} - -// Check that Bus can be validated, can be defaulted, and has immutable fields. -var _ apis.Validatable = (*ClusterBus)(nil) -var _ apis.Defaultable = (*ClusterBus)(nil) -var _ apis.Immutable = (*ClusterBus)(nil) -var _ runtime.Object = (*ClusterBus)(nil) -var _ webhook.GenericCRD = (*ClusterBus)(nil) - -// ClusterBusSpec (what the user wants) for a clusterbus -type ClusterBusSpec = BusSpec - -// ClusterBusStatus (computed) for a clusterbus -type ClusterBusStatus = BusStatus - -func (b *ClusterBus) BacksChannel(channel *Channel) bool { - return len(b.Namespace) == 0 && b.Name == channel.Spec.ClusterBus -} - -func (b *ClusterBus) GetSpec() *ClusterBusSpec { - return &b.Spec -} - -func (b *ClusterBus) GetStatus() *ClusterBusStatus { - return &b.Status -} - -func (b *ClusterBus) GetSpecJSON() ([]byte, error) { - return json.Marshal(b.Spec) -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// ClusterBusList returned in list operations -type ClusterBusList struct { - meta_v1.TypeMeta `json:",inline"` - meta_v1.ListMeta `json:"metadata"` - Items []ClusterBus `json:"items"` -} diff --git a/pkg/apis/channels/v1alpha1/param_types.go b/pkg/apis/channels/v1alpha1/param_types.go deleted file mode 100644 index b9e2fc9c63f..00000000000 --- a/pkg/apis/channels/v1alpha1/param_types.go +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2018 The Knative Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package v1alpha1 - -// inspired by the parameter/argument from buildtemplate/build - -// Parameter represents a named configuration parameter that must be supplied to -// create a particular resource by an Argument. Parameters may optionally have a -// default value that will be used if an Argument is not supplied. -type Parameter struct { - // Name is the name of the Parameter. - Name string `json:"name"` - - // Description is the human friendly description of the parameter. - Description string `json:"description"` - - // Default is the value to use if an Argument for this Parameter is not - // explicitly set. - Default *string `json:"default,omitempty"` -} - -// Argument represents a value for a named parameter. -type Argument struct { - // Name is the name of the Parameter this Argument is for. - Name string `json:"name"` - - // Value is the value for the Parameter. - Value string `json:"value"` -} diff --git a/pkg/apis/channels/v1alpha1/register.go b/pkg/apis/channels/v1alpha1/register.go deleted file mode 100644 index 32ce1eb5370..00000000000 --- a/pkg/apis/channels/v1alpha1/register.go +++ /dev/null @@ -1,59 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "github.com/knative/eventing/pkg/apis/channels" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -// SchemeGroupVersion is group version used to register these objects -var SchemeGroupVersion = schema.GroupVersion{Group: channels.GroupName, Version: "v1alpha1"} - -// Kind takes an unqualified kind and returns back a Group qualified GroupKind -func Kind(kind string) schema.GroupKind { - return SchemeGroupVersion.WithKind(kind).GroupKind() -} - -// Resource takes an unqualified resource and returns a Group qualified GroupResource -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} - -var ( - SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) - AddToScheme = SchemeBuilder.AddToScheme -) - -// Adds the list of known types to Scheme. -func addKnownTypes(scheme *runtime.Scheme) error { - scheme.AddKnownTypes(SchemeGroupVersion, - &Bus{}, - &BusList{}, - &ClusterBus{}, - &ClusterBusList{}, - &Channel{}, - &ChannelList{}, - &Subscription{}, - &SubscriptionList{}, - ) - metav1.AddToGroupVersion(scheme, SchemeGroupVersion) - return nil -} diff --git a/pkg/apis/channels/v1alpha1/subscription_types.go b/pkg/apis/channels/v1alpha1/subscription_types.go deleted file mode 100644 index 93747ae103f..00000000000 --- a/pkg/apis/channels/v1alpha1/subscription_types.go +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2018 The Knative Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package v1alpha1 - -import ( - "encoding/json" - - "github.com/knative/pkg/apis" - "github.com/knative/pkg/webhook" - "k8s.io/api/core/v1" - meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" -) - -// +genclient -// +genclient:noStatus -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +k8s:defaulter-gen=true - -// Subscription routes events received on a Channel to a DNS name and -// corresponds to the subscriptions.channels.knative.dev CRD. -type Subscription struct { - meta_v1.TypeMeta `json:",inline"` - meta_v1.ObjectMeta `json:"metadata"` - Spec SubscriptionSpec `json:"spec"` - Status SubscriptionStatus `json:"status,omitempty"` -} - -// Check that Subscription can be validated, can be defaulted, and has immutable fields. -var _ apis.Validatable = (*Subscription)(nil) -var _ apis.Defaultable = (*Subscription)(nil) -var _ apis.Immutable = (*Subscription)(nil) -var _ runtime.Object = (*Subscription)(nil) -var _ webhook.GenericCRD = (*ClusterBus)(nil) - -// SubscriptionSpec specifies the Channel and Subscriber and the configuration -// arguments for the Subscription. -type SubscriptionSpec struct { - // TODO: Generation does not work correctly with CRD. They are scrubbed - // by the APIserver (https://github.com/kubernetes/kubernetes/issues/58778) - // So, we add Generation here. Once that gets fixed, remove this and use - // ObjectMeta.Generation instead. - // +optional - Generation int64 `json:"generation,omitempty"` - - // Channel is the name of the channel to subscribe to. - Channel string `json:"channel"` - - // Subscriber is the name of the subscriber service DNS name. - Subscriber string `json:"subscriber"` - - // Target service DNS name for replies returned by the subscriber. - ReplyTo string `json:"replyTo,omitempty"` - - // Arguments is a list of configuration arguments for the Subscription. The - // Arguments for a channel must contain values for each of the Parameters - // specified by the Bus' spec.parameters.Subscriptions field except the - // Parameters that have a default value. If a Parameter has a default value - // and it is not in the list of Arguments, the default value will be used; a - // Parameter without a default value that does not have an Argument will - // result in an error setting up the Subscription. - Arguments *[]Argument `json:"arguments,omitempty"` -} - -type SubscriptionConditionType string - -const ( - // Dispatching means the subscription is actively listening for incoming events on its channel and dispatching them. - SubscriptionDispatching SubscriptionConditionType = "Dispatching" -) - -// SubscriptionCondition describes the state of a subscription at a point in time. -type SubscriptionCondition struct { - // Type of subscription condition. - Type SubscriptionConditionType `json:"type"` - // Status of the condition, one of True, False, Unknown. - Status v1.ConditionStatus `json:"status"` - // The last time this condition was updated. - LastUpdateTime meta_v1.Time `json:"lastUpdateTime,omitempty"` - // Last time the condition transitioned from one status to another. - LastTransitionTime meta_v1.Time `json:"lastTransitionTime,omitempty"` - // The reason for the condition's last transition. - Reason string `json:"reason,omitempty"` - // A human readable message indicating details about the transition. - Message string `json:"message,omitempty"` -} - -// SubscriptionStatus (computed) for a subscription -type SubscriptionStatus struct { - - // Represents the latest available observations of a subscription's current state. - // +patchMergeKey=type - // +patchStrategy=merge - Conditions []SubscriptionCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` -} - -func (ss *SubscriptionStatus) GetCondition(t SubscriptionConditionType) *SubscriptionCondition { - for _, cond := range ss.Conditions { - if cond.Type == t { - return &cond - } - } - return nil -} - -func (s *Subscription) GetSpecJSON() ([]byte, error) { - return json.Marshal(s.Spec) -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// SubscriptionList returned in list operations -type SubscriptionList struct { - meta_v1.TypeMeta `json:",inline"` - meta_v1.ListMeta `json:"metadata"` - Items []Subscription `json:"items"` -} diff --git a/pkg/apis/channels/v1alpha1/subscription_validation_test.go b/pkg/apis/channels/v1alpha1/subscription_validation_test.go deleted file mode 100644 index 091a5b7f3b2..00000000000 --- a/pkg/apis/channels/v1alpha1/subscription_validation_test.go +++ /dev/null @@ -1,139 +0,0 @@ -/* -Copyright 2018 The Knative Authors. All Rights Reserved. -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/knative/pkg/apis" -) - -func TestSubscriptionSpecValidation(t *testing.T) { - tests := []struct { - name string - c *SubscriptionSpec - want *apis.FieldError - }{{ - name: "valid", - c: &SubscriptionSpec{ - Channel: "bar", - Subscriber: "foo", - }, - want: nil, - }, { - name: "valid with arguments", - c: &SubscriptionSpec{ - Channel: "bar", - Subscriber: "foo", - Arguments: &[]Argument{{Name: "foo", Value: "bar"}}, - }, - want: nil, - }, { - name: "missing subscriber", - c: &SubscriptionSpec{ - Channel: "foo", - }, - want: func() *apis.FieldError { - fe := apis.ErrMissingField("subscriber") - fe.Details = "the Subscription must reference a Subscriber" - return fe - }(), - }, { - name: "empty", - c: &SubscriptionSpec{}, - want: func() *apis.FieldError { - fe := apis.ErrMissingField("channel") - fe.Details = "the Subscription must reference a Channel" - return fe - }(), - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.c.Validate() - if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { - t.Errorf("validateChannel (-want, +got) = %v", diff) - } - }) - } -} - -func TestSubscriptionImmutable(t *testing.T) { - tests := []struct { - name string - c *Subscription - og *Subscription - want *apis.FieldError - }{{ - name: "valid", - c: &Subscription{ - Spec: SubscriptionSpec{ - Channel: "foo", - }, - }, - og: &Subscription{ - Spec: SubscriptionSpec{ - Channel: "foo", - }, - }, - want: nil, - }, { - name: "valid, new subscriber", - c: &Subscription{ - Spec: SubscriptionSpec{ - Channel: "foo", - Subscriber: "bar", - }, - }, - og: &Subscription{ - Spec: SubscriptionSpec{ - Channel: "foo", - Subscriber: "baz", - }, - }, - want: nil, - }, { - name: "channel changed", - c: &Subscription{ - Spec: SubscriptionSpec{ - Channel: "foo", - }, - }, - og: &Subscription{ - Spec: SubscriptionSpec{ - Channel: "bar", - }, - }, - want: &apis.FieldError{ - Message: "Immutable fields changed (-old +new)", - Paths: []string{"spec"}, - Details: `{v1alpha1.SubscriptionSpec}.Channel: - -: "bar" - +: "foo" -`, - }, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.c.CheckImmutableFields(test.og) - if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { - t.Errorf("CheckImmutableFields (-want, +got) = %v", diff) - } - }) - } -} diff --git a/pkg/apis/channels/v1alpha1/zz_generated.deepcopy.go b/pkg/apis/channels/v1alpha1/zz_generated.deepcopy.go deleted file mode 100644 index 3f815bbcd0a..00000000000 --- a/pkg/apis/channels/v1alpha1/zz_generated.deepcopy.go +++ /dev/null @@ -1,615 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by deepcopy-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1 "k8s.io/api/core/v1" - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Argument) DeepCopyInto(out *Argument) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Argument. -func (in *Argument) DeepCopy() *Argument { - if in == nil { - return nil - } - out := new(Argument) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Bus) DeepCopyInto(out *Bus) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Bus. -func (in *Bus) DeepCopy() *Bus { - if in == nil { - return nil - } - out := new(Bus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Bus) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BusCondition) DeepCopyInto(out *BusCondition) { - *out = *in - in.LastUpdateTime.DeepCopyInto(&out.LastUpdateTime) - in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BusCondition. -func (in *BusCondition) DeepCopy() *BusCondition { - if in == nil { - return nil - } - out := new(BusCondition) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BusList) DeepCopyInto(out *BusList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Bus, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BusList. -func (in *BusList) DeepCopy() *BusList { - if in == nil { - return nil - } - out := new(BusList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *BusList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BusParameters) DeepCopyInto(out *BusParameters) { - *out = *in - if in.Channel != nil { - in, out := &in.Channel, &out.Channel - if *in == nil { - *out = nil - } else { - *out = new([]Parameter) - if **in != nil { - in, out := *in, *out - *out = make([]Parameter, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - } - } - if in.Subscription != nil { - in, out := &in.Subscription, &out.Subscription - if *in == nil { - *out = nil - } else { - *out = new([]Parameter) - if **in != nil { - in, out := *in, *out - *out = make([]Parameter, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BusParameters. -func (in *BusParameters) DeepCopy() *BusParameters { - if in == nil { - return nil - } - out := new(BusParameters) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BusSpec) DeepCopyInto(out *BusSpec) { - *out = *in - if in.Parameters != nil { - in, out := &in.Parameters, &out.Parameters - if *in == nil { - *out = nil - } else { - *out = new(BusParameters) - (*in).DeepCopyInto(*out) - } - } - if in.Provisioner != nil { - in, out := &in.Provisioner, &out.Provisioner - if *in == nil { - *out = nil - } else { - *out = new(v1.Container) - (*in).DeepCopyInto(*out) - } - } - in.Dispatcher.DeepCopyInto(&out.Dispatcher) - if in.Volumes != nil { - in, out := &in.Volumes, &out.Volumes - if *in == nil { - *out = nil - } else { - *out = new([]v1.Volume) - if **in != nil { - in, out := *in, *out - *out = make([]v1.Volume, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BusSpec. -func (in *BusSpec) DeepCopy() *BusSpec { - if in == nil { - return nil - } - out := new(BusSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BusStatus) DeepCopyInto(out *BusStatus) { - *out = *in - if in.Service != nil { - in, out := &in.Service, &out.Service - if *in == nil { - *out = nil - } else { - *out = new(v1.LocalObjectReference) - **out = **in - } - } - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make([]BusCondition, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BusStatus. -func (in *BusStatus) DeepCopy() *BusStatus { - if in == nil { - return nil - } - out := new(BusStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Channel) DeepCopyInto(out *Channel) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Channel. -func (in *Channel) DeepCopy() *Channel { - if in == nil { - return nil - } - out := new(Channel) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Channel) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ChannelCondition) DeepCopyInto(out *ChannelCondition) { - *out = *in - in.LastUpdateTime.DeepCopyInto(&out.LastUpdateTime) - in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChannelCondition. -func (in *ChannelCondition) DeepCopy() *ChannelCondition { - if in == nil { - return nil - } - out := new(ChannelCondition) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ChannelList) DeepCopyInto(out *ChannelList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Channel, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChannelList. -func (in *ChannelList) DeepCopy() *ChannelList { - if in == nil { - return nil - } - out := new(ChannelList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ChannelList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ChannelSpec) DeepCopyInto(out *ChannelSpec) { - *out = *in - if in.Arguments != nil { - in, out := &in.Arguments, &out.Arguments - if *in == nil { - *out = nil - } else { - *out = new([]Argument) - if **in != nil { - in, out := *in, *out - *out = make([]Argument, len(*in)) - copy(*out, *in) - } - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChannelSpec. -func (in *ChannelSpec) DeepCopy() *ChannelSpec { - if in == nil { - return nil - } - out := new(ChannelSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ChannelStatus) DeepCopyInto(out *ChannelStatus) { - *out = *in - if in.Service != nil { - in, out := &in.Service, &out.Service - if *in == nil { - *out = nil - } else { - *out = new(v1.LocalObjectReference) - **out = **in - } - } - if in.VirtualService != nil { - in, out := &in.VirtualService, &out.VirtualService - if *in == nil { - *out = nil - } else { - *out = new(v1.LocalObjectReference) - **out = **in - } - } - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make([]ChannelCondition, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChannelStatus. -func (in *ChannelStatus) DeepCopy() *ChannelStatus { - if in == nil { - return nil - } - out := new(ChannelStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterBus) DeepCopyInto(out *ClusterBus) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterBus. -func (in *ClusterBus) DeepCopy() *ClusterBus { - if in == nil { - return nil - } - out := new(ClusterBus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ClusterBus) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterBusList) DeepCopyInto(out *ClusterBusList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]ClusterBus, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterBusList. -func (in *ClusterBusList) DeepCopy() *ClusterBusList { - if in == nil { - return nil - } - out := new(ClusterBusList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ClusterBusList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Parameter) DeepCopyInto(out *Parameter) { - *out = *in - if in.Default != nil { - in, out := &in.Default, &out.Default - if *in == nil { - *out = nil - } else { - *out = new(string) - **out = **in - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Parameter. -func (in *Parameter) DeepCopy() *Parameter { - if in == nil { - return nil - } - out := new(Parameter) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Subscription) DeepCopyInto(out *Subscription) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Subscription. -func (in *Subscription) DeepCopy() *Subscription { - if in == nil { - return nil - } - out := new(Subscription) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Subscription) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SubscriptionCondition) DeepCopyInto(out *SubscriptionCondition) { - *out = *in - in.LastUpdateTime.DeepCopyInto(&out.LastUpdateTime) - in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SubscriptionCondition. -func (in *SubscriptionCondition) DeepCopy() *SubscriptionCondition { - if in == nil { - return nil - } - out := new(SubscriptionCondition) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SubscriptionList) DeepCopyInto(out *SubscriptionList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Subscription, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SubscriptionList. -func (in *SubscriptionList) DeepCopy() *SubscriptionList { - if in == nil { - return nil - } - out := new(SubscriptionList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *SubscriptionList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SubscriptionSpec) DeepCopyInto(out *SubscriptionSpec) { - *out = *in - if in.Arguments != nil { - in, out := &in.Arguments, &out.Arguments - if *in == nil { - *out = nil - } else { - *out = new([]Argument) - if **in != nil { - in, out := *in, *out - *out = make([]Argument, len(*in)) - copy(*out, *in) - } - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SubscriptionSpec. -func (in *SubscriptionSpec) DeepCopy() *SubscriptionSpec { - if in == nil { - return nil - } - out := new(SubscriptionSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SubscriptionStatus) DeepCopyInto(out *SubscriptionStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make([]SubscriptionCondition, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SubscriptionStatus. -func (in *SubscriptionStatus) DeepCopy() *SubscriptionStatus { - if in == nil { - return nil - } - out := new(SubscriptionStatus) - in.DeepCopyInto(out) - return out -} diff --git a/vendor/github.com/knative/serving/pkg/apis/istio/v1alpha3/doc.go b/pkg/apis/duck/v1alpha1/doc.go similarity index 88% rename from vendor/github.com/knative/serving/pkg/apis/istio/v1alpha3/doc.go rename to pkg/apis/duck/v1alpha1/doc.go index 47ec83daedf..3e5d1e3bc5a 100644 --- a/vendor/github.com/knative/serving/pkg/apis/istio/v1alpha3/doc.go +++ b/pkg/apis/duck/v1alpha1/doc.go @@ -1,12 +1,9 @@ /* Copyright 2018 The Knative 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. @@ -18,6 +15,7 @@ limitations under the License. // backward compatibility by support multiple concurrent versions // of the same resource +// Package v1alpha1 is the v1alpha1 version of the API. // +k8s:deepcopy-gen=package -// +groupName=networking.istio.io -package v1alpha3 +// +groupName=duck.knative.dev +package v1alpha1 diff --git a/pkg/apis/duck/v1alpha1/subscribable_types.go b/pkg/apis/duck/v1alpha1/subscribable_types.go new file mode 100644 index 00000000000..b0ca54d2fcd --- /dev/null +++ b/pkg/apis/duck/v1alpha1/subscribable_types.go @@ -0,0 +1,111 @@ +/* + * Copyright 2018 The Knative Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package v1alpha1 + +import ( + "github.com/knative/pkg/apis/duck" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +// Subscribable is the schema for the subscribable portion of the spec +// section of the resource. +type Subscribable struct { + // TODO: What is actually required here for Channel spec. + // This is the list of subscriptions for this channel. + Subscribers []ChannelSubscriberSpec `json:"subscribers,omitempty"` +} + +// ChannelSubscriberSpec defines a single subscriber to a Channel. +// Ref is a reference to the Subscription this ChannelSubscriberSpec was created for +// SubscriberURI is the endpoint for the subscriber +// ReplyURI is the endpoint for the reply +// At least one of SubscriberURI and ReplyURI must be present +type ChannelSubscriberSpec struct { + // +optional + Ref *corev1.ObjectReference `json:"ref,omitempty"` + // +optional + SubscriberURI string `json:"subscriberURI,omitempty"` + // +optional + ReplyURI string `json:"replyURI,omitempty"` +} + +// Channel is a skeleton type wrapping Subscribable in the manner we expect resource writers +// defining compatible resources to embed it. We will typically use this type to deserialize +// Channel ObjectReferences and access the Subscription data. This is not a real resource. +type Channel struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + // ChannelSpec is the part where Subscribable object is + // configured as to be compatible with Subscribable contract. + Spec ChannelSpec `json:"spec"` +} + +// ChannelSpec shows how we expect folks to embed Subscribable in their Spec field. +type ChannelSpec struct { + Subscribable *Subscribable `json:"subscribable,omitempty"` +} + +// GetFullType implements duck.Implementable +func (s *Subscribable) GetFullType() duck.Populatable { + return &Channel{} +} + +// Populate implements duck.Populatable +func (c *Channel) Populate() { + c.Spec.Subscribable = &Subscribable{ + // Populate ALL fields + Subscribers: []ChannelSubscriberSpec{{ + Ref: &corev1.ObjectReference{ + APIVersion: "eventing.knative.dev/v1alpha1", + Kind: "Subscription", + Name: "subscription1", + Namespace: "default", + UID: "2f9b5e8e-deb6-11e8-9f32-f2801f1b9fd1", + }, + SubscriberURI: "call1", + ReplyURI: "sink2", + }, { + Ref: &corev1.ObjectReference{ + APIVersion: "eventing.knative.dev/v1alpha1", + Kind: "Subscription", + Name: "subscription2", + Namespace: "default", + UID: "34c5aec8-deb6-11e8-9f32-f2801f1b9fd1", + }, + SubscriberURI: "call2", + ReplyURI: "sink2", + }}, + } +} + +// GetListType implements apis.Listable +func (c *Channel) GetListType() runtime.Object { + return &ChannelList{} +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ChannelList is a list of Channel resources +type ChannelList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata"` + + Items []Channel `json:"items"` +} diff --git a/pkg/apis/duck/v1alpha1/subscribable_types_test.go b/pkg/apis/duck/v1alpha1/subscribable_types_test.go new file mode 100644 index 00000000000..c14bbc70d92 --- /dev/null +++ b/pkg/apis/duck/v1alpha1/subscribable_types_test.go @@ -0,0 +1,83 @@ +/* + * Copyright 2018 The Knative Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package v1alpha1 + +import ( + "testing" + + "github.com/google/go-cmp/cmp" + corev1 "k8s.io/api/core/v1" +) + +func TestGetFullType(t *testing.T) { + s := &Subscribable{} + switch s.GetFullType().(type) { + case *Channel: + // expected + default: + t.Errorf("expected GetFullType to return *Channel, got %T", s.GetFullType()) + } +} + +func TestGetListType(t *testing.T) { + c := &Channel{} + switch c.GetListType().(type) { + case *ChannelList: + // expected + default: + t.Errorf("expected GetFullType to return *ChannelList, got %T", c.GetListType()) + } +} + +func TestPopulate(t *testing.T) { + got := &Channel{} + + want := &Channel{ + Spec: ChannelSpec{ + Subscribable: &Subscribable{ + Subscribers: []ChannelSubscriberSpec{{ + Ref: &corev1.ObjectReference{ + APIVersion: "eventing.knative.dev/v1alpha1", + Kind: "Subscription", + Name: "subscription1", + Namespace: "default", + UID: "2f9b5e8e-deb6-11e8-9f32-f2801f1b9fd1", + }, + SubscriberURI: "call1", + ReplyURI: "sink2", + }, { + Ref: &corev1.ObjectReference{ + APIVersion: "eventing.knative.dev/v1alpha1", + Kind: "Subscription", + Name: "subscription2", + Namespace: "default", + UID: "34c5aec8-deb6-11e8-9f32-f2801f1b9fd1", + }, + SubscriberURI: "call2", + ReplyURI: "sink2", + }}, + }, + }, + } + + got.Populate() + + if diff := cmp.Diff(want, got); diff != "" { + t.Errorf("Unexpected difference (-want, +got): %v", diff) + } + +} diff --git a/pkg/apis/duck/v1alpha1/zz_generated.deepcopy.go b/pkg/apis/duck/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 00000000000..064638afd33 --- /dev/null +++ b/pkg/apis/duck/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,151 @@ +// +build !ignore_autogenerated + +/* +Copyright 2018 The Knative 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. +*/ + +// Code generated by deepcopy-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + v1 "k8s.io/api/core/v1" + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Channel) DeepCopyInto(out *Channel) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Channel. +func (in *Channel) DeepCopy() *Channel { + if in == nil { + return nil + } + out := new(Channel) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ChannelList) DeepCopyInto(out *ChannelList) { + *out = *in + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Channel, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChannelList. +func (in *ChannelList) DeepCopy() *ChannelList { + if in == nil { + return nil + } + out := new(ChannelList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ChannelList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ChannelSpec) DeepCopyInto(out *ChannelSpec) { + *out = *in + if in.Subscribable != nil { + in, out := &in.Subscribable, &out.Subscribable + if *in == nil { + *out = nil + } else { + *out = new(Subscribable) + (*in).DeepCopyInto(*out) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChannelSpec. +func (in *ChannelSpec) DeepCopy() *ChannelSpec { + if in == nil { + return nil + } + out := new(ChannelSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ChannelSubscriberSpec) DeepCopyInto(out *ChannelSubscriberSpec) { + *out = *in + if in.Ref != nil { + in, out := &in.Ref, &out.Ref + if *in == nil { + *out = nil + } else { + *out = new(v1.ObjectReference) + **out = **in + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChannelSubscriberSpec. +func (in *ChannelSubscriberSpec) DeepCopy() *ChannelSubscriberSpec { + if in == nil { + return nil + } + out := new(ChannelSubscriberSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Subscribable) DeepCopyInto(out *Subscribable) { + *out = *in + if in.Subscribers != nil { + in, out := &in.Subscribers, &out.Subscribers + *out = make([]ChannelSubscriberSpec, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Subscribable. +func (in *Subscribable) DeepCopy() *Subscribable { + if in == nil { + return nil + } + out := new(Subscribable) + in.DeepCopyInto(out) + return out +} diff --git a/pkg/apis/eventing/logkey/constants.go b/pkg/apis/eventing/logkey/constants.go index e83233cc9a5..d9d383b18b5 100644 --- a/pkg/apis/eventing/logkey/constants.go +++ b/pkg/apis/eventing/logkey/constants.go @@ -19,6 +19,6 @@ package logkey const ( kNative = "knative.dev/" - // ClusterProvisioner is the key used for cluster provisioner names in structured logs - ClusterProvisioner = kNative + "clusterprovisioner" + // ClusterChannelProvisioner is the key used for cluster provisioner names in structured logs + ClusterChannelProvisioner = kNative + "clusterchannelprovisioner" ) diff --git a/pkg/apis/eventing/v1alpha1/channel_defaults.go b/pkg/apis/eventing/v1alpha1/channel_defaults.go index a95fb228dec..13207f98299 100644 --- a/pkg/apis/eventing/v1alpha1/channel_defaults.go +++ b/pkg/apis/eventing/v1alpha1/channel_defaults.go @@ -16,11 +16,36 @@ limitations under the License. package v1alpha1 -//TODO replace this with openapi defaults when -// https://github.com/kubernetes/features/issues/575 lands (scheduled for 1.13) +import ( + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +// ChannelProvisionerDefaulter sets the default Provisioner and Arguments on Channels that do not +// specify any Provisioner. +type ChannelProvisionerDefaulter interface { + // GetDefault determines the default provisioner and arguments for the given channel. It does + // not modify the given channel. It may return nil for either or both. + GetDefault(c *Channel) (*corev1.ObjectReference, *runtime.RawExtension) +} + +var ( + // ChannelDefaulterSingleton is the global singleton used to default Channels that do not + // specify any provisioner. + ChannelDefaulterSingleton ChannelProvisionerDefaulter +) + func (c *Channel) SetDefaults() { + if c != nil && c.Spec.Provisioner == nil { + // The singleton may not have been set, if so ignore it and validation will reject the + // Channel. + if cd := ChannelDefaulterSingleton; cd != nil { + prov, args := cd.GetDefault(c.DeepCopy()) + c.Spec.Provisioner = prov + c.Spec.Arguments = args + } + } c.Spec.SetDefaults() } -func (fs *ChannelSpec) SetDefaults() { -} +func (cs *ChannelSpec) SetDefaults() {} diff --git a/pkg/apis/eventing/v1alpha1/channel_defaults_test.go b/pkg/apis/eventing/v1alpha1/channel_defaults_test.go index d6cb6abd80b..a00e7413c5e 100644 --- a/pkg/apis/eventing/v1alpha1/channel_defaults_test.go +++ b/pkg/apis/eventing/v1alpha1/channel_defaults_test.go @@ -16,10 +16,99 @@ limitations under the License. package v1alpha1 -import "testing" +import ( + "testing" + + "k8s.io/apimachinery/pkg/runtime" + + corev1 "k8s.io/api/core/v1" + + "github.com/google/go-cmp/cmp" +) + +var ( + defaultChannelProvisioner = &corev1.ObjectReference{ + APIVersion: SchemeGroupVersion.String(), + Kind: "ClusterChannelProvisioner", + Name: "default-channel-provisioner", + } + defaultChannelArgs = &runtime.RawExtension{ + Object: &corev1.ObjectReference{ + Name: "default-args", + }, + } +) -// No-op test because method does nothing. func TestChannelSetDefaults(t *testing.T) { - c := Channel{} - c.SetDefaults() + testCases := map[string]struct { + nilChannelDefaulter bool + prov *corev1.ObjectReference + args *runtime.RawExtension + initial Channel + expected Channel + }{ + "nil ChannelDefaulter": { + nilChannelDefaulter: true, + expected: Channel{}, + }, + "unset ChannelDefaulter": { + expected: Channel{}, + }, + "set ChannelDefaulter": { + prov: defaultChannelProvisioner, + args: defaultChannelArgs, + expected: Channel{ + Spec: ChannelSpec{ + Provisioner: defaultChannelProvisioner, + Arguments: defaultChannelArgs, + }, + }, + }, + "provisioner already specified": { + prov: defaultChannelProvisioner, + args: defaultChannelArgs, + initial: Channel{ + Spec: ChannelSpec{ + Provisioner: &corev1.ObjectReference{ + APIVersion: SchemeGroupVersion.String(), + Kind: "ClusterChannelProvisioner", + Name: "already-specified", + }, + }, + }, + expected: Channel{ + Spec: ChannelSpec{ + Provisioner: &corev1.ObjectReference{ + APIVersion: SchemeGroupVersion.String(), + Kind: "ClusterChannelProvisioner", + Name: "already-specified", + }, + }, + }, + }, + } + for n, tc := range testCases { + t.Run(n, func(t *testing.T) { + if !tc.nilChannelDefaulter { + ChannelDefaulterSingleton = &channelDefaulter{ + prov: tc.prov, + args: tc.args, + } + defer func() { ChannelDefaulterSingleton = nil }() + } + tc.initial.SetDefaults() + if diff := cmp.Diff(tc.expected, tc.initial); diff != "" { + t.Fatalf("Unexpected defaults (-want, +got): %s", diff) + } + }) + } +} + +type channelDefaulter struct { + prov *corev1.ObjectReference + args *runtime.RawExtension +} + +func (cd *channelDefaulter) GetDefault(_ *Channel) (*corev1.ObjectReference, *runtime.RawExtension) { + return cd.prov, cd.args } diff --git a/pkg/apis/eventing/v1alpha1/channel_types.go b/pkg/apis/eventing/v1alpha1/channel_types.go index d5122b08344..2b6606bb717 100644 --- a/pkg/apis/eventing/v1alpha1/channel_types.go +++ b/pkg/apis/eventing/v1alpha1/channel_types.go @@ -17,6 +17,7 @@ package v1alpha1 import ( + eventingduck "github.com/knative/eventing/pkg/apis/duck/v1alpha1" "github.com/knative/pkg/apis" duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" "github.com/knative/pkg/webhook" @@ -29,8 +30,8 @@ import ( // +genclient:noStatus // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// Channel is an abstract resource that implements the Subscribable and Sinkable -// contracts. The Provisioner provisions infrastructure to accepts events and +// Channel is an abstract resource that implements the Addressable contract. +// The Provisioner provisions infrastructure to accepts events and // deliver to Subscriptions. type Channel struct { metav1.TypeMeta `json:",inline"` @@ -64,19 +65,18 @@ type ChannelSpec struct { Generation int64 `json:"generation,omitempty"` // Provisioner defines the name of the Provisioner backing this channel. - // TODO: +optional If missing, a default Provisioner may be selected for the Channel. - Provisioner *ProvisionerReference `json:"provisioner,omitempty"` + Provisioner *corev1.ObjectReference `json:"provisioner,omitempty"` - // Arguments defines the arguments to pass to the Provisioner which provisions - // this Channel. + // Arguments defines the arguments to pass to the Provisioner which + // provisions this Channel. // +optional Arguments *runtime.RawExtension `json:"arguments,omitempty"` - // Channel conforms to Duck type Channelable. - Channelable *duckv1alpha1.Channelable `json:"channelable,omitempty"` + // Channel conforms to Duck type Subscribable. + Subscribable *eventingduck.Subscribable `json:"subscribable,omitempty"` } -var chanCondSet = duckv1alpha1.NewLivingConditionSet(ChannelConditionProvisioned, ChannelConditionSinkable, ChannelConditionSubscribable) +var chanCondSet = duckv1alpha1.NewLivingConditionSet(ChannelConditionProvisioned, ChannelConditionAddressable) // ChannelStatus represents the current state of a Channel. type ChannelStatus struct { @@ -88,13 +88,12 @@ type ChannelStatus struct { // +optional ObservedGeneration int64 `json:"observedGeneration,omitempty"` - // Channel is Sinkable. It currently exposes the endpoint as top-level domain - // that will distribute traffic over the provided targets from inside the cluster. + // Channel is Addressable. It currently exposes the endpoint as a + // fully-qualified DNS name which will distribute traffic over the + // provided targets from inside the cluster. + // // It generally has the form {channel}.{namespace}.svc.cluster.local - Sinkable duckv1alpha1.Sinkable `json:"sinkable,omitempty"` - - // Channel is Subscribable. It just points to itself - Subscribable duckv1alpha1.Subscribable `json:"subscribable,omitempty"` + Address duckv1alpha1.Addressable `json:"address,omitempty"` // Represents the latest available observations of a channel's current state. // +optional @@ -104,21 +103,17 @@ type ChannelStatus struct { } const ( - // ChannelConditionReady has status True when the Channel is ready to accept - // traffic. + // ChannelConditionReady has status True when the Channel is ready to + // accept traffic. ChannelConditionReady = duckv1alpha1.ConditionReady - // ChannelConditionProvisioned has status True when the Channel's backing - // resources have been provisioned. + // ChannelConditionProvisioned has status True when the Channel's + // backing resources have been provisioned. ChannelConditionProvisioned duckv1alpha1.ConditionType = "Provisioned" - // ChannelConditionSinkable has status true when this Channel meets the Sinkable contract and - // has a non-empty domainInternal. - ChannelConditionSinkable duckv1alpha1.ConditionType = "Sinkable" - - // ChannelConditionSubscribable has status true when this Channel meets the Subscribable - // contract and has a non-empty Channelable object reference. - ChannelConditionSubscribable duckv1alpha1.ConditionType = "Subscribable" + // ChannelConditionAddressable has status true when this Channel meets + // the Addressable contract and has a non-empty hostname. + ChannelConditionAddressable duckv1alpha1.ConditionType = "Addressable" ) // GetCondition returns the condition currently associated with the given type, or nil. @@ -141,33 +136,19 @@ func (cs *ChannelStatus) MarkProvisioned() { chanCondSet.Manage(cs).MarkTrue(ChannelConditionProvisioned) } -// SetSubscribable makes this Channel Subscribable, by having it point at itself. The 'name' and -// 'namespace' should be the name and namespace of the Channel this ChannelStatus is on. It also -// sets the ChannelConditionSubscribable to true. -func (cs *ChannelStatus) SetSubscribable(namespace, name string) { - if namespace != "" || name != "" { - cs.Subscribable.Channelable = corev1.ObjectReference{ - Kind: "Channel", - APIVersion: SchemeGroupVersion.String(), - Namespace: namespace, - Name: name, - } - chanCondSet.Manage(cs).MarkTrue(ChannelConditionSubscribable) - } else { - cs.Subscribable.Channelable = corev1.ObjectReference{} - chanCondSet.Manage(cs).MarkFalse(ChannelConditionSubscribable, "notSubscribable", "not Subscribable") - } - +// MarkNotProvisioned sets ChannelConditionProvisioned condition to False state. +func (cs *ChannelStatus) MarkNotProvisioned(reason, messageFormat string, messageA ...interface{}) { + chanCondSet.Manage(cs).MarkFalse(ChannelConditionProvisioned, reason, messageFormat, messageA...) } -// SetSinkable makes this Channel sinkable by setting the domainInternal. It also sets the -// ChannelConditionSinkable to true. -func (cs *ChannelStatus) SetSinkable(domainInternal string) { - cs.Sinkable.DomainInternal = domainInternal - if domainInternal != "" { - chanCondSet.Manage(cs).MarkTrue(ChannelConditionSinkable) +// SetAddress makes this Channel addressable by setting the hostname. It also +// sets the ChannelConditionAddressable to true. +func (cs *ChannelStatus) SetAddress(hostname string) { + cs.Address.Hostname = hostname + if hostname != "" { + chanCondSet.Manage(cs).MarkTrue(ChannelConditionAddressable) } else { - chanCondSet.Manage(cs).MarkFalse(ChannelConditionSinkable, "emptyDomainInternal", "domainInternal is the empty string") + chanCondSet.Manage(cs).MarkFalse(ChannelConditionAddressable, "emptyHostname", "hostname is the empty string") } } diff --git a/pkg/apis/eventing/v1alpha1/channel_types_test.go b/pkg/apis/eventing/v1alpha1/channel_types_test.go index e2e6cac4104..2cbabce3696 100644 --- a/pkg/apis/eventing/v1alpha1/channel_types_test.go +++ b/pkg/apis/eventing/v1alpha1/channel_types_test.go @@ -35,7 +35,9 @@ var condUnprovisioned = duckv1alpha1.Condition{ Status: corev1.ConditionFalse, } -var ignoreTransitionTimeMessageAndReason = cmpopts.IgnoreFields(duckv1alpha1.Condition{}, "LastTransitionTime", "Message", "Reason") +var ignoreAllButTypeAndStatus = cmpopts.IgnoreFields( + duckv1alpha1.Condition{}, + "LastTransitionTime", "Message", "Reason", "Severity") func TestChannelGetCondition(t *testing.T) { tests := []struct { @@ -94,16 +96,13 @@ func TestChannelInitializeConditions(t *testing.T) { cs: &ChannelStatus{}, want: &ChannelStatus{ Conditions: []duckv1alpha1.Condition{{ - Type: ChannelConditionProvisioned, + Type: ChannelConditionAddressable, Status: corev1.ConditionUnknown, }, { - Type: ChannelConditionReady, - Status: corev1.ConditionUnknown, - }, { - Type: ChannelConditionSinkable, + Type: ChannelConditionProvisioned, Status: corev1.ConditionUnknown, }, { - Type: ChannelConditionSubscribable, + Type: ChannelConditionReady, Status: corev1.ConditionUnknown, }}, }, @@ -117,17 +116,14 @@ func TestChannelInitializeConditions(t *testing.T) { }, want: &ChannelStatus{ Conditions: []duckv1alpha1.Condition{{ + Type: ChannelConditionAddressable, + Status: corev1.ConditionUnknown, + }, { Type: ChannelConditionProvisioned, Status: corev1.ConditionFalse, }, { Type: ChannelConditionReady, Status: corev1.ConditionUnknown, - }, { - Type: ChannelConditionSinkable, - Status: corev1.ConditionUnknown, - }, { - Type: ChannelConditionSubscribable, - Status: corev1.ConditionUnknown, }}, }, }, { @@ -140,17 +136,14 @@ func TestChannelInitializeConditions(t *testing.T) { }, want: &ChannelStatus{ Conditions: []duckv1alpha1.Condition{{ + Type: ChannelConditionAddressable, + Status: corev1.ConditionUnknown, + }, { Type: ChannelConditionProvisioned, Status: corev1.ConditionTrue, }, { Type: ChannelConditionReady, Status: corev1.ConditionUnknown, - }, { - Type: ChannelConditionSinkable, - Status: corev1.ConditionUnknown, - }, { - Type: ChannelConditionSubscribable, - Status: corev1.ConditionUnknown, }}}, }, } @@ -158,8 +151,7 @@ func TestChannelInitializeConditions(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { test.cs.InitializeConditions() - ignore := cmpopts.IgnoreFields(duckv1alpha1.Condition{}, "LastTransitionTime") - if diff := cmp.Diff(test.want, test.cs, ignore); diff != "" { + if diff := cmp.Diff(test.want, test.cs, ignoreAllButTypeAndStatus); diff != "" { t.Errorf("unexpected conditions (-want, +got) = %v", diff) } }) @@ -170,20 +162,17 @@ func TestChannelIsReady(t *testing.T) { tests := []struct { name string markProvisioned bool - setSubscribable bool - setSinkable bool + setAddress bool wantReady bool }{{ name: "all happy", markProvisioned: true, - setSubscribable: true, - setSinkable: true, + setAddress: true, wantReady: true, }, { name: "one sad", markProvisioned: false, - setSubscribable: true, - setSinkable: true, + setAddress: true, wantReady: false, }} for _, test := range tests { @@ -191,12 +180,11 @@ func TestChannelIsReady(t *testing.T) { cs := &ChannelStatus{} if test.markProvisioned { cs.MarkProvisioned() + } else { + cs.MarkNotProvisioned("NotProvisioned", "testing") } - if test.setSubscribable { - cs.SetSubscribable("foo", "bar") - } - if test.setSinkable { - cs.SetSinkable("foo.bar") + if test.setAddress { + cs.SetAddress("foo.bar") } got := cs.IsReady() if test.wantReady != got { @@ -206,79 +194,7 @@ func TestChannelIsReady(t *testing.T) { } } -func TestChannelStatus_SetSubscribable(t *testing.T) { - testCases := map[string]struct { - namespace string - name string - want *ChannelStatus - }{ - "empty namespace and name": { - want: &ChannelStatus{ - Conditions: []duckv1alpha1.Condition{ - // Note that Ready is here because when the condition is marked False, duck - // automatically sets Ready to false. - { - Type: ChannelConditionReady, - Status: corev1.ConditionFalse, - }, - { - Type: ChannelConditionSubscribable, - Status: corev1.ConditionFalse, - }, - }, - }, - }, - "empty namespace": { - name: "foobar", - want: &ChannelStatus{ - Subscribable: duckv1alpha1.Subscribable{ - Channelable: corev1.ObjectReference{ - APIVersion: SchemeGroupVersion.String(), - Kind: "Channel", - Name: "foobar", - }, - }, - Conditions: []duckv1alpha1.Condition{ - { - Type: ChannelConditionSubscribable, - Status: corev1.ConditionTrue, - }, - }, - }, - }, - "subscribable": { - namespace: "test-namespace", - name: "test-name", - want: &ChannelStatus{ - Subscribable: duckv1alpha1.Subscribable{ - Channelable: corev1.ObjectReference{ - APIVersion: SchemeGroupVersion.String(), - Kind: "Channel", - Namespace: "test-namespace", - Name: "test-name", - }, - }, - Conditions: []duckv1alpha1.Condition{ - { - Type: ChannelConditionSubscribable, - Status: corev1.ConditionTrue, - }, - }, - }, - }, - } - for n, tc := range testCases { - t.Run(n, func(t *testing.T) { - cs := &ChannelStatus{} - cs.SetSubscribable(tc.namespace, tc.name) - if diff := cmp.Diff(tc.want, cs, ignoreTransitionTimeMessageAndReason); diff != "" { - t.Errorf("unexpected conditions (-want, +got) = %v", diff) - } - }) - } -} - -func TestChannelStatus_SetSinkable(t *testing.T) { +func TestChannelStatus_SetAddressable(t *testing.T) { testCases := map[string]struct { domainInternal string want *ChannelStatus @@ -286,14 +202,14 @@ func TestChannelStatus_SetSinkable(t *testing.T) { "empty string": { want: &ChannelStatus{ Conditions: []duckv1alpha1.Condition{ - // Note that Ready is here because when the condition is marked False, duck - // automatically sets Ready to false. { - Type: ChannelConditionReady, + Type: ChannelConditionAddressable, Status: corev1.ConditionFalse, }, + // Note that Ready is here because when the condition is marked False, duck + // automatically sets Ready to false. { - Type: ChannelConditionSinkable, + Type: ChannelConditionReady, Status: corev1.ConditionFalse, }, }, @@ -302,12 +218,12 @@ func TestChannelStatus_SetSinkable(t *testing.T) { "has domain": { domainInternal: "test-domain", want: &ChannelStatus{ - Sinkable: duckv1alpha1.Sinkable{ - DomainInternal: "test-domain", + Address: duckv1alpha1.Addressable{ + Hostname: "test-domain", }, Conditions: []duckv1alpha1.Condition{ { - Type: ChannelConditionSinkable, + Type: ChannelConditionAddressable, Status: corev1.ConditionTrue, }, }, @@ -317,8 +233,8 @@ func TestChannelStatus_SetSinkable(t *testing.T) { for n, tc := range testCases { t.Run(n, func(t *testing.T) { cs := &ChannelStatus{} - cs.SetSinkable(tc.domainInternal) - if diff := cmp.Diff(tc.want, cs, ignoreTransitionTimeMessageAndReason); diff != "" { + cs.SetAddress(tc.domainInternal) + if diff := cmp.Diff(tc.want, cs, ignoreAllButTypeAndStatus); diff != "" { t.Errorf("unexpected conditions (-want, +got) = %v", diff) } }) diff --git a/pkg/apis/eventing/v1alpha1/channel_validation.go b/pkg/apis/eventing/v1alpha1/channel_validation.go index 1a41996e3ae..054526b9fe8 100644 --- a/pkg/apis/eventing/v1alpha1/channel_validation.go +++ b/pkg/apis/eventing/v1alpha1/channel_validation.go @@ -34,12 +34,12 @@ func (cs *ChannelSpec) Validate() *apis.FieldError { errs = errs.Also(apis.ErrMissingField("provisioner")) } - if cs.Channelable != nil { - for i, subscriber := range cs.Channelable.Subscribers { - if subscriber.SinkableDomain == "" && subscriber.CallableDomain == "" { - fe := apis.ErrMissingField("sinkableDomain", "callableDomain") + if cs.Subscribable != nil { + for i, subscriber := range cs.Subscribable.Subscribers { + if subscriber.ReplyURI == "" && subscriber.SubscriberURI == "" { + fe := apis.ErrMissingField("replyURI", "subscriberURI") fe.Details = "expected at least one of, got none" - errs = errs.Also(fe.ViaField(fmt.Sprintf("subscriber[%d]", i)).ViaField("channelable")) + errs = errs.Also(fe.ViaField(fmt.Sprintf("subscriber[%d]", i)).ViaField("subscribable")) } } } @@ -55,7 +55,7 @@ func (current *Channel) CheckImmutableFields(og apis.Immutable) *apis.FieldError if !ok { return &apis.FieldError{Message: "The provided resource was not a Channel"} } - ignoreArguments := cmpopts.IgnoreFields(ChannelSpec{}, "Arguments", "Channelable") + ignoreArguments := cmpopts.IgnoreFields(ChannelSpec{}, "Arguments", "Subscribable") if diff := cmp.Diff(original.Spec, current.Spec, ignoreArguments); diff != "" { return &apis.FieldError{ Message: "Immutable fields changed", diff --git a/pkg/apis/eventing/v1alpha1/channel_validation_test.go b/pkg/apis/eventing/v1alpha1/channel_validation_test.go index e72623cf818..d21159209cc 100644 --- a/pkg/apis/eventing/v1alpha1/channel_validation_test.go +++ b/pkg/apis/eventing/v1alpha1/channel_validation_test.go @@ -20,8 +20,8 @@ import ( "testing" "github.com/google/go-cmp/cmp" + eventingduck "github.com/knative/eventing/pkg/apis/duck/v1alpha1" "github.com/knative/pkg/apis" - duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" ) @@ -33,10 +33,8 @@ func TestChannelValidation(t *testing.T) { name: "valid", cr: &Channel{ Spec: ChannelSpec{ - Provisioner: &ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: "foo", - }, + Provisioner: &corev1.ObjectReference{ + Name: "foo", }, }, }, @@ -51,15 +49,13 @@ func TestChannelValidation(t *testing.T) { name: "subscribers array", cr: &Channel{ Spec: ChannelSpec{ - Provisioner: &ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: "foo", - }, + Provisioner: &corev1.ObjectReference{ + Name: "foo", }, - Channelable: &duckv1alpha1.Channelable{ - Subscribers: []duckv1alpha1.ChannelSubscriberSpec{{ - CallableDomain: "callableendpoint", - SinkableDomain: "resultendpoint", + Subscribable: &eventingduck.Subscribable{ + Subscribers: []eventingduck.ChannelSubscriberSpec{{ + SubscriberURI: "subscriberendpoint", + ReplyURI: "resultendpoint", }}, }}, }, @@ -68,20 +64,18 @@ func TestChannelValidation(t *testing.T) { name: "empty subscriber at index 1", cr: &Channel{ Spec: ChannelSpec{ - Provisioner: &ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: "foo", - }, + Provisioner: &corev1.ObjectReference{ + Name: "foo", }, - Channelable: &duckv1alpha1.Channelable{ - Subscribers: []duckv1alpha1.ChannelSubscriberSpec{{ - CallableDomain: "callableendpoint", - SinkableDomain: "callableendpoint", + Subscribable: &eventingduck.Subscribable{ + Subscribers: []eventingduck.ChannelSubscriberSpec{{ + SubscriberURI: "subscriberendpoint", + ReplyURI: "replyendpoint", }, {}}, }}, }, want: func() *apis.FieldError { - fe := apis.ErrMissingField("spec.channelable.subscriber[1].callableDomain", "spec.channelable.subscriber[1].sinkableDomain") + fe := apis.ErrMissingField("spec.subscribable.subscriber[1].replyURI", "spec.subscribable.subscriber[1].subscriberURI") fe.Details = "expected at least one of, got none" return fe }(), @@ -89,22 +83,20 @@ func TestChannelValidation(t *testing.T) { name: "2 empty subscribers", cr: &Channel{ Spec: ChannelSpec{ - Provisioner: &ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: "foo", - }, + Provisioner: &corev1.ObjectReference{ + Name: "foo", }, - Channelable: &duckv1alpha1.Channelable{ - Subscribers: []duckv1alpha1.ChannelSubscriberSpec{{}, {}}, + Subscribable: &eventingduck.Subscribable{ + Subscribers: []eventingduck.ChannelSubscriberSpec{{}, {}}, }, }, }, want: func() *apis.FieldError { var errs *apis.FieldError - fe := apis.ErrMissingField("spec.channelable.subscriber[0].callableDomain", "spec.channelable.subscriber[0].sinkableDomain") + fe := apis.ErrMissingField("spec.subscribable.subscriber[0].replyURI", "spec.subscribable.subscriber[0].subscriberURI") fe.Details = "expected at least one of, got none" errs = errs.Also(fe) - fe = apis.ErrMissingField("spec.channelable.subscriber[1].callableDomain", "spec.channelable.subscriber[1].sinkableDomain") + fe = apis.ErrMissingField("spec.subscribable.subscriber[1].replyURI", "spec.subscribable.subscriber[1].subscriberURI") fe.Details = "expected at least one of, got none" errs = errs.Also(fe) return errs @@ -124,10 +116,8 @@ func TestChannelImmutableFields(t *testing.T) { name: "good (new)", new: &Channel{ Spec: ChannelSpec{ - Provisioner: &ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: "foo", - }, + Provisioner: &corev1.ObjectReference{ + Name: "foo", }, }, }, @@ -137,19 +127,15 @@ func TestChannelImmutableFields(t *testing.T) { name: "good (no change)", new: &Channel{ Spec: ChannelSpec{ - Provisioner: &ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: "foo", - }, + Provisioner: &corev1.ObjectReference{ + Name: "foo", }, }, }, old: &Channel{ Spec: ChannelSpec{ - Provisioner: &ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: "foo", - }, + Provisioner: &corev1.ObjectReference{ + Name: "foo", }, }, }, @@ -158,10 +144,8 @@ func TestChannelImmutableFields(t *testing.T) { name: "good (arguments change)", new: &Channel{ Spec: ChannelSpec{ - Provisioner: &ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: "foo", - }, + Provisioner: &corev1.ObjectReference{ + Name: "foo", }, Arguments: &runtime.RawExtension{ Raw: []byte("\"foo\":\"bar\""), @@ -170,10 +154,8 @@ func TestChannelImmutableFields(t *testing.T) { }, old: &Channel{ Spec: ChannelSpec{ - Provisioner: &ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: "foo", - }, + Provisioner: &corev1.ObjectReference{ + Name: "foo", }, Arguments: &runtime.RawExtension{ Raw: []byte(`{"foo":"baz"}`), @@ -185,10 +167,8 @@ func TestChannelImmutableFields(t *testing.T) { name: "bad (not channel)", new: &Channel{ Spec: ChannelSpec{ - Provisioner: &ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: "foo", - }, + Provisioner: &corev1.ObjectReference{ + Name: "foo", }, }, }, @@ -200,19 +180,15 @@ func TestChannelImmutableFields(t *testing.T) { name: "bad (provisioner changes)", new: &Channel{ Spec: ChannelSpec{ - Provisioner: &ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: "foo", - }, + Provisioner: &corev1.ObjectReference{ + Name: "foo", }, }, }, old: &Channel{ Spec: ChannelSpec{ - Provisioner: &ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: "bar", - }, + Provisioner: &corev1.ObjectReference{ + Name: "bar", }, }, }, diff --git a/pkg/apis/eventing/v1alpha1/cluster_provisioner_defaults.go b/pkg/apis/eventing/v1alpha1/cluster_channel_provisioner_defaults.go similarity index 79% rename from pkg/apis/eventing/v1alpha1/cluster_provisioner_defaults.go rename to pkg/apis/eventing/v1alpha1/cluster_channel_provisioner_defaults.go index c5b74ae0da6..59a8089676f 100644 --- a/pkg/apis/eventing/v1alpha1/cluster_provisioner_defaults.go +++ b/pkg/apis/eventing/v1alpha1/cluster_channel_provisioner_defaults.go @@ -17,11 +17,11 @@ limitations under the License. package v1alpha1 // SetDefaults defaults -func (p *ClusterProvisioner) SetDefaults() { +func (p *ClusterChannelProvisioner) SetDefaults() { p.Spec.SetDefaults() } -// SetDefaults defaults the ClusterProvisioner spec. -func (ps *ClusterProvisionerSpec) SetDefaults() { +// SetDefaults defaults the ClusterChannelProvisioner spec. +func (ps *ClusterChannelProvisionerSpec) SetDefaults() { // no defaults } diff --git a/pkg/apis/eventing/v1alpha1/cluster_provisioner_defaults_test.go b/pkg/apis/eventing/v1alpha1/cluster_channel_provisioner_defaults_test.go similarity index 87% rename from pkg/apis/eventing/v1alpha1/cluster_provisioner_defaults_test.go rename to pkg/apis/eventing/v1alpha1/cluster_channel_provisioner_defaults_test.go index f193167fa2b..565b2b4a91f 100644 --- a/pkg/apis/eventing/v1alpha1/cluster_provisioner_defaults_test.go +++ b/pkg/apis/eventing/v1alpha1/cluster_channel_provisioner_defaults_test.go @@ -19,7 +19,7 @@ package v1alpha1 import "testing" // No-op test because method does nothing. -func TestClusterProvisionerSetDefaults(t *testing.T) { - p := ClusterProvisioner{} +func TestClusterChannelProvisionerSetDefaults(t *testing.T) { + p := ClusterChannelProvisioner{} p.SetDefaults() } diff --git a/pkg/apis/eventing/v1alpha1/cluster_provisioner_types.go b/pkg/apis/eventing/v1alpha1/cluster_channel_provisioner_types.go similarity index 50% rename from pkg/apis/eventing/v1alpha1/cluster_provisioner_types.go rename to pkg/apis/eventing/v1alpha1/cluster_channel_provisioner_types.go index 6a0a32ecb0b..751925c66eb 100644 --- a/pkg/apis/eventing/v1alpha1/cluster_provisioner_types.go +++ b/pkg/apis/eventing/v1alpha1/cluster_channel_provisioner_types.go @@ -30,93 +30,93 @@ import ( // +genclient:nonNamespaced // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// ClusterProvisioner encapsulates a provisioning strategy for the backing -// resources required to realize a particular resource type. -type ClusterProvisioner struct { +// ClusterChannelProvisioner encapsulates a provisioning strategy for the +// backing resources required to realize a particular resource type. +type ClusterChannelProvisioner struct { metav1.TypeMeta `json:",inline"` // +optional metav1.ObjectMeta `json:"metadata,omitempty"` // Spec defines the Types provisioned by this Provisioner. - Spec ClusterProvisionerSpec `json:"spec"` + Spec ClusterChannelProvisionerSpec `json:"spec"` // Status is the current status of the Provisioner. // +optional - Status ClusterProvisionerStatus `json:"status,omitempty"` + Status ClusterChannelProvisionerStatus `json:"status,omitempty"` } -// Check that ClusterProvisioner can be validated and can be defaulted. -var _ apis.Validatable = (*ClusterProvisioner)(nil) -var _ apis.Defaultable = (*ClusterProvisioner)(nil) -var _ runtime.Object = (*ClusterProvisioner)(nil) -var _ webhook.GenericCRD = (*ClusterProvisioner)(nil) +// Check that ClusterChannelProvisioner can be validated and can be defaulted. +var _ apis.Validatable = (*ClusterChannelProvisioner)(nil) +var _ apis.Defaultable = (*ClusterChannelProvisioner)(nil) +var _ runtime.Object = (*ClusterChannelProvisioner)(nil) +var _ webhook.GenericCRD = (*ClusterChannelProvisioner)(nil) -// ClusterProvisionerSpec is the spec for a ClusterProvisioner resource. -type ClusterProvisionerSpec struct { +// ClusterChannelProvisionerSpec is the spec for a ClusterChannelProvisioner resource. +type ClusterChannelProvisionerSpec struct { // TODO: Generation does not work correctly with CRD. They are scrubbed // by the APIserver (https://github.com/kubernetes/kubernetes/issues/58778) // So, we add Generation here. Once that gets fixed, remove this and use // ObjectMeta.Generation instead. // +optional Generation int64 `json:"generation,omitempty"` - - // Reconciles is the kind of the resource the provisioner controller watches to - // produce required backing resources. - // +required - Reconciles metav1.GroupKind `json:"reconciles"` } -var cProvCondSet = duckv1alpha1.NewLivingConditionSet() +var ccProvCondSet = duckv1alpha1.NewLivingConditionSet() -// ClusterProvisionerStatus is the status for a ClusterProvisioner resource -type ClusterProvisionerStatus struct { +// ClusterChannelProvisionerStatus is the status for a ClusterChannelProvisioner resource +type ClusterChannelProvisionerStatus struct { // Conditions holds the state of a cluster provisioner at a point in time. // +optional // +patchMergeKey=type // +patchStrategy=merge Conditions duckv1alpha1.Conditions `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` - // ObservedGeneration is the 'Generation' of the ClusterProvisioner that + // ObservedGeneration is the 'Generation' of the ClusterChannelProvisioner that // was last reconciled by the controller. // +optional ObservedGeneration int64 `json:"observedGeneration,omitempty"` } const ( - // ClusterProvisionerConditionReady has status True when the Controller reconciling objects + // ClusterChannelProvisionerConditionReady has status True when the Controller reconciling objects // controlled by it is ready to control them. - ClusterProvisionerConditionReady = duckv1alpha1.ConditionReady + ClusterChannelProvisionerConditionReady = duckv1alpha1.ConditionReady ) // GetCondition returns the condition currently associated with the given type, or nil. -func (ps *ClusterProvisionerStatus) GetCondition(t duckv1alpha1.ConditionType) *duckv1alpha1.Condition { - return cProvCondSet.Manage(ps).GetCondition(t) +func (ps *ClusterChannelProvisionerStatus) GetCondition(t duckv1alpha1.ConditionType) *duckv1alpha1.Condition { + return ccProvCondSet.Manage(ps).GetCondition(t) } // IsReady returns true if the resource is ready overall. -func (ps *ClusterProvisionerStatus) IsReady() bool { - return cProvCondSet.Manage(ps).IsHappy() +func (ps *ClusterChannelProvisionerStatus) IsReady() bool { + return ccProvCondSet.Manage(ps).IsHappy() +} + +// MarkProvisionerNotReady sets the condition that the provisioner is not ready to provision backing resource. +func (ps *ClusterChannelProvisionerStatus) MarkNotReady(reason, messageFormat string, messageA ...interface{}) { + ccProvCondSet.Manage(ps).MarkFalse(ClusterChannelProvisionerConditionReady, reason, messageFormat, messageA...) } // InitializeConditions sets relevant unset conditions to Unknown state. -func (ps *ClusterProvisionerStatus) InitializeConditions() { - cProvCondSet.Manage(ps).InitializeConditions() +func (ps *ClusterChannelProvisionerStatus) InitializeConditions() { + ccProvCondSet.Manage(ps).InitializeConditions() } -// MarkReady marks this ClusterProvisioner as Ready=true. +// MarkReady marks this ClusterChannelProvisioner as Ready=true. // // Note that this is not the normal pattern for duck conditions, but because there is (currently) -// no other condition on ClusterProvisioners, the normal IsReady() logic doesn't work well. -func (ps *ClusterProvisionerStatus) MarkReady() { - cProvCondSet.Manage(ps).MarkTrue(ClusterProvisionerConditionReady) +// no other condition on ClusterChannelProvisioners, the normal IsReady() logic doesn't work well. +func (ps *ClusterChannelProvisionerStatus) MarkReady() { + ccProvCondSet.Manage(ps).MarkTrue(ClusterChannelProvisionerConditionReady) } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// ClusterProvisionerList is a list of ClusterProvisioner resources -type ClusterProvisionerList struct { +// ClusterChannelProvisionerList is a list of ClusterChannelProvisioner resources +type ClusterChannelProvisionerList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata"` - Items []ClusterProvisioner `json:"items"` + Items []ClusterChannelProvisioner `json:"items"` } diff --git a/pkg/apis/eventing/v1alpha1/cluster_provisioner_types_test.go b/pkg/apis/eventing/v1alpha1/cluster_channel_provisioner_types_test.go similarity index 71% rename from pkg/apis/eventing/v1alpha1/cluster_provisioner_types_test.go rename to pkg/apis/eventing/v1alpha1/cluster_channel_provisioner_types_test.go index afb7e8a0ff9..c7943ee0d6e 100644 --- a/pkg/apis/eventing/v1alpha1/cluster_provisioner_types_test.go +++ b/pkg/apis/eventing/v1alpha1/cluster_channel_provisioner_types_test.go @@ -24,44 +24,44 @@ import ( corev1 "k8s.io/api/core/v1" ) -func TestClusterProvisionerStatusIsReady(t *testing.T) { +func TestClusterChannelProvisionerStatusIsReady(t *testing.T) { tests := []struct { name string - ps *ClusterProvisionerStatus + ps *ClusterChannelProvisionerStatus want bool }{{ name: "uninitialized", - ps: &ClusterProvisionerStatus{}, + ps: &ClusterChannelProvisionerStatus{}, want: false, }, { name: "initialized", - ps: func() *ClusterProvisionerStatus { - ps := &ClusterProvisionerStatus{} + ps: func() *ClusterChannelProvisionerStatus { + ps := &ClusterChannelProvisionerStatus{} ps.InitializeConditions() return ps }(), want: false, }, { name: "ready true condition", - ps: &ClusterProvisionerStatus{ - Conditions: []duckv1alpha1.Condition{{ - Type: ChannelConditionReady, - Status: corev1.ConditionTrue, - }}, - }, + ps: func() *ClusterChannelProvisionerStatus { + ps := &ClusterChannelProvisionerStatus{} + ps.InitializeConditions() + ps.MarkReady() + return ps + }(), want: true, }, { name: "ready false condition", - ps: &ClusterProvisionerStatus{ - Conditions: []duckv1alpha1.Condition{{ - Type: ChannelConditionReady, - Status: corev1.ConditionFalse, - }}, - }, + ps: func() *ClusterChannelProvisionerStatus { + ps := &ClusterChannelProvisionerStatus{} + ps.InitializeConditions() + ps.MarkNotReady("Not Ready", "testing") + return ps + }(), want: false, }, { name: "unknown condition", - ps: &ClusterProvisionerStatus{ + ps: &ClusterChannelProvisionerStatus{ Conditions: []duckv1alpha1.Condition{{ Type: "foo", Status: corev1.ConditionTrue, @@ -80,15 +80,15 @@ func TestClusterProvisionerStatusIsReady(t *testing.T) { } } -func TestClusterProvisionerStatusGetCondition(t *testing.T) { +func TestClusterChannelProvisionerStatusGetCondition(t *testing.T) { tests := []struct { name string - ps *ClusterProvisionerStatus + ps *ClusterChannelProvisionerStatus condQuery duckv1alpha1.ConditionType want *duckv1alpha1.Condition }{{ name: "single condition", - ps: &ClusterProvisionerStatus{ + ps: &ClusterChannelProvisionerStatus{ Conditions: []duckv1alpha1.Condition{ condReady, }, @@ -97,7 +97,7 @@ func TestClusterProvisionerStatusGetCondition(t *testing.T) { want: &condReady, }, { name: "unknown condition", - ps: &ClusterProvisionerStatus{ + ps: &ClusterChannelProvisionerStatus{ Conditions: []duckv1alpha1.Condition{ condReady, condUnprovisioned, @@ -117,8 +117,8 @@ func TestClusterProvisionerStatusGetCondition(t *testing.T) { } } -func TestClusterProvisionerStatus_MarkReady(t *testing.T) { - ps := ClusterProvisionerStatus{} +func TestClusterChannelProvisionerStatus_MarkReady(t *testing.T) { + ps := ClusterChannelProvisionerStatus{} ps.InitializeConditions() if ps.IsReady() { t.Errorf("Should not be ready when initialized.") diff --git a/pkg/apis/feeds/v1alpha1/cluster_event_source_validation.go b/pkg/apis/eventing/v1alpha1/cluster_channel_provisioner_validation.go similarity index 65% rename from pkg/apis/feeds/v1alpha1/cluster_event_source_validation.go rename to pkg/apis/eventing/v1alpha1/cluster_channel_provisioner_validation.go index 96451fc1d5d..748786777af 100644 --- a/pkg/apis/feeds/v1alpha1/cluster_event_source_validation.go +++ b/pkg/apis/eventing/v1alpha1/cluster_channel_provisioner_validation.go @@ -20,10 +20,14 @@ import ( "github.com/knative/pkg/apis" ) -func (es *ClusterEventSource) Validate() *apis.FieldError { - return es.Spec.Validate().ViaField("spec") +// Validate validates the ClusterChannelProvisioner resource. +func (p *ClusterChannelProvisioner) Validate() *apis.FieldError { + return p.Spec.Validate().ViaField("spec") } -func (ess *ClusterEventSourceSpec) Validate() *apis.FieldError { - return ess.CommonEventSourceSpec.Validate() +// Validate validates the ClusterChannelProvisioner spec +func (ps *ClusterChannelProvisionerSpec) Validate() *apis.FieldError { + var errs *apis.FieldError + + return errs } diff --git a/pkg/apis/channels/v1alpha1/channel_validation_test.go b/pkg/apis/eventing/v1alpha1/cluster_channel_provisioner_validation_test.go similarity index 55% rename from pkg/apis/channels/v1alpha1/channel_validation_test.go rename to pkg/apis/eventing/v1alpha1/cluster_channel_provisioner_validation_test.go index 1f70b64dcf6..8a6639512c1 100644 --- a/pkg/apis/channels/v1alpha1/channel_validation_test.go +++ b/pkg/apis/eventing/v1alpha1/cluster_channel_provisioner_validation_test.go @@ -17,52 +17,32 @@ limitations under the License. package v1alpha1 import ( + "testing" + "github.com/google/go-cmp/cmp" "github.com/knative/pkg/apis" - "testing" ) -func TestChannelSpecValidation(t *testing.T) { +func TestClusterChannelProvisionerValidate(t *testing.T) { tests := []struct { name string - c *ChannelSpec + p *ClusterChannelProvisioner want *apis.FieldError }{{ - name: "namespace valid", - c: &ChannelSpec{ - Bus: "foo", - }, - want: nil, - }, { - name: "cluster valid", - c: &ChannelSpec{ - ClusterBus: "bar", + name: "valid", + p: &ClusterChannelProvisioner{ + Spec: ClusterChannelProvisionerSpec{}, }, - want: nil, }, { name: "empty", - c: &ChannelSpec{}, - want: apis.ErrMissingOneOf("bus", "clusterBus"), - }, { - name: "mutually exclusive missing", - c: &ChannelSpec{ - Arguments: &[]Argument{{Name: "foo", Value: "bar"}}, - }, - want: apis.ErrMissingOneOf("bus", "clusterBus"), - }, { - name: "mutually exclusive both", - c: &ChannelSpec{ - Bus: "foo", - ClusterBus: "bar", - }, - want: apis.ErrMultipleOneOf("bus", "clusterBus"), + p: &ClusterChannelProvisioner{}, }} for _, test := range tests { t.Run(test.name, func(t *testing.T) { - got := test.c.Validate() + got := test.p.Validate() if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { - t.Errorf("validateChannel (-want, +got) = %v", diff) + t.Errorf("validate (-want, +got) = %v", diff) } }) } diff --git a/pkg/apis/eventing/v1alpha1/cluster_provisioner_validation.go b/pkg/apis/eventing/v1alpha1/cluster_provisioner_validation.go deleted file mode 100644 index c46e166819f..00000000000 --- a/pkg/apis/eventing/v1alpha1/cluster_provisioner_validation.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "github.com/knative/pkg/apis" - "k8s.io/apimachinery/pkg/api/equality" -) - -// Validate validates the ClusterProvisioner resource. -func (p *ClusterProvisioner) Validate() *apis.FieldError { - return p.Spec.Validate().ViaField("spec") -} - -// Validate validates the ClusterProvisioner spec -func (ps *ClusterProvisionerSpec) Validate() *apis.FieldError { - if equality.Semantic.DeepEqual(ps, &ClusterProvisionerSpec{}) { - return apis.ErrMissingField("reconciles") - } - var errs *apis.FieldError - if ps.Reconciles.Kind == "" { - errs = errs.Also(apis.ErrMissingField("kind").ViaField("reconciles")) - } - if ps.Reconciles.Group == "" { - errs = errs.Also(apis.ErrMissingField("group").ViaField("reconciles")) - } - - return errs -} diff --git a/pkg/apis/eventing/v1alpha1/cluster_provisioner_validation_test.go b/pkg/apis/eventing/v1alpha1/cluster_provisioner_validation_test.go deleted file mode 100644 index 7d77e4a6d8c..00000000000 --- a/pkg/apis/eventing/v1alpha1/cluster_provisioner_validation_test.go +++ /dev/null @@ -1,83 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "github.com/google/go-cmp/cmp" - "github.com/knative/pkg/apis" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "testing" -) - -func TestClusterProvisionerValidate(t *testing.T) { - tests := []struct { - name string - p *ClusterProvisioner - want *apis.FieldError - }{{ - name: "valid", - p: &ClusterProvisioner{ - Spec: ClusterProvisionerSpec{ - Reconciles: metav1.GroupKind{ - Group: "knative.dev", - Kind: "Channel", - }, - }, - }, - }, { - name: "invalid cluster provisioner, empty reconciles", - p: &ClusterProvisioner{ - Spec: ClusterProvisionerSpec{ - Reconciles: metav1.GroupKind{}, - }, - }, - want: apis.ErrMissingField("spec.reconciles"), - }, { - name: "invalid cluster provisioner, empty kind", - p: &ClusterProvisioner{ - Spec: ClusterProvisionerSpec{ - Reconciles: metav1.GroupKind{ - Group: "eventing.knative.test", - }, - }, - }, - want: apis.ErrMissingField("spec.reconciles.kind"), - }, { - name: "invalid cluster provisioner", - p: &ClusterProvisioner{ - Spec: ClusterProvisionerSpec{ - Reconciles: metav1.GroupKind{ - Kind: "Channel", - }, - }, - }, - want: apis.ErrMissingField("spec.reconciles.group"), - }, { - name: "empty", - p: &ClusterProvisioner{}, - want: apis.ErrMissingField("spec.reconciles"), - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.p.Validate() - if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { - t.Errorf("validate (-want, +got) = %v", diff) - } - }) - } -} diff --git a/pkg/apis/eventing/v1alpha1/doc.go b/pkg/apis/eventing/v1alpha1/doc.go index b2c114bfe8a..e080fe737d2 100644 --- a/pkg/apis/eventing/v1alpha1/doc.go +++ b/pkg/apis/eventing/v1alpha1/doc.go @@ -10,7 +10,8 @@ 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. */ -// +k8s:deepcopy-gen=package + // Package v1alpha1 is the v1alpha1 version of the API. +// +k8s:deepcopy-gen=package // +groupName=eventing.knative.dev package v1alpha1 diff --git a/pkg/apis/eventing/v1alpha1/implements_test.go b/pkg/apis/eventing/v1alpha1/implements_test.go index 7b40b2d9af3..84768e12091 100644 --- a/pkg/apis/eventing/v1alpha1/implements_test.go +++ b/pkg/apis/eventing/v1alpha1/implements_test.go @@ -15,6 +15,7 @@ package v1alpha1 import ( "testing" + eventingduck "github.com/knative/eventing/pkg/apis/duck/v1alpha1" "github.com/knative/pkg/apis/duck" duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" ) @@ -27,15 +28,14 @@ func TestTypesImplements(t *testing.T) { }{ // Channel {instance: &Channel{}, iface: &duckv1alpha1.Conditions{}}, - {instance: &Channel{}, iface: &duckv1alpha1.Channelable{}}, - {instance: &Channel{}, iface: &duckv1alpha1.Subscribable{}}, - {instance: &Channel{}, iface: &duckv1alpha1.Sinkable{}}, - // ClusterProvisioner - {instance: &ClusterProvisioner{}, iface: &duckv1alpha1.Conditions{}}, + {instance: &Channel{}, iface: &emptyGen}, + {instance: &Channel{}, iface: &eventingduck.Subscribable{}}, + {instance: &Channel{}, iface: &duckv1alpha1.Addressable{}}, + // ClusterChannelProvisioner + {instance: &ClusterChannelProvisioner{}, iface: &duckv1alpha1.Conditions{}}, // Subscription {instance: &Subscription{}, iface: &duckv1alpha1.Conditions{}}, {instance: &Subscription{}, iface: &emptyGen}, - {instance: &Subscription{}, iface: &duckv1alpha1.Subscribable{}}, } for _, tc := range testCases { if err := duck.VerifyType(tc.instance, tc.iface); err != nil { diff --git a/pkg/apis/eventing/v1alpha1/provisioner_reference.go b/pkg/apis/eventing/v1alpha1/provisioner_reference.go deleted file mode 100644 index 1d0bbca4cbe..00000000000 --- a/pkg/apis/eventing/v1alpha1/provisioner_reference.go +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2018 The Knative Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package v1alpha1 - -import ( - corev1 "k8s.io/api/core/v1" -) - -// ProvisionerReference defines the strategy for selecting a Provisioner for a -// provisioned resource. Shared by Channel and Source. -type ProvisionerReference struct { - // A reference to a specific Provisioner. - //TODO: +optional add selector - Ref *corev1.ObjectReference `json:"ref,omitempty"` -} diff --git a/pkg/apis/eventing/v1alpha1/register.go b/pkg/apis/eventing/v1alpha1/register.go index e3fb19db05d..df6338f66c1 100644 --- a/pkg/apis/eventing/v1alpha1/register.go +++ b/pkg/apis/eventing/v1alpha1/register.go @@ -47,8 +47,8 @@ func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes(SchemeGroupVersion, &Channel{}, &ChannelList{}, - &ClusterProvisioner{}, - &ClusterProvisionerList{}, + &ClusterChannelProvisioner{}, + &ClusterChannelProvisionerList{}, &Subscription{}, &SubscriptionList{}, ) diff --git a/pkg/apis/eventing/v1alpha1/register_test.go b/pkg/apis/eventing/v1alpha1/register_test.go new file mode 100644 index 00000000000..0f7133addc1 --- /dev/null +++ b/pkg/apis/eventing/v1alpha1/register_test.go @@ -0,0 +1,69 @@ +/* +Copyright 2018 The Knative Authors +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package v1alpha1 + +import ( + "github.com/google/go-cmp/cmp" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "testing" +) + +// Resource takes an unqualified resource and returns a Group qualified GroupResource +func TestResource(t *testing.T) { + want := schema.GroupResource{ + Group: "eventing.knative.dev", + Resource: "foo", + } + + got := Resource("foo") + + if diff := cmp.Diff(want, got); diff != "" { + t.Errorf("unexpected resource (-want, +got) = %v", diff) + } +} + +// Kind takes an unqualified resource and returns a Group qualified GroupKind +func TestKind(t *testing.T) { + want := schema.GroupKind{ + Group: "eventing.knative.dev", + Kind: "kind", + } + + got := Kind("kind") + + if diff := cmp.Diff(want, got); diff != "" { + t.Errorf("unexpected resource (-want, +got) = %v", diff) + } +} + +// TestKnownTypes makes sure that expected types get added. +func TestKnownTypes(t *testing.T) { + scheme := runtime.NewScheme() + addKnownTypes(scheme) + types := scheme.KnownTypes(SchemeGroupVersion) + + for _, name := range []string{ + "Channel", + "ChannelList", + "ClusterChannelProvisioner", + "ClusterChannelProvisionerList", + "Subscription", + "SubscriptionList", + } { + if _, ok := types[name]; !ok { + t.Errorf("Did not find %q as registered type", name) + } + } + +} diff --git a/pkg/apis/eventing/v1alpha1/source_defaults.go b/pkg/apis/eventing/v1alpha1/source_defaults.go deleted file mode 100644 index 9d417f8e35a..00000000000 --- a/pkg/apis/eventing/v1alpha1/source_defaults.go +++ /dev/null @@ -1,27 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -// SetDefaults defaults -func (s *Source) SetDefaults() { - s.Spec.SetDefaults() -} - -// SetDefaults defaults the Source spec. -func (ss *SourceSpec) SetDefaults() { - // no defaults -} diff --git a/pkg/apis/eventing/v1alpha1/source_types.go b/pkg/apis/eventing/v1alpha1/source_types.go deleted file mode 100644 index 5b58b416b95..00000000000 --- a/pkg/apis/eventing/v1alpha1/source_types.go +++ /dev/null @@ -1,156 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "github.com/knative/pkg/apis/duck" - duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" - "github.com/knative/pkg/webhook" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/runtime" -) - -// +genclient -// +genclient:noStatus -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// Source resource Describes a specific configuration (credentials, etc) of a -// source system which can be used to supply events. Sources emit events using a -// channel specified in their status. They cannot receive events. -type Source struct { - metav1.TypeMeta `json:",inline"` - // +optional - metav1.ObjectMeta `json:"metadata,omitempty"` - - // Spec defines the the Provisioner and arguments provided for this Source. - Spec SourceSpec `json:"spec"` - - // Status is the current status of the Source. - // +optional - Status SourceStatus `json:"status,omitempty"` -} - -// Check that Source can be validated and can be defaulted. -var _ webhook.GenericCRD = (*Source)(nil) - -// Check that Source implements the Conditions duck type. -var _ = duck.VerifyType(&Source{}, &duckv1alpha1.Conditions{}) - -// Check that Source implements the Generation duck type. -var emptyGenSource duckv1alpha1.Generation -var _ = duck.VerifyType(&Source{}, &emptyGenSource) - -// And it's Subscribable -var _ = duck.VerifyType(&Subscription{}, &duckv1alpha1.Subscribable{}) - -// SourceSpec is the spec for a Source resource. -type SourceSpec struct { - // TODO: Generation does not work correctly with CRD. They are scrubbed - // by the APIserver (https://github.com/kubernetes/kubernetes/issues/58778) - // So, we add Generation here. Once that gets fixed, remove this and use - // ObjectMeta.Generation instead. - // +optional - Generation int64 `json:"generation,omitempty"` - - // Provisioner is used to create any backing resources and configuration. - // +required - Provisioner *ProvisionerReference `json:"provisioner,omitempty"` - - // Arguments defines the arguments to pass to the Provisioner which provisions - // this Source. - // +optional - Arguments *runtime.RawExtension `json:"arguments,omitempty"` - - // Specify an existing channel to use to emit events. If empty, create a new - // Channel using the cluster/namespace default. - // - // This object must fulfill the Channelable contract. - // - // You can specify only the following fields of the ObjectReference: - // - Kind - // - APIVersion - // - Name - // Currently Kind must be "Channel" and - // APIVersion must be "eventing.knative.dev/v1alpha1" - // +optional - Channel *corev1.ObjectReference `json:"target,omitempty"` -} - -const ( - // SourceConditionReady has status True when the Source is ready to send events. - SourceConditionReady = duckv1alpha1.ConditionReady - - // SourceConditionProvisioned has status True when the Source's backing - // resources have been provisioned. - SourceConditionProvisioned duckv1alpha1.ConditionType = "Provisioned" -) - -var sourceCondSet = duckv1alpha1.NewLivingConditionSet(SourceConditionProvisioned) - -// SourceStatus is the status for a Source resource -type SourceStatus struct { - // Conditions holds the state of a source at a point in time. - // +optional - // +patchMergeKey=type - // +patchStrategy=merge - Conditions duckv1alpha1.Conditions `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` - - // ObservedGeneration is the 'Generation' of the Source that - // was last reconciled by the controller. - // +optional - ObservedGeneration int64 `json:"observedGeneration,omitempty"` - - // Source might be Subscribable. This points to the Channelable object. - Subscribable duckv1alpha1.Subscribable `json:"subscribable,omitempty"` -} - -// GetCondition returns the condition currently associated with the given type, or nil. -func (ss *SourceStatus) GetCondition(t duckv1alpha1.ConditionType) *duckv1alpha1.Condition { - return sourceCondSet.Manage(ss).GetCondition(t) -} - -// IsReady returns true if the resource is ready overall. -func (ss *SourceStatus) IsReady() bool { - return sourceCondSet.Manage(ss).IsHappy() -} - -// InitializeConditions sets relevant unset conditions to Unknown state. -func (ss *SourceStatus) InitializeConditions() { - sourceCondSet.Manage(ss).InitializeConditions() -} - -// MarkProvisioned sets the condition that the source has had its backing resources created. -func (ss *SourceStatus) MarkProvisioned() { - sourceCondSet.Manage(ss).MarkTrue(SourceConditionProvisioned) -} - -// MarkDeprovisioned sets the condition that the source has had its backing resources removed. -func (ss *SourceStatus) MarkDeprovisioned(reason, messageFormat string, messageA ...interface{}) { - sourceCondSet.Manage(ss).MarkFalse(SourceConditionProvisioned, reason, messageFormat, messageA...) -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// SourceList is a list of Source resources -type SourceList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []Source `json:"items"` -} diff --git a/pkg/apis/eventing/v1alpha1/source_types_test.go b/pkg/apis/eventing/v1alpha1/source_types_test.go deleted file mode 100644 index 380e0c98324..00000000000 --- a/pkg/apis/eventing/v1alpha1/source_types_test.go +++ /dev/null @@ -1,142 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "testing" - - "github.com/google/go-cmp/cmp" - duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" - corev1 "k8s.io/api/core/v1" -) - -func TestSourceStatusIsReady(t *testing.T) { - tests := []struct { - name string - s *SourceStatus - want bool - }{{ - name: "uninitialized", - s: &SourceStatus{}, - want: false, - }, { - name: "initialized", - s: func() *SourceStatus { - s := &SourceStatus{} - s.InitializeConditions() - return s - }(), - want: false, - }, { - name: "ready true condition", - s: &SourceStatus{ - Conditions: []duckv1alpha1.Condition{{ - Type: SourceConditionReady, - Status: corev1.ConditionTrue, - }, { - Type: SourceConditionProvisioned, - Status: corev1.ConditionTrue, - }}, - }, - want: true, - }, { - name: "ready false condition", - s: &SourceStatus{ - Conditions: []duckv1alpha1.Condition{{ - Type: SourceConditionReady, - Status: corev1.ConditionFalse, - }, { - Type: SourceConditionProvisioned, - Status: corev1.ConditionTrue, - }}, - }, - want: false, - }, { - name: "unknown condition", - s: &SourceStatus{ - Conditions: []duckv1alpha1.Condition{{ - Type: "foo", - Status: corev1.ConditionTrue, - }}, - }, - want: false, - }, { - name: "mark provisioned", - s: func() *SourceStatus { - s := &SourceStatus{} - s.InitializeConditions() - s.MarkProvisioned() - return s - }(), - want: true, - }, { - name: "mark deprovisioned", - s: func() *SourceStatus { - s := &SourceStatus{} - s.InitializeConditions() - s.MarkDeprovisioned("Testing", "Just a test") - return s - }(), - want: false, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.s.IsReady() - if diff := cmp.Diff(test.want, got); diff != "" { - t.Errorf("%s: unexpected condition (-want, +got) = %v", test.name, diff) - } - }) - } -} - -func TestSourceStatusGetCondition(t *testing.T) { - tests := []struct { - name string - s *SourceStatus - condQuery duckv1alpha1.ConditionType - want *duckv1alpha1.Condition - }{{ - name: "single condition", - s: &SourceStatus{ - Conditions: []duckv1alpha1.Condition{ - condReady, - }, - }, - condQuery: duckv1alpha1.ConditionReady, - want: &condReady, - }, { - name: "unknown condition", - s: &SourceStatus{ - Conditions: []duckv1alpha1.Condition{ - condReady, - condUnprovisioned, - }, - }, - condQuery: duckv1alpha1.ConditionType("foo"), - want: nil, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.s.GetCondition(test.condQuery) - if diff := cmp.Diff(test.want, got); diff != "" { - t.Errorf("unexpected condition (-want, +got) = %v", diff) - } - }) - } -} diff --git a/pkg/apis/eventing/v1alpha1/source_validation.go b/pkg/apis/eventing/v1alpha1/source_validation.go deleted file mode 100644 index 5876a2a108c..00000000000 --- a/pkg/apis/eventing/v1alpha1/source_validation.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "github.com/knative/pkg/apis" - "k8s.io/apimachinery/pkg/api/equality" -) - -// Validate validates the Source resource. -func (s *Source) Validate() *apis.FieldError { - return s.Spec.Validate().ViaField("spec") -} - -// Validate validates the Source spec -func (ss *SourceSpec) Validate() *apis.FieldError { - if equality.Semantic.DeepEqual(ss, &SourceSpec{}) { - return apis.ErrMissingField("provisioner") - } - var errs *apis.FieldError - - if ss.Channel != nil && !isChannelableEmpty(*ss.Channel) { - errs = errs.Also(isValidChannelable(*ss.Channel).ViaField("channel")) - } - - // TODO: could validate that arguments are json if that is a requirement. - - return errs -} diff --git a/pkg/apis/eventing/v1alpha1/source_validation_test.go b/pkg/apis/eventing/v1alpha1/source_validation_test.go deleted file mode 100644 index 212a24ad9a3..00000000000 --- a/pkg/apis/eventing/v1alpha1/source_validation_test.go +++ /dev/null @@ -1,110 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "testing" - - "github.com/knative/pkg/apis" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/runtime" -) - -func TestSourceValidate(t *testing.T) { - tests := []CRDTest{{ - name: "empty", - cr: &Source{ - Spec: SourceSpec{}, - }, - want: apis.ErrMissingField("spec.provisioner"), - }, { - name: "minimum valid", - cr: &Source{ - Spec: SourceSpec{ - Provisioner: &ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: "foo", - }, - }, - }, - }, - }, { - name: "full valid", - cr: &Source{ - Spec: SourceSpec{ - Provisioner: &ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: "foo", - }, - }, - Arguments: &runtime.RawExtension{ - Raw: []byte(`{"foo":"baz"}`), - }, - Channel: &corev1.ObjectReference{ - Name: "bar", - Kind: "Channel", - APIVersion: "eventing.knative.dev/v1alpha1", - }, - }, - }, - }, { - name: "invalid, set extra channel parameters", - cr: &Source{ - Spec: SourceSpec{ - Provisioner: &ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: "foo", - }, - }, - Channel: &corev1.ObjectReference{ - Name: "bar", - Kind: "Channel", - APIVersion: "eventing.knative.dev/v1alpha1", - ResourceVersion: "SoMad", - }, - }, - }, - want: &apis.FieldError{ - Message: "must not set the field(s)", - Paths: []string{"spec.channel.ResourceVersion"}, - Details: "only name, apiVersion and kind are supported fields", - }, - }, { - name: "invalid, set extra channel as not a channel", - cr: &Source{ - Spec: SourceSpec{ - Provisioner: &ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: "foo", - }, - }, - Channel: &corev1.ObjectReference{ - Name: "backwards", - Kind: "lennahC", - APIVersion: "eventing.knative.dev/v1alpha1", - }, - }, - }, - want: &apis.FieldError{ - Message: "invalid value \"lennahC\"", - Paths: []string{"spec.channel.kind"}, - Details: "only 'Channel' kind is allowed", - }, - }} - - doValidateTest(t, tests) -} diff --git a/pkg/apis/eventing/v1alpha1/subscribable_channelable_validation.go b/pkg/apis/eventing/v1alpha1/subscribable_channelable_validation.go index 7918fc3d481..b415b68a183 100644 --- a/pkg/apis/eventing/v1alpha1/subscribable_channelable_validation.go +++ b/pkg/apis/eventing/v1alpha1/subscribable_channelable_validation.go @@ -25,7 +25,7 @@ import ( "k8s.io/apimachinery/pkg/api/equality" ) -func isSubscribableEmpty(f corev1.ObjectReference) bool { +func isChannelEmpty(f corev1.ObjectReference) bool { return equality.Semantic.DeepEqual(f, corev1.ObjectReference{}) } @@ -33,32 +33,7 @@ func isSubscribableEmpty(f corev1.ObjectReference) bool { // - Kind == 'Channel' // - APIVersion == 'eventing.knative.dev/v1alpha1' // - Name == not empty -func isValidSubscribable(f corev1.ObjectReference) *apis.FieldError { - errs := isValidObjectReference(f) - - if f.Kind != "Channel" { - fe := apis.ErrInvalidValue(f.Kind, "kind") - fe.Paths = []string{"kind"} - fe.Details = "only 'Channel' kind is allowed" - errs = errs.Also(fe) - } - if f.APIVersion != "eventing.knative.dev/v1alpha1" { - fe := apis.ErrInvalidValue(f.APIVersion, "apiVersion") - fe.Details = "only eventing.knative.dev/v1alpha1 is allowed for apiVersion" - errs = errs.Also(fe) - } - return errs -} - -func isChannelableEmpty(f corev1.ObjectReference) bool { - return equality.Semantic.DeepEqual(f, corev1.ObjectReference{}) -} - -// Valid from only contains the following fields: -// - Kind == 'Channel' -// - APIVersion == 'eventing.knative.dev/v1alpha1' -// - Name == not empty -func isValidChannelable(f corev1.ObjectReference) *apis.FieldError { +func isValidChannel(f corev1.ObjectReference) *apis.FieldError { errs := isValidObjectReference(f) if f.Kind != "Channel" { diff --git a/pkg/apis/eventing/v1alpha1/subscribable_channelable_validation_test.go b/pkg/apis/eventing/v1alpha1/subscribable_channelable_validation_test.go new file mode 100644 index 00000000000..5586d3b23c7 --- /dev/null +++ b/pkg/apis/eventing/v1alpha1/subscribable_channelable_validation_test.go @@ -0,0 +1,167 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha1 + +import ( + "github.com/google/go-cmp/cmp" + "github.com/knative/pkg/apis" + corev1 "k8s.io/api/core/v1" + "testing" +) + +var validationTests = []struct { + name string + ref corev1.ObjectReference + want *apis.FieldError +}{ + { + name: "invalid kind", + ref: corev1.ObjectReference{ + Name: "boaty-mcboatface", + APIVersion: "eventing.knative.dev/v1alpha1", + Kind: "Strait", + }, + want: &apis.FieldError{ + Message: "invalid value \"Strait\"", + Paths: []string{"kind"}, + Details: "only 'Channel' kind is allowed", + }, + }, + { + name: "invalid api version", + ref: corev1.ObjectReference{ + Name: "boaty-mcboatface", + APIVersion: "eventing.knative.dev/v1alpha2", + Kind: "Channel", + }, + want: &apis.FieldError{ + Message: `invalid value "eventing.knative.dev/v1alpha2"`, + Paths: []string{"apiVersion"}, + Details: "only eventing.knative.dev/v1alpha1 " + + "is allowed for apiVersion", + }, + }, + { + name: "valid channel", + ref: corev1.ObjectReference{ + Name: "boaty-mcboatface", + APIVersion: "eventing.knative.dev/v1alpha1", + Kind: "Channel", + }, + want: nil, + }, +} + +func TestIsChannelEmpty(t *testing.T) { + name := "non empty" + t.Run(name, func(t *testing.T) { + r := corev1.ObjectReference{ + Name: "boaty-mcboatface", + APIVersion: "eventing.knative.dev/v1alpha1", + Kind: "Channel", + } + if isChannelEmpty(r) { + t.Errorf("%s: isChannelEmpty(%s) should be false", name, r) + } + }) + + name = "empty" + t.Run(name, func(t *testing.T) { + r := corev1.ObjectReference{} + if !isChannelEmpty(r) { + t.Errorf("%s: isChannelEmpty(%s) should be true", name, r) + } + }) +} + +func TestIsValidChannel(t *testing.T) { + for _, test := range validationTests { + t.Run(test.name, func(t *testing.T) { + got := isValidChannel(test.ref) + if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { + t.Errorf("%s: validation (-want, +got) = %v", test.name, diff) + } + }) + } +} + +func TestIsValidObjectReference(t *testing.T) { + tests := []struct { + name string + ref corev1.ObjectReference + want []*apis.FieldError + }{ + { + name: "missing api version and kind", + ref: corev1.ObjectReference{ + Name: "boaty-mcboatface", + APIVersion: "", + Kind: "", + }, + want: []*apis.FieldError{ + apis.ErrMissingField("apiVersion"), + apis.ErrMissingField("kind"), + }, + }, + { + name: "missing name", + ref: corev1.ObjectReference{ + Name: "", + APIVersion: "eventing.knative.dev/v1alpha1", + Kind: "Strait", + }, + want: []*apis.FieldError{ + apis.ErrMissingField("name"), + }, + }, + { + name: "missing all", + ref: corev1.ObjectReference{ + Name: "", + APIVersion: "", + Kind: "", + }, + want: []*apis.FieldError{ + apis.ErrMissingField("name"), + apis.ErrMissingField("apiVersion"), + apis.ErrMissingField("kind"), + }, + }, + { + name: "missing none", + ref: corev1.ObjectReference{ + Name: "kind", + APIVersion: "eventing.knative.dev/v1alpha1", + Kind: "Channel", + }, + want: []*apis.FieldError{}, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + allWanted := &apis.FieldError{} + for _, fe := range test.want { + allWanted = allWanted.Also(fe) + } + got := isValidObjectReference(test.ref) + if diff := cmp.Diff(allWanted.Error(), got.Error()); diff != "" { + t.Errorf("%s: validation (-want, +got) = %v", test.name, diff) + } + }) + } +} diff --git a/pkg/apis/eventing/v1alpha1/subscription_types.go b/pkg/apis/eventing/v1alpha1/subscription_types.go index 4af64819a17..1d7b2950eeb 100644 --- a/pkg/apis/eventing/v1alpha1/subscription_types.go +++ b/pkg/apis/eventing/v1alpha1/subscription_types.go @@ -46,19 +46,19 @@ var _ apis.Immutable = (*Subscription)(nil) var _ runtime.Object = (*Subscription)(nil) var _ webhook.GenericCRD = (*Subscription)(nil) -// SubscriptionSpec specifies the Channel for incoming events, a Call target for -// processing those events and where to put the result of the processing. Only +// SubscriptionSpec specifies the Channel for incoming events, a Subscriber target +// for processing those events and where to put the result of the processing. Only // From (where the events are coming from) is always required. You can optionally // only Process the events (results in no output events) by leaving out the Result. // You can also perform an identity transformation on the invoming events by leaving -// out the Call and only specifying Result. +// out the Subscriber and only specifying Result. // // The following are all valid specifications: -// from --[call]--> result +// channel --[subscriber]--> reply // Sink, no outgoing events: -// from -- call +// channel -- subscriber // no-op function (identity transformation): -// from --> result +// channel --> reply type SubscriptionSpec struct { // TODO: Generation used to not work correctly with CRD. They were scrubbed // by the APIserver (https://github.com/kubernetes/kubernetes/issues/58778) @@ -67,18 +67,16 @@ type SubscriptionSpec struct { // +optional Generation int64 `json:"generation,omitempty"` - // Reference to an object that will be used to create the subscription - // for receiving events. The object must have spec.subscriptions + // Reference to a channel that will be used to create the subscription + // for receiving events. The channel must have spec.subscriptions // list which will then be modified accordingly. // - // This object must fulfill the Subscribable contract. - // // You can specify only the following fields of the ObjectReference: // - Kind // - APIVersion // - Name - // Currently Kind must be "Channel" and - // APIVersion must be "eventing.knative.dev/v1alpha1" + // Kind must be "Channel" and APIVersion must be + // "eventing.knative.dev/v1alpha1" // // This field is immutable. We have no good answer on what happens to // the events that are currently in the channel being consumed from @@ -87,21 +85,21 @@ type SubscriptionSpec struct { // channel, giving the user more control over what semantics should // be used (drain the channel first, possibly have events dropped, // etc.) - From corev1.ObjectReference `json:"from"` + Channel corev1.ObjectReference `json:"channel"` - // Call is reference to (optional) function for processing events. - // Events from the From channel will be delivered here and replies - // are sent to a channel as specified by the Result. + // Subscriber is reference to (optional) function for processing events. + // Events from the Channel will be delivered here and replies are + // sent to a channel as specified by the Reply. // +optional - Call *EndpointSpec `json:"call,omitempty"` + Subscriber *SubscriberSpec `json:"subscriber,omitempty"` - // Result specifies (optionally) how to handle events returned from - // the Call target. + // Reply specifies (optionally) how to handle events returned from + // the Subscriber target. // +optional - Result *ResultStrategy `json:"result,omitempty"` + Reply *ReplyStrategy `json:"reply,omitempty"` } -// EndpointSpec specifies the reference to an object that's expected to +// SubscriberSpec specifies the reference to an object that's expected to // provide the resolved target of the action. // Currently we inspect the objects Status and see if there's a predefined // Status field that we will then use to dispatch events to be processed by @@ -116,17 +114,17 @@ type SubscriptionSpec struct { // // This ensures that we can support external targets and for ease of use // we also allow for an URI to be specified. -// There of course is also a requirement for the resolved EndpointSpec to +// There of course is also a requirement for the resolved SubscriberSpec to // behave properly at the data plane level. // TODO: Add a pointer to a real spec for this. // For now, this means: Receive an event payload, and respond with one of: // success and an optional response event, or failure. -// Delivery failures may be retried by the from Channel -type EndpointSpec struct { +// Delivery failures may be retried by the channel +type SubscriberSpec struct { // Only one of these can be specified // Reference to an object that will be used to find the target - // endpoint. + // endpoint, which should implement the Addressable duck type. // For example, this could be a reference to a Route resource // or a Knative Service resource. // TODO: Specify the required fields the target object must @@ -136,7 +134,7 @@ type EndpointSpec struct { // - APIVersion // - Name // +optional - TargetRef *corev1.ObjectReference `json:"targetRef,omitempty"` + Ref *corev1.ObjectReference `json:"ref,omitempty"` // Reference to a 'known' endpoint where no resolving is done. // http://k8s-service for example @@ -145,24 +143,24 @@ type EndpointSpec struct { DNSName *string `json:"dnsName,omitempty"` } -// ResultStrategy specifies the handling of the EndpointSpec's returned result. -// If no EndpointSpec is specified, the identity function is assumed. -type ResultStrategy struct { - // This object must fulfill the Sinkable contract. +// ReplyStrategy specifies the handling of the SubscriberSpec's returned replies. +// If no SubscriberSpec is specified, the identity function is assumed. +type ReplyStrategy struct { + // This object must be a Channel. // - // TODO: Specify the required fields the target object must - // have in the status. // You can specify only the following fields of the ObjectReference: // - Kind // - APIVersion // - Name + // Kind must be "Channel" and APIVersion must be + // "eventing.knative.dev/v1alpha1" // +optional - Target *corev1.ObjectReference `json:"target,omitempty"` + Channel *corev1.ObjectReference `json:"channel,omitempty"` } // subCondSet is a condition set with Ready as the happy condition and -// ReferencesResolved and FromReady as the dependent conditions. -var subCondSet = duckv1alpha1.NewLivingConditionSet(SubscriptionConditionReferencesResolved, SubscriptionConditionFromReady) +// ReferencesResolved and ChannelReady as the dependent conditions. +var subCondSet = duckv1alpha1.NewLivingConditionSet(SubscriptionConditionReferencesResolved, SubscriptionConditionChannelReady) // SubscriptionStatus (computed) for a subscription type SubscriptionStatus struct { @@ -171,10 +169,6 @@ type SubscriptionStatus struct { // +patchStrategy=merge Conditions duckv1alpha1.Conditions `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` - // Subscription might be Subscribable. This depends if there's a Result channel - // In that case, this points to that resource. - Subscribable duckv1alpha1.Subscribable `json:"subscribable,omitempty"` - // PhysicalSubscription is the fully resolved values that this Subscription represents. PhysicalSubscription SubscriptionStatusPhysicalSubscription `json:"physicalSubscription,omitEmpty"` } @@ -182,14 +176,11 @@ type SubscriptionStatus struct { // SubscriptionStatusPhysicalSubscription represents the fully resolved values for this // Subscription. type SubscriptionStatusPhysicalSubscription struct { - // From is the object pointed to in status.from's Subscribable contract. - From corev1.ObjectReference `json:"from,omitEmpty"` - - // CallDomain is the fully resolved domain for spec.callable. - CallDomain string `json:"callDomain,omitEmpty"` + // SubscriberURI is the fully resolved URI for spec.subscriber. + SubscriberURI string `json:"subscriberURI,omitEmpty"` - // ResultDomain is the fully resolved domain for the spec.result. - ResultDomain string `json:"resultDomain,omitEmpty"` + // ReplyURI is the fully resolved URI for the spec.reply. + ReplyURI string `json:"replyURI,omitEmpty"` } const ( @@ -200,9 +191,9 @@ const ( // resolved. SubscriptionConditionReferencesResolved duckv1alpha1.ConditionType = "Resolved" - // SubscriptionConditionFromReady has status True when controller has successfully added a subscription to From - // resource. - SubscriptionConditionFromReady duckv1alpha1.ConditionType = "FromReady" + // SubscriptionConditionChannelReady has status True when controller has successfully added a + // subscription to the spec.channel resource. + SubscriptionConditionChannelReady duckv1alpha1.ConditionType = "ChannelReady" ) // GetCondition returns the condition currently associated with the given type, or nil. @@ -225,9 +216,9 @@ func (ss *SubscriptionStatus) MarkReferencesResolved() { subCondSet.Manage(ss).MarkTrue(SubscriptionConditionReferencesResolved) } -// MarkFromReady sets the FromReady condition to True state. -func (ss *SubscriptionStatus) MarkFromReady() { - subCondSet.Manage(ss).MarkTrue(SubscriptionConditionFromReady) +// MarkChannelReady sets the ChannelReady condition to True state. +func (ss *SubscriptionStatus) MarkChannelReady() { + subCondSet.Manage(ss).MarkTrue(SubscriptionConditionChannelReady) } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object diff --git a/pkg/apis/eventing/v1alpha1/subscription_types_test.go b/pkg/apis/eventing/v1alpha1/subscription_types_test.go index b55c6d1527e..c2fb93a74dc 100644 --- a/pkg/apis/eventing/v1alpha1/subscription_types_test.go +++ b/pkg/apis/eventing/v1alpha1/subscription_types_test.go @@ -20,7 +20,6 @@ import ( "testing" "github.com/google/go-cmp/cmp" - "github.com/google/go-cmp/cmp/cmpopts" duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" corev1 "k8s.io/api/core/v1" ) @@ -35,8 +34,8 @@ var subscriptionConditionReferencesResolved = duckv1alpha1.Condition{ Status: corev1.ConditionFalse, } -var subscriptionConditionFromReady = duckv1alpha1.Condition{ - Type: SubscriptionConditionFromReady, +var subscriptionConditionChannelReady = duckv1alpha1.Condition{ + Type: SubscriptionConditionChannelReady, Status: corev1.ConditionTrue, } @@ -70,11 +69,11 @@ func TestSubscriptionGetCondition(t *testing.T) { ss: &SubscriptionStatus{ Conditions: []duckv1alpha1.Condition{ subscriptionConditionReady, - subscriptionConditionFromReady, + subscriptionConditionChannelReady, }, }, - condQuery: SubscriptionConditionFromReady, - want: &subscriptionConditionFromReady, + condQuery: SubscriptionConditionChannelReady, + want: &subscriptionConditionChannelReady, }, { name: "unknown condition", ss: &SubscriptionStatus{ @@ -107,7 +106,7 @@ func TestSubscriptionInitializeConditions(t *testing.T) { ss: &SubscriptionStatus{}, want: &SubscriptionStatus{ Conditions: []duckv1alpha1.Condition{{ - Type: SubscriptionConditionFromReady, + Type: SubscriptionConditionChannelReady, Status: corev1.ConditionUnknown, }, { Type: SubscriptionConditionReady, @@ -121,13 +120,13 @@ func TestSubscriptionInitializeConditions(t *testing.T) { name: "one false", ss: &SubscriptionStatus{ Conditions: []duckv1alpha1.Condition{{ - Type: SubscriptionConditionFromReady, + Type: SubscriptionConditionChannelReady, Status: corev1.ConditionFalse, }}, }, want: &SubscriptionStatus{ Conditions: []duckv1alpha1.Condition{{ - Type: SubscriptionConditionFromReady, + Type: SubscriptionConditionChannelReady, Status: corev1.ConditionFalse, }, { Type: SubscriptionConditionReady, @@ -147,7 +146,7 @@ func TestSubscriptionInitializeConditions(t *testing.T) { }, want: &SubscriptionStatus{ Conditions: []duckv1alpha1.Condition{{ - Type: SubscriptionConditionFromReady, + Type: SubscriptionConditionChannelReady, Status: corev1.ConditionUnknown, }, { Type: SubscriptionConditionReady, @@ -162,8 +161,7 @@ func TestSubscriptionInitializeConditions(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { test.ss.InitializeConditions() - ignore := cmpopts.IgnoreFields(duckv1alpha1.Condition{}, "LastTransitionTime") - if diff := cmp.Diff(test.want, test.ss, ignore); diff != "" { + if diff := cmp.Diff(test.want, test.ss, ignoreAllButTypeAndStatus); diff != "" { t.Errorf("unexpected conditions (-want, +got) = %v", diff) } }) @@ -172,30 +170,30 @@ func TestSubscriptionInitializeConditions(t *testing.T) { func TestSubscriptionIsReady(t *testing.T) { tests := []struct { - name string - markResolved bool - markFromReady bool - wantReady bool + name string + markResolved bool + markChannelReady bool + wantReady bool }{{ - name: "all happy", - markResolved: true, - markFromReady: true, - wantReady: true, + name: "all happy", + markResolved: true, + markChannelReady: true, + wantReady: true, }, { - name: "one sad", - markResolved: false, - markFromReady: true, - wantReady: false, + name: "one sad", + markResolved: false, + markChannelReady: true, + wantReady: false, }, { - name: "other sad", - markResolved: true, - markFromReady: false, - wantReady: false, + name: "other sad", + markResolved: true, + markChannelReady: false, + wantReady: false, }, { - name: "both sad", - markResolved: false, - markFromReady: false, - wantReady: false, + name: "both sad", + markResolved: false, + markChannelReady: false, + wantReady: false, }} for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -203,8 +201,8 @@ func TestSubscriptionIsReady(t *testing.T) { if test.markResolved { ss.MarkReferencesResolved() } - if test.markFromReady { - ss.MarkFromReady() + if test.markChannelReady { + ss.MarkChannelReady() } got := ss.IsReady() if test.wantReady != got { diff --git a/pkg/apis/eventing/v1alpha1/subscription_validation.go b/pkg/apis/eventing/v1alpha1/subscription_validation.go index ddbe9468f01..c74f1a4ac44 100644 --- a/pkg/apis/eventing/v1alpha1/subscription_validation.go +++ b/pkg/apis/eventing/v1alpha1/subscription_validation.go @@ -28,92 +28,79 @@ func (s *Subscription) Validate() *apis.FieldError { return s.Spec.Validate().ViaField("spec") } -// We require always From -// Also at least one of 'call' and 'result' must be defined (non-nill and non-empty) +// We require always Channel +// Also at least one of 'subscriber' and 'reply' must be defined (non-nill and non-empty) func (ss *SubscriptionSpec) Validate() *apis.FieldError { var errs *apis.FieldError - if isFromEmpty(ss.From) { - fe := apis.ErrMissingField("from") - fe.Details = "the Subscription must reference a from channel" + if isChannelEmpty(ss.Channel) { + fe := apis.ErrMissingField("channel") + fe.Details = "the Subscription must reference a channel" return fe - } else if fe := isValidFrom(ss.From); fe != nil { - errs = errs.Also(fe.ViaField("from")) + } else if fe := isValidChannel(ss.Channel); fe != nil { + errs = errs.Also(fe.ViaField("channel")) } - missingCall := isEndpointSpecNilOrEmpty(ss.Call) - missingResultStrategy := isResultStrategyNilOrEmpty(ss.Result) - if missingCall && missingResultStrategy { - fe := apis.ErrMissingField("result", "call") - fe.Details = "the Subscription must reference at least one of (result channel or a call)" + missingSubscriber := isSubscriberSpecNilOrEmpty(ss.Subscriber) + missingReply := isReplyStrategyNilOrEmpty(ss.Reply) + if missingSubscriber && missingReply { + fe := apis.ErrMissingField("reply", "subscriber") + fe.Details = "the Subscription must reference at least one of (reply or a subscriber)" errs = errs.Also(fe) } - if !missingCall { - if fe := isValidEndpointSpec(*ss.Call); fe != nil { - errs = errs.Also(fe.ViaField("call")) + if !missingSubscriber { + if fe := isValidSubscriberSpec(*ss.Subscriber); fe != nil { + errs = errs.Also(fe.ViaField("subscriber")) } } - if !missingResultStrategy { - if fe := isValidResultStrategy(*ss.Result); fe != nil { - errs = errs.Also(fe.ViaField("result")) + if !missingReply { + if fe := isValidReply(*ss.Reply); fe != nil { + errs = errs.Also(fe.ViaField("reply")) } } return errs } -func isEndpointSpecNilOrEmpty(e *EndpointSpec) bool { - return e == nil || equality.Semantic.DeepEqual(e, &EndpointSpec{}) || - (equality.Semantic.DeepEqual(e.TargetRef, &corev1.ObjectReference{}) && e.DNSName == nil) +func isSubscriberSpecNilOrEmpty(s *SubscriberSpec) bool { + return s == nil || equality.Semantic.DeepEqual(s, &SubscriberSpec{}) || + (equality.Semantic.DeepEqual(s.Ref, &corev1.ObjectReference{}) && s.DNSName == nil) } -func isValidEndpointSpec(e EndpointSpec) *apis.FieldError { +func isValidSubscriberSpec(s SubscriberSpec) *apis.FieldError { var errs *apis.FieldError - if e.DNSName != nil && *e.DNSName != "" && e.TargetRef != nil && !equality.Semantic.DeepEqual(e.TargetRef, &corev1.ObjectReference{}) { - errs = errs.Also(apis.ErrMultipleOneOf("targetRef", "dnsName")) + if s.DNSName != nil && *s.DNSName != "" && s.Ref != nil && !equality.Semantic.DeepEqual(s.Ref, &corev1.ObjectReference{}) { + errs = errs.Also(apis.ErrMultipleOneOf("ref", "dnsName")) } - // If TargetRef given, check the fields. - if e.TargetRef != nil && !equality.Semantic.DeepEqual(e.TargetRef, &corev1.ObjectReference{}) { - fe := isValidObjectReference(*e.TargetRef) + // If Ref given, check the fields. + if s.Ref != nil && !equality.Semantic.DeepEqual(s.Ref, &corev1.ObjectReference{}) { + fe := isValidObjectReference(*s.Ref) if fe != nil { - errs = errs.Also(fe.ViaField("targetRef")) + errs = errs.Also(fe.ViaField("ref")) } } return errs } -func isFromEmpty(f corev1.ObjectReference) bool { - return isSubscribableEmpty(f) +func isReplyStrategyNilOrEmpty(r *ReplyStrategy) bool { + return r == nil || equality.Semantic.DeepEqual(r, &ReplyStrategy{}) || equality.Semantic.DeepEqual(r.Channel, &corev1.ObjectReference{}) } -// Valid from only contains the following fields: -// - Kind == 'Channel' -// - APIVersion == 'eventing.knative.dev/v1alpha1' -// - Name == not empty -func isValidFrom(f corev1.ObjectReference) *apis.FieldError { - return isValidSubscribable(f) -} - -func isResultStrategyNilOrEmpty(r *ResultStrategy) bool { - return r == nil || equality.Semantic.DeepEqual(r, &ResultStrategy{}) || equality.Semantic.DeepEqual(r.Target, &corev1.ObjectReference{}) -} - -func isValidResultStrategy(r ResultStrategy) *apis.FieldError { - fe := isValidObjectReference(*r.Target) - if fe != nil { - return fe.ViaField("target") +func isValidReply(r ReplyStrategy) *apis.FieldError { + if fe := isValidObjectReference(*r.Channel); fe != nil { + return fe.ViaField("channel") } - if r.Target.Kind != "Channel" { - fe := apis.ErrInvalidValue(r.Target.Kind, "kind") + if r.Channel.Kind != "Channel" { + fe := apis.ErrInvalidValue(r.Channel.Kind, "kind") fe.Paths = []string{"kind"} fe.Details = "only 'Channel' kind is allowed" return fe } - if r.Target.APIVersion != "eventing.knative.dev/v1alpha1" { - fe := apis.ErrInvalidValue(r.Target.APIVersion, "apiVersion") + if r.Channel.APIVersion != "eventing.knative.dev/v1alpha1" { + fe := apis.ErrInvalidValue(r.Channel.APIVersion, "apiVersion") fe.Details = "only eventing.knative.dev/v1alpha1 is allowed for apiVersion" return fe } @@ -129,8 +116,8 @@ func (current *Subscription) CheckImmutableFields(og apis.Immutable) *apis.Field return nil } - // Only Call and Result are mutable. - ignoreArguments := cmpopts.IgnoreFields(SubscriptionSpec{}, "Call", "Result") + // Only Subscriber and Reply are mutable. + ignoreArguments := cmpopts.IgnoreFields(SubscriptionSpec{}, "Subscriber", "Reply") if diff := cmp.Diff(original.Spec, current.Spec, ignoreArguments); diff != "" { return &apis.FieldError{ Message: "Immutable fields changed (-old +new)", diff --git a/pkg/apis/eventing/v1alpha1/subscription_validation_test.go b/pkg/apis/eventing/v1alpha1/subscription_validation_test.go index 66117c09500..5acdfdcb230 100644 --- a/pkg/apis/eventing/v1alpha1/subscription_validation_test.go +++ b/pkg/apis/eventing/v1alpha1/subscription_validation_test.go @@ -28,33 +28,33 @@ const ( channelAPIVersion = "eventing.knative.dev/v1alpha1" routeKind = "Route" routeAPIVersion = "serving.knative.dev/v1alpha1" - fromChannelName = "fromChannel" - resultChannelName = "toChannel" - callName = "call" + channelName = "subscribedChannel" + replyChannelName = "toChannel" + subscriberName = "subscriber" ) -func getValidFromRef() corev1.ObjectReference { +func getValidChannelRef() corev1.ObjectReference { return corev1.ObjectReference{ - Name: fromChannelName, + Name: channelName, Kind: channelKind, APIVersion: channelAPIVersion, } } -func getValidResultStrategy() *ResultStrategy { - return &ResultStrategy{ - Target: &corev1.ObjectReference{ - Name: resultChannelName, +func getValidReplyStrategy() *ReplyStrategy { + return &ReplyStrategy{ + Channel: &corev1.ObjectReference{ + Name: replyChannelName, Kind: channelKind, APIVersion: channelAPIVersion, }, } } -func getValidEndpointSpec() *EndpointSpec { - return &EndpointSpec{ - TargetRef: &corev1.ObjectReference{ - Name: callName, +func getValidSubscriberSpec() *SubscriberSpec { + return &SubscriberSpec{ + Ref: &corev1.ObjectReference{ + Name: subscriberName, Kind: routeKind, APIVersion: routeAPIVersion, }, @@ -68,16 +68,16 @@ func (d *DummyImmutableType) CheckImmutableFields(og apis.Immutable) *apis.Field } func TestSubscriptionValidation(t *testing.T) { - name := "empty from" + name := "empty channel" c := &Subscription{ Spec: SubscriptionSpec{ - From: corev1.ObjectReference{}, + Channel: corev1.ObjectReference{}, }, } want := &apis.FieldError{ - Paths: []string{"spec.from"}, + Paths: []string{"spec.channel"}, Message: "missing field(s)", - Details: "the Subscription must reference a from channel", + Details: "the Subscription must reference a channel", } t.Run(name, func(t *testing.T) { @@ -97,134 +97,134 @@ func TestSubscriptionSpecValidation(t *testing.T) { }{{ name: "valid", c: &SubscriptionSpec{ - From: getValidFromRef(), - Call: getValidEndpointSpec(), + Channel: getValidChannelRef(), + Subscriber: getValidSubscriberSpec(), }, want: nil, }, { - name: "empty From", + name: "empty Channel", c: &SubscriptionSpec{ - From: corev1.ObjectReference{}, + Channel: corev1.ObjectReference{}, }, want: func() *apis.FieldError { - fe := apis.ErrMissingField("from") - fe.Details = "the Subscription must reference a from channel" + fe := apis.ErrMissingField("channel") + fe.Details = "the Subscription must reference a channel" return fe }(), }, { - name: "missing name in From", + name: "missing name in Channel", c: &SubscriptionSpec{ - From: corev1.ObjectReference{ + Channel: corev1.ObjectReference{ Kind: channelKind, APIVersion: channelAPIVersion, }, - Call: getValidEndpointSpec(), + Subscriber: getValidSubscriberSpec(), }, want: func() *apis.FieldError { - fe := apis.ErrMissingField("from.name") + fe := apis.ErrMissingField("channel.name") return fe }(), }, { - name: "missing Call and Result", + name: "missing Subscriber and Reply", c: &SubscriptionSpec{ - From: getValidFromRef(), + Channel: getValidChannelRef(), }, want: func() *apis.FieldError { - fe := apis.ErrMissingField("result", "call") - fe.Details = "the Subscription must reference at least one of (result channel or a call)" + fe := apis.ErrMissingField("reply", "subscriber") + fe.Details = "the Subscription must reference at least one of (reply or a subscriber)" return fe }(), }, { - name: "empty Call and Result", + name: "empty Subscriber and Reply", c: &SubscriptionSpec{ - From: getValidFromRef(), - Call: &EndpointSpec{}, - Result: &ResultStrategy{}, + Channel: getValidChannelRef(), + Subscriber: &SubscriberSpec{}, + Reply: &ReplyStrategy{}, }, want: func() *apis.FieldError { - fe := apis.ErrMissingField("result", "call") - fe.Details = "the Subscription must reference at least one of (result channel or a call)" + fe := apis.ErrMissingField("reply", "subscriber") + fe.Details = "the Subscription must reference at least one of (reply or a subscriber)" return fe }(), }, { - name: "missing Result", + name: "missing Reply", c: &SubscriptionSpec{ - From: getValidFromRef(), - Call: getValidEndpointSpec(), + Channel: getValidChannelRef(), + Subscriber: getValidSubscriberSpec(), }, want: nil, }, { - name: "empty Result", + name: "empty Reply", c: &SubscriptionSpec{ - From: getValidFromRef(), - Call: getValidEndpointSpec(), - Result: &ResultStrategy{}, + Channel: getValidChannelRef(), + Subscriber: getValidSubscriberSpec(), + Reply: &ReplyStrategy{}, }, want: nil, }, { - name: "missing Call", + name: "missing Subscriber", c: &SubscriptionSpec{ - From: getValidFromRef(), - Result: getValidResultStrategy(), + Channel: getValidChannelRef(), + Reply: getValidReplyStrategy(), }, want: nil, }, { - name: "empty Call", + name: "empty Subscriber", c: &SubscriptionSpec{ - From: getValidFromRef(), - Call: &EndpointSpec{}, - Result: getValidResultStrategy(), + Channel: getValidChannelRef(), + Subscriber: &SubscriberSpec{}, + Reply: getValidReplyStrategy(), }, want: nil, }, { - name: "missing name in from, and missing call, result", + name: "missing name in channel, and missing subscriber, reply", c: &SubscriptionSpec{ - From: corev1.ObjectReference{ + Channel: corev1.ObjectReference{ Kind: channelKind, APIVersion: channelAPIVersion, }, }, want: func() *apis.FieldError { - fe := apis.ErrMissingField("result", "call") - fe.Details = "the Subscription must reference at least one of (result channel or a call)" - return apis.ErrMissingField("from.name").Also(fe) + fe := apis.ErrMissingField("reply", "subscriber") + fe.Details = "the Subscription must reference at least one of (reply or a subscriber)" + return apis.ErrMissingField("channel.name").Also(fe) }(), }, { name: "empty", c: &SubscriptionSpec{}, want: func() *apis.FieldError { - fe := apis.ErrMissingField("from") - fe.Details = "the Subscription must reference a from channel" + fe := apis.ErrMissingField("channel") + fe.Details = "the Subscription must reference a channel" return fe }(), }, { - name: "missing name in Call.TargetRef", + name: "missing name in Subscriber.Ref", c: &SubscriptionSpec{ - From: getValidFromRef(), - Call: &EndpointSpec{ - TargetRef: &corev1.ObjectReference{ + Channel: getValidChannelRef(), + Subscriber: &SubscriberSpec{ + Ref: &corev1.ObjectReference{ Kind: channelKind, APIVersion: channelAPIVersion, }, }, }, want: func() *apis.FieldError { - fe := apis.ErrMissingField("call.targetRef.name") + fe := apis.ErrMissingField("subscriber.ref.name") return fe }(), }, { - name: "missing name in Result.TargetRef", + name: "missing name in Reply.Ref", c: &SubscriptionSpec{ - From: getValidFromRef(), - Result: &ResultStrategy{ - Target: &corev1.ObjectReference{ + Channel: getValidChannelRef(), + Reply: &ReplyStrategy{ + Channel: &corev1.ObjectReference{ Kind: channelKind, APIVersion: channelAPIVersion, }, }, }, want: func() *apis.FieldError { - fe := apis.ErrMissingField("result.target.name") + fe := apis.ErrMissingField("reply.channel.name") return fe }(), }} @@ -233,21 +233,21 @@ func TestSubscriptionSpecValidation(t *testing.T) { t.Run(test.name, func(t *testing.T) { got := test.c.Validate() if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { - t.Errorf("%s: validateFrom (-want, +got) = %v", test.name, diff) + t.Errorf("%s: validateChannel (-want, +got) = %v", test.name, diff) } }) } } func TestSubscriptionImmutable(t *testing.T) { - newFrom := getValidFromRef() - newFrom.Name = "newFromChannel" + newChannel := getValidChannelRef() + newChannel.Name = "newChannel" - newCall := getValidEndpointSpec() - newCall.TargetRef.Name = "newCall" + newSubscriber := getValidSubscriberSpec() + newSubscriber.Ref.Name = "newSubscriber" - newResult := getValidResultStrategy() - newResult.Target.Name = "newResultChannel" + newReply := getValidReplyStrategy() + newReply.Channel.Name = "newReplyChannel" tests := []struct { name string @@ -258,12 +258,12 @@ func TestSubscriptionImmutable(t *testing.T) { name: "valid", c: &Subscription{ Spec: SubscriptionSpec{ - From: getValidFromRef(), + Channel: getValidChannelRef(), }, }, og: &Subscription{ Spec: SubscriptionSpec{ - From: getValidFromRef(), + Channel: getValidChannelRef(), }, }, want: nil, @@ -271,90 +271,90 @@ func TestSubscriptionImmutable(t *testing.T) { name: "new nil is ok", c: &Subscription{ Spec: SubscriptionSpec{ - From: getValidFromRef(), - Call: getValidEndpointSpec(), + Channel: getValidChannelRef(), + Subscriber: getValidSubscriberSpec(), }, }, og: nil, want: nil, }, { - name: "valid, new Call", + name: "valid, new Subscriber", c: &Subscription{ Spec: SubscriptionSpec{ - From: getValidFromRef(), - Call: getValidEndpointSpec(), + Channel: getValidChannelRef(), + Subscriber: getValidSubscriberSpec(), }, }, og: &Subscription{ Spec: SubscriptionSpec{ - From: getValidFromRef(), - Call: newCall, + Channel: getValidChannelRef(), + Subscriber: newSubscriber, }, }, want: nil, }, { - name: "valid, new Result", + name: "valid, new Reply", c: &Subscription{ Spec: SubscriptionSpec{ - From: getValidFromRef(), - Result: getValidResultStrategy(), + Channel: getValidChannelRef(), + Reply: getValidReplyStrategy(), }, }, og: &Subscription{ Spec: SubscriptionSpec{ - From: getValidFromRef(), - Result: newResult, + Channel: getValidChannelRef(), + Reply: newReply, }, }, want: nil, }, { - name: "valid, have Result, remove and replace with Call", + name: "valid, have Reply, remove and replace with Subscriber", c: &Subscription{ Spec: SubscriptionSpec{ - From: getValidFromRef(), - Result: getValidResultStrategy(), + Channel: getValidChannelRef(), + Reply: getValidReplyStrategy(), }, }, og: &Subscription{ Spec: SubscriptionSpec{ - From: getValidFromRef(), - Call: getValidEndpointSpec(), + Channel: getValidChannelRef(), + Subscriber: getValidSubscriberSpec(), }, }, want: nil, }, { - name: "valid, have Call, remove and replace with Result", + name: "valid, have Subscriber, remove and replace with Reply", c: &Subscription{ Spec: SubscriptionSpec{ - From: getValidFromRef(), - Call: getValidEndpointSpec(), + Channel: getValidChannelRef(), + Subscriber: getValidSubscriberSpec(), }, }, og: &Subscription{ Spec: SubscriptionSpec{ - From: getValidFromRef(), - Result: getValidResultStrategy(), + Channel: getValidChannelRef(), + Reply: getValidReplyStrategy(), }, }, want: nil, }, { - name: "From changed", + name: "Channel changed", c: &Subscription{ Spec: SubscriptionSpec{ - From: getValidFromRef(), + Channel: getValidChannelRef(), }, }, og: &Subscription{ Spec: SubscriptionSpec{ - From: newFrom, + Channel: newChannel, }, }, want: &apis.FieldError{ Message: "Immutable fields changed (-old +new)", Paths: []string{"spec"}, - Details: `{v1alpha1.SubscriptionSpec}.From.Name: - -: "newFromChannel" - +: "fromChannel" + Details: `{v1alpha1.SubscriptionSpec}.Channel.Name: + -: "newChannel" + +: "subscribedChannel" `, }, }} @@ -373,8 +373,8 @@ func TestInvalidImmutableType(t *testing.T) { name := "invalid type" c := &Subscription{ Spec: SubscriptionSpec{ - From: getValidFromRef(), - Call: getValidEndpointSpec(), + Channel: getValidChannelRef(), + Subscriber: getValidSubscriberSpec(), }, } og := &DummyImmutableType{} @@ -389,7 +389,7 @@ func TestInvalidImmutableType(t *testing.T) { }) } -func TestValidFrom(t *testing.T) { +func TestValidChannel(t *testing.T) { tests := []struct { name string c corev1.ObjectReference @@ -397,7 +397,7 @@ func TestValidFrom(t *testing.T) { }{{ name: "valid", c: corev1.ObjectReference{ - Name: fromChannelName, + Name: channelName, APIVersion: channelAPIVersion, Kind: channelKind, }, @@ -415,7 +415,7 @@ func TestValidFrom(t *testing.T) { }, { name: "missing apiVersion", c: corev1.ObjectReference{ - Name: fromChannelName, + Name: channelName, Kind: channelKind, }, want: func() *apis.FieldError { @@ -426,7 +426,7 @@ func TestValidFrom(t *testing.T) { }, { name: "missing kind", c: corev1.ObjectReference{ - Name: fromChannelName, + Name: channelName, APIVersion: channelAPIVersion, }, want: func() *apis.FieldError { @@ -437,7 +437,7 @@ func TestValidFrom(t *testing.T) { }, { name: "invalid kind", c: corev1.ObjectReference{ - Name: fromChannelName, + Name: channelName, APIVersion: channelAPIVersion, Kind: "subscription", }, @@ -449,7 +449,7 @@ func TestValidFrom(t *testing.T) { }, { name: "invalid apiVersion", c: corev1.ObjectReference{ - Name: fromChannelName, + Name: channelName, APIVersion: "wrongapiversion", Kind: channelKind, }, @@ -461,7 +461,7 @@ func TestValidFrom(t *testing.T) { }, { name: "extra field, namespace", c: corev1.ObjectReference{ - Name: fromChannelName, + Name: channelName, APIVersion: channelAPIVersion, Kind: channelKind, Namespace: "secretnamespace", @@ -474,7 +474,7 @@ func TestValidFrom(t *testing.T) { }, { name: "extra field, namespace and resourceVersion", c: corev1.ObjectReference{ - Name: fromChannelName, + Name: channelName, APIVersion: channelAPIVersion, Kind: channelKind, Namespace: "secretnamespace", @@ -489,7 +489,7 @@ func TestValidFrom(t *testing.T) { // Make sure that if an empty field for namespace is given, it's treated as not there. name: "valid extra field, namespace empty", c: corev1.ObjectReference{ - Name: fromChannelName, + Name: channelName, APIVersion: channelAPIVersion, Kind: channelKind, Namespace: "", @@ -499,101 +499,101 @@ func TestValidFrom(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - got := isValidFrom(test.c) + got := isValidChannel(test.c) if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { - t.Errorf("isValidFrom (-want, +got) = %v", diff) + t.Errorf("isValidChannel (-want, +got) = %v", diff) } }) } } -func TestValidgetValidEndpointSpec(t *testing.T) { +func TestValidgetValidSubscriber(t *testing.T) { dnsName := "example.com" tests := []struct { name string - e EndpointSpec + s SubscriberSpec want *apis.FieldError }{{ - name: "valid targetRef", - e: *getValidEndpointSpec(), + name: "valid ref", + s: *getValidSubscriberSpec(), want: nil, }, { name: "valid dnsName", - e: EndpointSpec{ + s: SubscriberSpec{ DNSName: &dnsName, }, want: nil, }, { - name: "both targetRef and dnsName given", - e: EndpointSpec{ - TargetRef: &corev1.ObjectReference{ - Name: fromChannelName, + name: "both ref and dnsName given", + s: SubscriberSpec{ + Ref: &corev1.ObjectReference{ + Name: channelName, APIVersion: channelAPIVersion, Kind: channelKind, }, DNSName: &dnsName, }, want: func() *apis.FieldError { - fe := apis.ErrMultipleOneOf("targetRef", "dnsName") + fe := apis.ErrMultipleOneOf("ref", "dnsName") return fe }(), }, { - name: "missing name in targetRef", - e: EndpointSpec{ - TargetRef: &corev1.ObjectReference{ + name: "missing name in ref", + s: SubscriberSpec{ + Ref: &corev1.ObjectReference{ APIVersion: channelAPIVersion, Kind: channelKind, }, }, want: func() *apis.FieldError { - fe := apis.ErrMissingField("targetRef.name") + fe := apis.ErrMissingField("ref.name") return fe }(), }, { - name: "missing apiVersion in targetRef", - e: EndpointSpec{ - TargetRef: &corev1.ObjectReference{ - Name: fromChannelName, + name: "missing apiVersion in ref", + s: SubscriberSpec{ + Ref: &corev1.ObjectReference{ + Name: channelName, Kind: channelKind, }, }, want: func() *apis.FieldError { - fe := apis.ErrMissingField("targetRef.apiVersion") + fe := apis.ErrMissingField("ref.apiVersion") return fe }(), }, { - name: "missing kind in targetRef", - e: EndpointSpec{ - TargetRef: &corev1.ObjectReference{ - Name: fromChannelName, + name: "missing kind in ref", + s: SubscriberSpec{ + Ref: &corev1.ObjectReference{ + Name: channelName, APIVersion: channelAPIVersion, }, }, want: func() *apis.FieldError { - fe := apis.ErrMissingField("targetRef.kind") + fe := apis.ErrMissingField("ref.kind") return fe }(), }, { name: "extra field, namespace", - e: EndpointSpec{ - TargetRef: &corev1.ObjectReference{ - Name: fromChannelName, + s: SubscriberSpec{ + Ref: &corev1.ObjectReference{ + Name: channelName, APIVersion: channelAPIVersion, Kind: channelKind, Namespace: "secretnamespace", }, }, want: func() *apis.FieldError { - fe := apis.ErrDisallowedFields("targetRef.Namespace") + fe := apis.ErrDisallowedFields("ref.Namespace") fe.Details = "only name, apiVersion and kind are supported fields" return fe }(), }, { // Make sure that if an empty field for namespace is given, it's treated as not there. name: "valid extra field, namespace empty", - e: EndpointSpec{ - TargetRef: &corev1.ObjectReference{ - Name: fromChannelName, + s: SubscriberSpec{ + Ref: &corev1.ObjectReference{ + Name: channelName, APIVersion: channelAPIVersion, Kind: channelKind, Namespace: "", @@ -604,64 +604,64 @@ func TestValidgetValidEndpointSpec(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - got := isValidEndpointSpec(test.e) + got := isValidSubscriberSpec(test.s) if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { - t.Errorf("%s: isValidFrom (-want, +got) = %v", test.name, diff) + t.Errorf("%s: isValidSubscriber (-want, +got) = %v", test.name, diff) } }) } } -func TestValidResultStrategy(t *testing.T) { +func TestValidReply(t *testing.T) { tests := []struct { name string - c ResultStrategy + r ReplyStrategy want *apis.FieldError }{{ name: "valid target", - c: *getValidResultStrategy(), + r: *getValidReplyStrategy(), want: nil, }, { name: "missing name in target", - c: ResultStrategy{ - Target: &corev1.ObjectReference{ + r: ReplyStrategy{ + Channel: &corev1.ObjectReference{ APIVersion: channelAPIVersion, Kind: channelKind, }, }, want: func() *apis.FieldError { - fe := apis.ErrMissingField("target.name") + fe := apis.ErrMissingField("channel.name") return fe }(), }, { name: "missing apiVersion in target", - c: ResultStrategy{ - Target: &corev1.ObjectReference{ - Name: fromChannelName, + r: ReplyStrategy{ + Channel: &corev1.ObjectReference{ + Name: channelName, Kind: channelKind, }, }, want: func() *apis.FieldError { - fe := apis.ErrMissingField("target.apiVersion") + fe := apis.ErrMissingField("channel.apiVersion") return fe }(), }, { name: "missing kind in target", - c: ResultStrategy{ - Target: &corev1.ObjectReference{ - Name: fromChannelName, + r: ReplyStrategy{ + Channel: &corev1.ObjectReference{ + Name: channelName, APIVersion: channelAPIVersion, }, }, want: func() *apis.FieldError { - fe := apis.ErrMissingField("target.kind") + fe := apis.ErrMissingField("channel.kind") return fe }(), }, { name: "invalid kind", - c: ResultStrategy{ - Target: &corev1.ObjectReference{ - Name: fromChannelName, + r: ReplyStrategy{ + Channel: &corev1.ObjectReference{ + Name: channelName, APIVersion: channelAPIVersion, Kind: "subscription", }, @@ -673,9 +673,9 @@ func TestValidResultStrategy(t *testing.T) { }(), }, { name: "invalid apiVersion", - c: ResultStrategy{ - Target: &corev1.ObjectReference{ - Name: fromChannelName, + r: ReplyStrategy{ + Channel: &corev1.ObjectReference{ + Name: channelName, APIVersion: "wrongapiversion", Kind: channelKind, }, @@ -687,25 +687,25 @@ func TestValidResultStrategy(t *testing.T) { }(), }, { name: "extra field, namespace", - c: ResultStrategy{ - Target: &corev1.ObjectReference{ - Name: fromChannelName, + r: ReplyStrategy{ + Channel: &corev1.ObjectReference{ + Name: channelName, APIVersion: channelAPIVersion, Kind: channelKind, Namespace: "secretnamespace", }, }, want: func() *apis.FieldError { - fe := apis.ErrDisallowedFields("target.Namespace") + fe := apis.ErrDisallowedFields("channel.Namespace") fe.Details = "only name, apiVersion and kind are supported fields" return fe }(), }, { // Make sure that if an empty field for namespace is given, it's treated as not there. name: "valid extra field, namespace empty", - c: ResultStrategy{ - Target: &corev1.ObjectReference{ - Name: fromChannelName, + r: ReplyStrategy{ + Channel: &corev1.ObjectReference{ + Name: channelName, APIVersion: channelAPIVersion, Kind: channelKind, Namespace: "", @@ -716,9 +716,9 @@ func TestValidResultStrategy(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - got := isValidResultStrategy(test.c) + got := isValidReply(test.r) if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { - t.Errorf("%s: isValidFrom (-want, +got) = %v", test.name, diff) + t.Errorf("%s: isValidReply (-want, +got) = %v", test.name, diff) } }) } diff --git a/pkg/apis/eventing/v1alpha1/zz_generated.deepcopy.go b/pkg/apis/eventing/v1alpha1/zz_generated.deepcopy.go index ddde0c1d91b..56b501996f4 100644 --- a/pkg/apis/eventing/v1alpha1/zz_generated.deepcopy.go +++ b/pkg/apis/eventing/v1alpha1/zz_generated.deepcopy.go @@ -21,7 +21,8 @@ limitations under the License. package v1alpha1 import ( - duck_v1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" + duck_v1alpha1 "github.com/knative/eventing/pkg/apis/duck/v1alpha1" + apis_duck_v1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" v1 "k8s.io/api/core/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) @@ -95,8 +96,8 @@ func (in *ChannelSpec) DeepCopyInto(out *ChannelSpec) { if *in == nil { *out = nil } else { - *out = new(ProvisionerReference) - (*in).DeepCopyInto(*out) + *out = new(v1.ObjectReference) + **out = **in } } if in.Arguments != nil { @@ -108,12 +109,12 @@ func (in *ChannelSpec) DeepCopyInto(out *ChannelSpec) { (*in).DeepCopyInto(*out) } } - if in.Channelable != nil { - in, out := &in.Channelable, &out.Channelable + if in.Subscribable != nil { + in, out := &in.Subscribable, &out.Subscribable if *in == nil { *out = nil } else { - *out = new(duck_v1alpha1.Channelable) + *out = new(duck_v1alpha1.Subscribable) (*in).DeepCopyInto(*out) } } @@ -133,11 +134,10 @@ func (in *ChannelSpec) DeepCopy() *ChannelSpec { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ChannelStatus) DeepCopyInto(out *ChannelStatus) { *out = *in - out.Sinkable = in.Sinkable - out.Subscribable = in.Subscribable + out.Address = in.Address if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(duck_v1alpha1.Conditions, len(*in)) + *out = make(apis_duck_v1alpha1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -156,7 +156,7 @@ func (in *ChannelStatus) DeepCopy() *ChannelStatus { } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterProvisioner) DeepCopyInto(out *ClusterProvisioner) { +func (in *ClusterChannelProvisioner) DeepCopyInto(out *ClusterChannelProvisioner) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) @@ -165,18 +165,18 @@ func (in *ClusterProvisioner) DeepCopyInto(out *ClusterProvisioner) { return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterProvisioner. -func (in *ClusterProvisioner) DeepCopy() *ClusterProvisioner { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterChannelProvisioner. +func (in *ClusterChannelProvisioner) DeepCopy() *ClusterChannelProvisioner { if in == nil { return nil } - out := new(ClusterProvisioner) + out := new(ClusterChannelProvisioner) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ClusterProvisioner) DeepCopyObject() runtime.Object { +func (in *ClusterChannelProvisioner) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } @@ -184,13 +184,13 @@ func (in *ClusterProvisioner) DeepCopyObject() runtime.Object { } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterProvisionerList) DeepCopyInto(out *ClusterProvisionerList) { +func (in *ClusterChannelProvisionerList) DeepCopyInto(out *ClusterChannelProvisionerList) { *out = *in out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items - *out = make([]ClusterProvisioner, len(*in)) + *out = make([]ClusterChannelProvisioner, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -198,18 +198,18 @@ func (in *ClusterProvisionerList) DeepCopyInto(out *ClusterProvisionerList) { return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterProvisionerList. -func (in *ClusterProvisionerList) DeepCopy() *ClusterProvisionerList { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterChannelProvisionerList. +func (in *ClusterChannelProvisionerList) DeepCopy() *ClusterChannelProvisionerList { if in == nil { return nil } - out := new(ClusterProvisionerList) + out := new(ClusterChannelProvisionerList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ClusterProvisionerList) DeepCopyObject() runtime.Object { +func (in *ClusterChannelProvisionerList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } @@ -217,28 +217,27 @@ func (in *ClusterProvisionerList) DeepCopyObject() runtime.Object { } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterProvisionerSpec) DeepCopyInto(out *ClusterProvisionerSpec) { +func (in *ClusterChannelProvisionerSpec) DeepCopyInto(out *ClusterChannelProvisionerSpec) { *out = *in - out.Reconciles = in.Reconciles return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterProvisionerSpec. -func (in *ClusterProvisionerSpec) DeepCopy() *ClusterProvisionerSpec { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterChannelProvisionerSpec. +func (in *ClusterChannelProvisionerSpec) DeepCopy() *ClusterChannelProvisionerSpec { if in == nil { return nil } - out := new(ClusterProvisionerSpec) + out := new(ClusterChannelProvisionerSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterProvisionerStatus) DeepCopyInto(out *ClusterProvisionerStatus) { +func (in *ClusterChannelProvisionerStatus) DeepCopyInto(out *ClusterChannelProvisionerStatus) { *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(duck_v1alpha1.Conditions, len(*in)) + *out = make(apis_duck_v1alpha1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -246,21 +245,21 @@ func (in *ClusterProvisionerStatus) DeepCopyInto(out *ClusterProvisionerStatus) return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterProvisionerStatus. -func (in *ClusterProvisionerStatus) DeepCopy() *ClusterProvisionerStatus { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterChannelProvisionerStatus. +func (in *ClusterChannelProvisionerStatus) DeepCopy() *ClusterChannelProvisionerStatus { if in == nil { return nil } - out := new(ClusterProvisionerStatus) + out := new(ClusterChannelProvisionerStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *EndpointSpec) DeepCopyInto(out *EndpointSpec) { +func (in *ReplyStrategy) DeepCopyInto(out *ReplyStrategy) { *out = *in - if in.TargetRef != nil { - in, out := &in.TargetRef, &out.TargetRef + if in.Channel != nil { + in, out := &in.Channel, &out.Channel if *in == nil { *out = nil } else { @@ -268,30 +267,21 @@ func (in *EndpointSpec) DeepCopyInto(out *EndpointSpec) { **out = **in } } - if in.DNSName != nil { - in, out := &in.DNSName, &out.DNSName - if *in == nil { - *out = nil - } else { - *out = new(string) - **out = **in - } - } return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EndpointSpec. -func (in *EndpointSpec) DeepCopy() *EndpointSpec { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ReplyStrategy. +func (in *ReplyStrategy) DeepCopy() *ReplyStrategy { if in == nil { return nil } - out := new(EndpointSpec) + out := new(ReplyStrategy) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ProvisionerReference) DeepCopyInto(out *ProvisionerReference) { +func (in *SubscriberSpec) DeepCopyInto(out *SubscriberSpec) { *out = *in if in.Ref != nil { in, out := &in.Ref, &out.Ref @@ -302,168 +292,24 @@ func (in *ProvisionerReference) DeepCopyInto(out *ProvisionerReference) { **out = **in } } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProvisionerReference. -func (in *ProvisionerReference) DeepCopy() *ProvisionerReference { - if in == nil { - return nil - } - out := new(ProvisionerReference) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ResultStrategy) DeepCopyInto(out *ResultStrategy) { - *out = *in - if in.Target != nil { - in, out := &in.Target, &out.Target - if *in == nil { - *out = nil - } else { - *out = new(v1.ObjectReference) - **out = **in - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResultStrategy. -func (in *ResultStrategy) DeepCopy() *ResultStrategy { - if in == nil { - return nil - } - out := new(ResultStrategy) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Source) DeepCopyInto(out *Source) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Source. -func (in *Source) DeepCopy() *Source { - if in == nil { - return nil - } - out := new(Source) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Source) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SourceList) DeepCopyInto(out *SourceList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Source, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SourceList. -func (in *SourceList) DeepCopy() *SourceList { - if in == nil { - return nil - } - out := new(SourceList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *SourceList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SourceSpec) DeepCopyInto(out *SourceSpec) { - *out = *in - if in.Provisioner != nil { - in, out := &in.Provisioner, &out.Provisioner - if *in == nil { - *out = nil - } else { - *out = new(ProvisionerReference) - (*in).DeepCopyInto(*out) - } - } - if in.Arguments != nil { - in, out := &in.Arguments, &out.Arguments - if *in == nil { - *out = nil - } else { - *out = new(runtime.RawExtension) - (*in).DeepCopyInto(*out) - } - } - if in.Channel != nil { - in, out := &in.Channel, &out.Channel + if in.DNSName != nil { + in, out := &in.DNSName, &out.DNSName if *in == nil { *out = nil } else { - *out = new(v1.ObjectReference) + *out = new(string) **out = **in } } return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SourceSpec. -func (in *SourceSpec) DeepCopy() *SourceSpec { - if in == nil { - return nil - } - out := new(SourceSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SourceStatus) DeepCopyInto(out *SourceStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make(duck_v1alpha1.Conditions, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - out.Subscribable = in.Subscribable - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SourceStatus. -func (in *SourceStatus) DeepCopy() *SourceStatus { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SubscriberSpec. +func (in *SubscriberSpec) DeepCopy() *SubscriberSpec { if in == nil { return nil } - out := new(SourceStatus) + out := new(SubscriberSpec) in.DeepCopyInto(out) return out } @@ -532,22 +378,22 @@ func (in *SubscriptionList) DeepCopyObject() runtime.Object { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SubscriptionSpec) DeepCopyInto(out *SubscriptionSpec) { *out = *in - out.From = in.From - if in.Call != nil { - in, out := &in.Call, &out.Call + out.Channel = in.Channel + if in.Subscriber != nil { + in, out := &in.Subscriber, &out.Subscriber if *in == nil { *out = nil } else { - *out = new(EndpointSpec) + *out = new(SubscriberSpec) (*in).DeepCopyInto(*out) } } - if in.Result != nil { - in, out := &in.Result, &out.Result + if in.Reply != nil { + in, out := &in.Reply, &out.Reply if *in == nil { *out = nil } else { - *out = new(ResultStrategy) + *out = new(ReplyStrategy) (*in).DeepCopyInto(*out) } } @@ -569,12 +415,11 @@ func (in *SubscriptionStatus) DeepCopyInto(out *SubscriptionStatus) { *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make(duck_v1alpha1.Conditions, len(*in)) + *out = make(apis_duck_v1alpha1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } - out.Subscribable = in.Subscribable out.PhysicalSubscription = in.PhysicalSubscription return } @@ -592,7 +437,6 @@ func (in *SubscriptionStatus) DeepCopy() *SubscriptionStatus { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SubscriptionStatusPhysicalSubscription) DeepCopyInto(out *SubscriptionStatusPhysicalSubscription) { *out = *in - out.From = in.From return } diff --git a/pkg/apis/feeds/logkey/constants.go b/pkg/apis/feeds/logkey/constants.go deleted file mode 100644 index 4bfb3cb2fdc..00000000000 --- a/pkg/apis/feeds/logkey/constants.go +++ /dev/null @@ -1,36 +0,0 @@ -/* -Copyright 2018 The Knative 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 logkey - -const ( - kNative = "knative.dev/" - - // ClusterEventSource is the key used for cluster scoped event source name in structured logs - ClusterEventSource = kNative + "clustereventsource" - - // ClusterEventType is the key used for cluster event type name in structured logs - ClusterEventType = kNative + "clustereventtype" - - // EventSource is the key used for event source name in structured logs - EventSource = kNative + "eventsource" - - // EventType is the key used for event type name in structured logs - EventType = kNative + "eventtype" - - // Feed is the key used for feed name in structured logs - Feed = kNative + "feed" -) diff --git a/pkg/apis/feeds/v1alpha1/cluster_event_source_defaults.go b/pkg/apis/feeds/v1alpha1/cluster_event_source_defaults.go deleted file mode 100644 index ba86a0d2894..00000000000 --- a/pkg/apis/feeds/v1alpha1/cluster_event_source_defaults.go +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -func (es *ClusterEventSource) SetDefaults() { - es.Spec.SetDefaults() -} - -func (ess *ClusterEventSourceSpec) SetDefaults() { - ess.CommonEventSourceSpec.SetDefaults() -} diff --git a/pkg/apis/feeds/v1alpha1/cluster_event_source_types.go b/pkg/apis/feeds/v1alpha1/cluster_event_source_types.go deleted file mode 100644 index 08fd3f98539..00000000000 --- a/pkg/apis/feeds/v1alpha1/cluster_event_source_types.go +++ /dev/null @@ -1,74 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "encoding/json" - - "github.com/knative/pkg/apis" - "github.com/knative/pkg/webhook" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" -) - -// +genclient -// +genclient:nonNamespaced -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// ClusterEventSource represents a software system which wishes to make changes in -// state discoverable via eventing, without prior knowledge of systems which -// might consume state changes. ClusterEventSources produce events that the Feed -// resource connects to consumers. -type ClusterEventSource struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec ClusterEventSourceSpec `json:"spec"` - Status ClusterEventSourceStatus `json:"status"` -} - -// Check that ClusterEventSource can be validated, can be defaulted, and has immutable fields. -var _ apis.Validatable = (*ClusterEventSource)(nil) -var _ apis.Defaultable = (*ClusterEventSource)(nil) -var _ runtime.Object = (*ClusterEventSource)(nil) -var _ webhook.GenericCRD = (*ClusterEventSource)(nil) - -// ClusterEventSourceSpec describes the type and source of an event, a container image -// to run for feed lifecycle operations, and configuration options for the -// ClusterEventSource. -type ClusterEventSourceSpec struct { - CommonEventSourceSpec `json:",inline"` -} - -// ClusterEventSourceStatus is the status for a ClusterEventSource resource -type ClusterEventSourceStatus struct { - CommonEventSourceStatus `json:",inline"` -} - -func (es *ClusterEventSource) GetSpecJSON() ([]byte, error) { - return json.Marshal(es.Spec) -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// ClusterEventSourceList is a list of ClusterEventSource resources -type ClusterEventSourceList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []ClusterEventSource `json:"items"` -} diff --git a/pkg/apis/feeds/v1alpha1/cluster_event_type_defaults.go b/pkg/apis/feeds/v1alpha1/cluster_event_type_defaults.go deleted file mode 100644 index dc8c615029a..00000000000 --- a/pkg/apis/feeds/v1alpha1/cluster_event_type_defaults.go +++ /dev/null @@ -1,26 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -func (cet *ClusterEventType) SetDefaults() { - cet.Spec.SetDefaults() -} - -func (cets *ClusterEventTypeSpec) SetDefaults() { - cets.CommonEventTypeSpec.SetDefaults() - // TODO anything? -} diff --git a/pkg/apis/feeds/v1alpha1/cluster_event_type_types.go b/pkg/apis/feeds/v1alpha1/cluster_event_type_types.go deleted file mode 100644 index f54a32537b7..00000000000 --- a/pkg/apis/feeds/v1alpha1/cluster_event_type_types.go +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "encoding/json" - "github.com/knative/pkg/apis" - "github.com/knative/pkg/webhook" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" -) - -// +genclient -// +genclient:nonNamespaced -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// ClusterEventType is a specification for a ClusterEventType resource -// EventSource can expose multiple event types. For example, github -// has PullRequest events as well as Issues and Comments, etc. -type ClusterEventType struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec ClusterEventTypeSpec `json:"spec"` - Status ClusterEventTypeStatus `json:"status"` -} - -// Check that ClusterEventType can be validated, can be defaulted, and has immutable fields. -var _ apis.Validatable = (*ClusterEventType)(nil) -var _ apis.Defaultable = (*ClusterEventType)(nil) -var _ apis.Immutable = (*ClusterEventType)(nil) -var _ runtime.Object = (*ClusterEventType)(nil) -var _ webhook.GenericCRD = (*ClusterEventType)(nil) - -// ClusterEventTypeSpec specifies information about the ClusterEventType, including a schema -// for the event and information about the parameters needed to create a Feed to -// the event. -type ClusterEventTypeSpec struct { - CommonEventTypeSpec `json:",inline"` - // ClusterEventSource is the name of the ClusterEventSource that produces this ClusterEventType. - ClusterEventSource string `json:"eventSource"` -} - -// ClusterEventTypeStatus is the status for a ClusterEventType resource -type ClusterEventTypeStatus struct { - CommonEventTypeStatus `json:",inline"` -} - -func (et *ClusterEventType) GetSpecJSON() ([]byte, error) { - return json.Marshal(et.Spec) -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// ClusterEventTypeList is a list of ClusterEventType resources -type ClusterEventTypeList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []ClusterEventType `json:"items"` -} diff --git a/pkg/apis/feeds/v1alpha1/cluster_event_type_validation.go b/pkg/apis/feeds/v1alpha1/cluster_event_type_validation.go deleted file mode 100644 index b809348f459..00000000000 --- a/pkg/apis/feeds/v1alpha1/cluster_event_type_validation.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "github.com/knative/pkg/apis" - "k8s.io/apimachinery/pkg/util/validation" -) - -func (et *ClusterEventType) Validate() *apis.FieldError { - return et.Spec.Validate().ViaField("spec") -} - -func (ets *ClusterEventTypeSpec) Validate() *apis.FieldError { - if ets.ClusterEventSource == "" { - return apis.ErrMissingField("eventSource") - } - if errs := validation.IsQualifiedName(ets.ClusterEventSource); len(errs) > 0 { - return apis.ErrInvalidValue(ets.ClusterEventSource, "eventSource") - } - return ets.CommonEventTypeSpec.Validate() -} - -func (current *ClusterEventType) CheckImmutableFields(og apis.Immutable) *apis.FieldError { - original, ok := og.(*ClusterEventType) - if !ok { - return &apis.FieldError{Message: "The provided original was not a ClusterEventType"} - } - if original == nil { - return nil - } - - // EventSource for an EventType should not change. - if original.Spec.ClusterEventSource != current.Spec.ClusterEventSource { - return &apis.FieldError{ - Message: "Immutable fields changed", - Paths: []string{"spec.eventSource"}, - } - } - - return nil -} diff --git a/pkg/apis/feeds/v1alpha1/cluster_event_type_validation_test.go b/pkg/apis/feeds/v1alpha1/cluster_event_type_validation_test.go deleted file mode 100644 index 6bcb34d51b1..00000000000 --- a/pkg/apis/feeds/v1alpha1/cluster_event_type_validation_test.go +++ /dev/null @@ -1,121 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "github.com/google/go-cmp/cmp" - "github.com/knative/pkg/apis" - "testing" -) - -func TestClusterEventTypeSpecValidation(t *testing.T) { - tests := []struct { - name string - et *ClusterEventTypeSpec - want *apis.FieldError - }{{ - name: "valid", - et: &ClusterEventTypeSpec{ - ClusterEventSource: "foo", - }, - }, { - name: "invalid source", - et: &ClusterEventTypeSpec{ - ClusterEventSource: "f@o", - }, - want: apis.ErrInvalidValue("f@o", "eventSource"), - }, { - name: "empty", - et: &ClusterEventTypeSpec{}, - want: apis.ErrMissingField("eventSource"), - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.et.Validate() - if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { - t.Errorf("validateClusterEventType (-want, +got) = %v", diff) - } - }) - } -} - -func TestClusterEventTypeImmutableFields(t *testing.T) { - tests := []struct { - name string - new apis.Immutable - old apis.Immutable - want *apis.FieldError - }{{ - name: "good (no change)", - new: &ClusterEventType{ - Spec: ClusterEventTypeSpec{ - ClusterEventSource: "foo", - }, - }, - old: &ClusterEventType{ - Spec: ClusterEventTypeSpec{ - ClusterEventSource: "foo", - }, - }, - want: nil, - }, { - name: "good (description change)", - new: &ClusterEventType{ - Spec: ClusterEventTypeSpec{ - ClusterEventSource: "foo", - CommonEventTypeSpec: CommonEventTypeSpec{ - Description: "Foo foo foo.", - }, - }, - }, - old: &ClusterEventType{ - Spec: ClusterEventTypeSpec{ - ClusterEventSource: "foo", - CommonEventTypeSpec: CommonEventTypeSpec{ - Description: "Bar bar bar.", - }, - }, - }, - want: nil, - }, { - name: "bad (source changes)", - new: &ClusterEventType{ - Spec: ClusterEventTypeSpec{ - ClusterEventSource: "foo", - }, - }, - old: &ClusterEventType{ - Spec: ClusterEventTypeSpec{ - ClusterEventSource: "bar", - }, - }, - want: &apis.FieldError{ - Message: "Immutable fields changed", - Paths: []string{"spec.eventSource"}, - }, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.new.CheckImmutableFields(test.old) - if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { - t.Errorf("Validate (-want, +got) = %v", diff) - } - }) - } -} diff --git a/pkg/apis/feeds/v1alpha1/common_event_source_test.go b/pkg/apis/feeds/v1alpha1/common_event_source_test.go deleted file mode 100644 index c812aa40cfa..00000000000 --- a/pkg/apis/feeds/v1alpha1/common_event_source_test.go +++ /dev/null @@ -1,128 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "fmt" - "testing" -) - -func TestCommonEventSourceCondition_SetCondition(t *testing.T) { - testcases := []struct { - name string - types []CommonEventSourceConditionType - want int - }{ - {"Simple", []CommonEventSourceConditionType{EventSourceComplete}, 1}, - {"Two", []CommonEventSourceConditionType{EventSourceComplete, EventSourceFailed}, 2}, - {"Override", []CommonEventSourceConditionType{EventSourceComplete, EventSourceComplete}, 1}, - {"Invalid", []CommonEventSourceConditionType{""}, 0}, - } - - // EventSource - for _, tc := range testcases { - testName := fmt.Sprintf("%s - %s", "EventSource", tc.name) - t.Run(testName, func(t *testing.T) { - src := EventSource{} - for _, t := range tc.types { - c := &CommonEventSourceCondition{ - Type: t, - } - src.Status.SetCondition(c) - } - got := len(src.Status.Conditions) - if tc.want != got { - t.Fatalf("Failed to return expecected number of conditions. \nwant:\t%#v\ngot:\t%#v", tc.want, got) - } - }) - } - // ClusterEventSource - for _, tc := range testcases { - testName := fmt.Sprintf("%s - %s", "ClusterEventSource", tc.name) - t.Run(testName, func(t *testing.T) { - src := ClusterEventSource{} - for _, t := range tc.types { - c := &CommonEventSourceCondition{ - Type: t, - } - src.Status.SetCondition(c) - } - got := len(src.Status.Conditions) - if tc.want != got { - t.Fatalf("Failed to return expecected number of conditions. \nwant:\t%#v\ngot:\t%#v", tc.want, got) - } - }) - } -} - -func TestCommonEventSourceCondition_RemoveCondition(t *testing.T) { - testcases := []struct { - name string - set []CommonEventSourceConditionType - remove []CommonEventSourceConditionType - want int - }{ - {"Simple", []CommonEventSourceConditionType{EventSourceComplete}, []CommonEventSourceConditionType{EventSourceComplete}, 0}, - {"One", []CommonEventSourceConditionType{EventSourceComplete, EventSourceFailed}, []CommonEventSourceConditionType{EventSourceComplete}, 1}, - {"Missing", []CommonEventSourceConditionType{EventSourceComplete}, []CommonEventSourceConditionType{EventSourceFailed}, 1}, - {"Invalid", []CommonEventSourceConditionType{EventSourceComplete}, []CommonEventSourceConditionType{""}, 1}, - } - - // EventSource - for _, tc := range testcases { - testName := fmt.Sprintf("%s - %s", "EventSource", tc.name) - t.Run(testName, func(t *testing.T) { - src := EventSource{} - for _, t := range tc.set { - c := &CommonEventSourceCondition{ - Type: t, - } - src.Status.SetCondition(c) - } - for _, t := range tc.remove { - src.Status.RemoveCondition(t) - } - - got := len(src.Status.Conditions) - if tc.want != got { - t.Fatalf("Failed to return expecected number of conditions. \nwant:\t%#v\ngot:\t%#v", tc.want, got) - } - }) - } - - // ClusterEventSource - for _, tc := range testcases { - testName := fmt.Sprintf("%s - %s", "ClusterEventSource", tc.name) - t.Run(testName, func(t *testing.T) { - src := ClusterEventSource{} - for _, t := range tc.set { - c := &CommonEventSourceCondition{ - Type: t, - } - src.Status.SetCondition(c) - } - for _, t := range tc.remove { - src.Status.RemoveCondition(t) - } - - got := len(src.Status.Conditions) - if tc.want != got { - t.Fatalf("Failed to return expecected number of conditions. \nwant:\t%#v\ngot:\t%#v", tc.want, got) - } - }) - } -} diff --git a/pkg/apis/feeds/v1alpha1/common_event_source_types.go b/pkg/apis/feeds/v1alpha1/common_event_source_types.go deleted file mode 100644 index a3a32b378d1..00000000000 --- a/pkg/apis/feeds/v1alpha1/common_event_source_types.go +++ /dev/null @@ -1,112 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "github.com/knative/pkg/apis" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/runtime" -) - -// CommonEventSourceSpec describes the type and source of an event, a container image -// to run for feed lifecycle operations, and configuration options common for -// ClusterEventSource and EventSource. -type CommonEventSourceSpec struct { - // TODO: Generation does not work correctly with CRD. They are scrubbed - // by the APIserver (https://github.com/kubernetes/kubernetes/issues/58778) - // So, we add Generation here. Once that gets fixed, remove this and use - // ObjectMeta.Generation instead. - // +optional - Generation int64 `json:"generation,omitempty"` - - // Source is the name of the source that produces the events. - Source string `json:"source,omitempty"` - - // Image is the container image to run for feed lifecycle operations. - // - // TODO: make this a container - // TODO: specify exactly when containers are run - Image string `json:"image,omitempty"` - - // Parameters are configuration options for a particular EventSource - // TODO: Consider instead using ConfigMaps and mount them instead - // on the event sources containers. - Parameters *runtime.RawExtension `json:"parameters,omitempty"` -} - -// Check that CommonEventSourceSpec can be validated and can be defaulted -var _ apis.Validatable = (*CommonEventSourceSpec)(nil) -var _ apis.Defaultable = (*CommonEventSourceSpec)(nil) - -// EventSourceStatus is the status for a EventSource resource -type CommonEventSourceStatus struct { - Conditions []CommonEventSourceCondition `json:"conditions,omitempty"` -} - -type CommonEventSourceConditionType string - -const ( - // EventSourceComplete specifies that the EventSource has completed successfully. - EventSourceComplete CommonEventSourceConditionType = "Complete" - // EventSourceFailed specifies that the EventSource has failed. - EventSourceFailed CommonEventSourceConditionType = "Failed" - // EventSourceInvalid specifies that the given EventSource specification is invalid. - EventSourceInvalid CommonEventSourceConditionType = "Invalid" -) - -// CommonEventSourceCondition defines a readiness condition for a EventSource. -// See: https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#typical-status-properties -type CommonEventSourceCondition struct { - Type CommonEventSourceConditionType `json:"type"` - - Status corev1.ConditionStatus `json:"status" description:"status of the condition, one of True, False, Unknown"` - - // +optional - Reason string `json:"reason,omitempty" description:"one-word CamelCase reason for the condition's last transition"` - // +optional - Message string `json:"message,omitempty" description:"human-readable message indicating details about last transition"` -} - -func (ess *CommonEventSourceStatus) SetCondition(new *CommonEventSourceCondition) { - if new == nil || new.Type == "" { - return - } - - t := new.Type - var conditions []CommonEventSourceCondition - for _, cond := range ess.Conditions { - if cond.Type != t { - conditions = append(conditions, cond) - } - } - conditions = append(conditions, *new) - ess.Conditions = conditions -} - -func (ess *CommonEventSourceStatus) RemoveCondition(t CommonEventSourceConditionType) { - if t == "" { - return - } - - var conditions []CommonEventSourceCondition - for _, cond := range ess.Conditions { - if cond.Type != t { - conditions = append(conditions, cond) - } - } - ess.Conditions = conditions -} diff --git a/pkg/apis/feeds/v1alpha1/common_event_type_defaults.go b/pkg/apis/feeds/v1alpha1/common_event_type_defaults.go deleted file mode 100644 index 5e42df2ce04..00000000000 --- a/pkg/apis/feeds/v1alpha1/common_event_type_defaults.go +++ /dev/null @@ -1,21 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -func (cets *CommonEventTypeSpec) SetDefaults() { - // TODO anything? -} diff --git a/pkg/apis/feeds/v1alpha1/common_event_type_test.go b/pkg/apis/feeds/v1alpha1/common_event_type_test.go deleted file mode 100644 index 9d57924b0c6..00000000000 --- a/pkg/apis/feeds/v1alpha1/common_event_type_test.go +++ /dev/null @@ -1,128 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "fmt" - "testing" -) - -func TestCommonEventTypeCondition_SetCondition(t *testing.T) { - testcases := []struct { - name string - types []CommonEventTypeConditionType - want int - }{ - {"Simple", []CommonEventTypeConditionType{EventTypeComplete}, 1}, - {"Two", []CommonEventTypeConditionType{EventTypeComplete, EventTypeFailed}, 2}, - {"Override", []CommonEventTypeConditionType{EventTypeComplete, EventTypeComplete}, 1}, - {"Invalid", []CommonEventTypeConditionType{""}, 0}, - } - - // EventType - for _, tc := range testcases { - testName := fmt.Sprintf("%s - %s", "EventType", tc.name) - t.Run(testName, func(t *testing.T) { - src := EventType{} - for _, t := range tc.types { - c := &CommonEventTypeCondition{ - Type: t, - } - src.Status.SetCondition(c) - } - got := len(src.Status.Conditions) - if tc.want != got { - t.Fatalf("Failed to return expecected number of conditions. \nwant:\t%#v\ngot:\t%#v", tc.want, got) - } - }) - } - // ClusterEventType - for _, tc := range testcases { - testName := fmt.Sprintf("%s - %s", "ClusterEventType", tc.name) - t.Run(testName, func(t *testing.T) { - src := ClusterEventType{} - for _, t := range tc.types { - c := &CommonEventTypeCondition{ - Type: t, - } - src.Status.SetCondition(c) - } - got := len(src.Status.Conditions) - if tc.want != got { - t.Fatalf("Failed to return expecected number of conditions. \nwant:\t%#v\ngot:\t%#v", tc.want, got) - } - }) - } -} - -func TestCommonEventTypeCondition_RemoveCondition(t *testing.T) { - testcases := []struct { - name string - set []CommonEventTypeConditionType - remove []CommonEventTypeConditionType - want int - }{ - {"Simple", []CommonEventTypeConditionType{EventTypeComplete}, []CommonEventTypeConditionType{EventTypeComplete}, 0}, - {"One", []CommonEventTypeConditionType{EventTypeComplete, EventTypeFailed}, []CommonEventTypeConditionType{EventTypeComplete}, 1}, - {"Missing", []CommonEventTypeConditionType{EventTypeComplete}, []CommonEventTypeConditionType{EventTypeFailed}, 1}, - {"Invalid", []CommonEventTypeConditionType{EventTypeComplete}, []CommonEventTypeConditionType{""}, 1}, - } - - // EventType - for _, tc := range testcases { - testName := fmt.Sprintf("%s - %s", "EventType", tc.name) - t.Run(testName, func(t *testing.T) { - src := EventType{} - for _, t := range tc.set { - c := &CommonEventTypeCondition{ - Type: t, - } - src.Status.SetCondition(c) - } - for _, t := range tc.remove { - src.Status.RemoveCondition(t) - } - - got := len(src.Status.Conditions) - if tc.want != got { - t.Fatalf("Failed to return expecected number of conditions. \nwant:\t%#v\ngot:\t%#v", tc.want, got) - } - }) - } - - // ClusterEventType - for _, tc := range testcases { - testName := fmt.Sprintf("%s - %s", "ClusterEventType", tc.name) - t.Run(testName, func(t *testing.T) { - src := ClusterEventType{} - for _, t := range tc.set { - c := &CommonEventTypeCondition{ - Type: t, - } - src.Status.SetCondition(c) - } - for _, t := range tc.remove { - src.Status.RemoveCondition(t) - } - - got := len(src.Status.Conditions) - if tc.want != got { - t.Fatalf("Failed to return expecected number of conditions. \nwant:\t%#v\ngot:\t%#v", tc.want, got) - } - }) - } -} diff --git a/pkg/apis/feeds/v1alpha1/common_event_type_types.go b/pkg/apis/feeds/v1alpha1/common_event_type_types.go deleted file mode 100644 index c4c7b7841c8..00000000000 --- a/pkg/apis/feeds/v1alpha1/common_event_type_types.go +++ /dev/null @@ -1,110 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "github.com/knative/pkg/apis" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/runtime" -) - -// CommonEventTypeSpec specifies information about the [Cluster]EventType, -// including a schema for the event and information about the parameters -// needed to create a Feed to the event. -type CommonEventTypeSpec struct { - // TODO: Generation does not work correctly with CRD. They are scrubbed - // by the APIserver (https://github.com/kubernetes/kubernetes/issues/58778) - // So, we add Generation here. Once that gets fixed, remove this and use - // ObjectMeta.Generation instead. - // +optional - Generation int64 `json:"generation,omitempty"` - - // Description is a human-readable description of the EventType. - Description string `json:"description,omitempty"` - // SubscribeSchema describing how to subscribe to this. This basically - // defines what is required in the Feed.Parameters so that the developer - // can see the required parameters. - SubscribeSchema *runtime.RawExtension `json:"subscribeSchema,omitempty"` - // Describe the schema for the events emitted by this EventType. - EventSchema *runtime.RawExtension `json:"eventSchema,omitempty"` -} - -// Check that CommonEventTypeSpec can be validated and can be defaulted -var _ apis.Validatable = (*CommonEventTypeSpec)(nil) -var _ apis.Defaultable = (*CommonEventTypeSpec)(nil) - -// CommonEventTypeStatus is the status for a EventType resource -type CommonEventTypeStatus struct { - Conditions []CommonEventTypeCondition `json:"conditions,omitempty"` -} - -type CommonEventTypeConditionType string - -const ( - // EventTypeComplete specifies that the EventType has completed successfully. - EventTypeComplete CommonEventTypeConditionType = "Complete" - // EventTypeFailed specifies that the EventType has failed. - EventTypeFailed CommonEventTypeConditionType = "Failed" - // EventTypeInvalid specifies that the given EventType specification is invalid. - EventTypeInvalid CommonEventTypeConditionType = "Invalid" - // EventTypeInUse specifies that the given EventType, which is marked for deletion, still has - // Feeds that depend on it, so cannot yet be deleted. - EventTypeInUse CommonEventTypeConditionType = "InUse" -) - -// EventTypeCondition defines a readiness condition for a EventType. -// See: https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#typical-status-properties -type CommonEventTypeCondition struct { - Type CommonEventTypeConditionType `json:"type"` - - Status corev1.ConditionStatus `json:"status" description:"status of the condition, one of True, False, Unknown"` - - // +optional - Reason string `json:"reason,omitempty" description:"one-word CamelCase reason for the condition's last transition"` - // +optional - Message string `json:"message,omitempty" description:"human-readable message indicating details about last transition"` -} - -func (ets *CommonEventTypeStatus) SetCondition(new *CommonEventTypeCondition) { - if new == nil || new.Type == "" { - return - } - - t := new.Type - var conditions []CommonEventTypeCondition - for _, cond := range ets.Conditions { - if cond.Type != t { - conditions = append(conditions, cond) - } - } - conditions = append(conditions, *new) - ets.Conditions = conditions -} - -func (ets *CommonEventTypeStatus) RemoveCondition(t CommonEventTypeConditionType) { - if t == "" { - return - } - - var conditions []CommonEventTypeCondition - for _, cond := range ets.Conditions { - if cond.Type != t { - conditions = append(conditions, cond) - } - } - ets.Conditions = conditions -} diff --git a/pkg/apis/feeds/v1alpha1/doc.go b/pkg/apis/feeds/v1alpha1/doc.go deleted file mode 100644 index 45e3270570a..00000000000 --- a/pkg/apis/feeds/v1alpha1/doc.go +++ /dev/null @@ -1,16 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ -// +k8s:deepcopy-gen=package -// Package v1alpha1 is the v1alpha1 version of the API. -// +groupName=feeds.knative.dev -package v1alpha1 diff --git a/pkg/apis/feeds/v1alpha1/event_source_defaults.go b/pkg/apis/feeds/v1alpha1/event_source_defaults.go deleted file mode 100644 index b49b8b0f0b0..00000000000 --- a/pkg/apis/feeds/v1alpha1/event_source_defaults.go +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -func (es *EventSource) SetDefaults() { - es.Spec.SetDefaults() -} - -func (ess *EventSourceSpec) SetDefaults() { - ess.CommonEventSourceSpec.SetDefaults() -} diff --git a/pkg/apis/feeds/v1alpha1/event_source_types.go b/pkg/apis/feeds/v1alpha1/event_source_types.go deleted file mode 100644 index 84776c4c381..00000000000 --- a/pkg/apis/feeds/v1alpha1/event_source_types.go +++ /dev/null @@ -1,72 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "encoding/json" - "github.com/knative/pkg/apis" - "github.com/knative/pkg/webhook" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" -) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// EventSource represents a software system which wishes to make changes in -// state discoverable via eventing, without prior knowledge of systems which -// might consume state changes. EventSources produce events that the Feed -// resource connects to consumers. -type EventSource struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec EventSourceSpec `json:"spec"` - Status EventSourceStatus `json:"status"` -} - -// Check that EventSource can be validated, can be defaulted, and has immutable fields. -var _ apis.Validatable = (*EventSource)(nil) -var _ apis.Defaultable = (*EventSource)(nil) -var _ runtime.Object = (*EventSource)(nil) -var _ webhook.GenericCRD = (*EventSource)(nil) - -// EventSourceSpec describes the type and source of an event, a container image -// to run for feed lifecycle operations, and configuration options for the -// EventSource. -type EventSourceSpec struct { - CommonEventSourceSpec `json:",inline"` -} - -// EventSourceStatus is the status for a EventSource resource -type EventSourceStatus struct { - CommonEventSourceStatus `json:",inline"` -} - -func (es *EventSource) GetSpecJSON() ([]byte, error) { - return json.Marshal(es.Spec) -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// EventSourceList is a list of EventSource resources -type EventSourceList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []EventSource `json:"items"` -} diff --git a/pkg/apis/feeds/v1alpha1/event_type_defaults.go b/pkg/apis/feeds/v1alpha1/event_type_defaults.go deleted file mode 100644 index 20fa4adab8b..00000000000 --- a/pkg/apis/feeds/v1alpha1/event_type_defaults.go +++ /dev/null @@ -1,26 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -func (et *EventType) SetDefaults() { - et.Spec.SetDefaults() -} - -func (ets *EventTypeSpec) SetDefaults() { - ets.CommonEventTypeSpec.SetDefaults() - // TODO anything? -} diff --git a/pkg/apis/feeds/v1alpha1/event_type_types.go b/pkg/apis/feeds/v1alpha1/event_type_types.go deleted file mode 100644 index 425b155902e..00000000000 --- a/pkg/apis/feeds/v1alpha1/event_type_types.go +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "encoding/json" - - "github.com/knative/pkg/apis" - "github.com/knative/pkg/webhook" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" -) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// EventType is a specification for a EventType resource -// EventSource can expose multiple event types. For example, github -// has PullRequest events as well as Issues and Comments, etc. -type EventType struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec EventTypeSpec `json:"spec"` - Status EventTypeStatus `json:"status"` -} - -// Check that EventType can be validated, can be defaulted, and has immutable fields. -var _ apis.Validatable = (*EventType)(nil) -var _ apis.Defaultable = (*EventType)(nil) -var _ apis.Immutable = (*EventType)(nil) -var _ runtime.Object = (*EventType)(nil) -var _ webhook.GenericCRD = (*EventType)(nil) - -// EventTypeSpec specifies information about the EventType, including a schema -// for the event and information about the parameters needed to create a Feed to -// the event. -type EventTypeSpec struct { - CommonEventTypeSpec `json:",inline"` - // EventSource is the name of the EventSource that produces this EventType. - EventSource string `json:"eventSource"` -} - -// EventTypeStatus is the status for a EventType resource -type EventTypeStatus struct { - CommonEventTypeStatus `json:",inline"` -} - -func (et *EventType) GetSpecJSON() ([]byte, error) { - return json.Marshal(et.Spec) -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// EventTypeList is a list of EventType resources -type EventTypeList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []EventType `json:"items"` -} diff --git a/pkg/apis/feeds/v1alpha1/event_type_validation.go b/pkg/apis/feeds/v1alpha1/event_type_validation.go deleted file mode 100644 index dd53e1b5dec..00000000000 --- a/pkg/apis/feeds/v1alpha1/event_type_validation.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "github.com/knative/pkg/apis" - "k8s.io/apimachinery/pkg/util/validation" -) - -func (et *EventType) Validate() *apis.FieldError { - return et.Spec.Validate().ViaField("spec") -} - -func (ets *EventTypeSpec) Validate() *apis.FieldError { - if ets.EventSource == "" { - return apis.ErrMissingField("eventSource") - } - if errs := validation.IsQualifiedName(ets.EventSource); len(errs) > 0 { - return apis.ErrInvalidValue(ets.EventSource, "eventSource") - } - return ets.CommonEventTypeSpec.Validate() -} - -func (current *EventType) CheckImmutableFields(og apis.Immutable) *apis.FieldError { - original, ok := og.(*EventType) - if !ok { - return &apis.FieldError{Message: "The provided original was not a EventType"} - } - if original == nil { - return nil - } - - // EventSource for an EventType should not change. - if original.Spec.EventSource != current.Spec.EventSource { - return &apis.FieldError{ - Message: "Immutable fields changed", - Paths: []string{"spec.eventSource"}, - } - } - - return nil -} diff --git a/pkg/apis/feeds/v1alpha1/event_type_validation_test.go b/pkg/apis/feeds/v1alpha1/event_type_validation_test.go deleted file mode 100644 index ff794b920f1..00000000000 --- a/pkg/apis/feeds/v1alpha1/event_type_validation_test.go +++ /dev/null @@ -1,121 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "github.com/google/go-cmp/cmp" - "github.com/knative/pkg/apis" - "testing" -) - -func TestEventTypeSpecValidation(t *testing.T) { - tests := []struct { - name string - et *EventTypeSpec - want *apis.FieldError - }{{ - name: "valid", - et: &EventTypeSpec{ - EventSource: "foo", - }, - }, { - name: "invalid source", - et: &EventTypeSpec{ - EventSource: "f@o", - }, - want: apis.ErrInvalidValue("f@o", "eventSource"), - }, { - name: "empty", - et: &EventTypeSpec{}, - want: apis.ErrMissingField("eventSource"), - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.et.Validate() - if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { - t.Errorf("validateClusterEventType (-want, +got) = %v", diff) - } - }) - } -} - -func TestEventTypeImmutableFields(t *testing.T) { - tests := []struct { - name string - new apis.Immutable - old apis.Immutable - want *apis.FieldError - }{{ - name: "good (no change)", - new: &EventType{ - Spec: EventTypeSpec{ - EventSource: "foo", - }, - }, - old: &EventType{ - Spec: EventTypeSpec{ - EventSource: "foo", - }, - }, - want: nil, - }, { - name: "good (description change)", - new: &EventType{ - Spec: EventTypeSpec{ - EventSource: "foo", - CommonEventTypeSpec: CommonEventTypeSpec{ - Description: "Foo foo foo.", - }, - }, - }, - old: &EventType{ - Spec: EventTypeSpec{ - EventSource: "foo", - CommonEventTypeSpec: CommonEventTypeSpec{ - Description: "Bar bar bar.", - }, - }, - }, - want: nil, - }, { - name: "bad (source changes)", - new: &EventType{ - Spec: EventTypeSpec{ - EventSource: "foo", - }, - }, - old: &EventType{ - Spec: EventTypeSpec{ - EventSource: "bar", - }, - }, - want: &apis.FieldError{ - Message: "Immutable fields changed", - Paths: []string{"spec.eventSource"}, - }, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.new.CheckImmutableFields(test.old) - if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { - t.Errorf("Validate (-want, +got) = %v", diff) - } - }) - } -} diff --git a/pkg/apis/feeds/v1alpha1/feed_defaults.go b/pkg/apis/feeds/v1alpha1/feed_defaults.go deleted file mode 100644 index 30f6d3c3b51..00000000000 --- a/pkg/apis/feeds/v1alpha1/feed_defaults.go +++ /dev/null @@ -1,27 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -func (f *Feed) SetDefaults() { - f.Spec.SetDefaults() -} - -func (fs *FeedSpec) SetDefaults() { - if fs.ServiceAccountName == "" { - fs.ServiceAccountName = "default" - } -} diff --git a/pkg/apis/feeds/v1alpha1/feed_defaults_test.go b/pkg/apis/feeds/v1alpha1/feed_defaults_test.go deleted file mode 100644 index 9e1d0577428..00000000000 --- a/pkg/apis/feeds/v1alpha1/feed_defaults_test.go +++ /dev/null @@ -1,79 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "github.com/google/go-cmp/cmp" - "testing" -) - -func TestFeedDefaults(t *testing.T) { - tests := []struct { - name string - f *Feed - want *Feed - }{{ - name: "valid (no change)", - f: &Feed{ - Spec: FeedSpec{ - Trigger: EventTrigger{ - EventType: "foo", - Resource: "baz", - }, - ServiceAccountName: "bar", - }, - }, - want: &Feed{ - Spec: FeedSpec{ - Trigger: EventTrigger{ - EventType: "foo", - Resource: "baz", - }, - ServiceAccountName: "bar", - }, - }, - }, { - name: "valid (default service account)", - f: &Feed{ - Spec: FeedSpec{ - Trigger: EventTrigger{ - EventType: "foo", - Resource: "baz", - }, - }, - }, - want: &Feed{ - Spec: FeedSpec{ - Trigger: EventTrigger{ - EventType: "foo", - Resource: "baz", - }, - ServiceAccountName: "default", - }, - }, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.f.DeepCopy() - got.SetDefaults() - if diff := cmp.Diff(test.want, got); diff != "" { - t.Errorf("defaultFeed (-want, +got) = %v", diff) - } - }) - } -} diff --git a/pkg/apis/feeds/v1alpha1/feed_types.go b/pkg/apis/feeds/v1alpha1/feed_types.go deleted file mode 100644 index 371ee15d377..00000000000 --- a/pkg/apis/feeds/v1alpha1/feed_types.go +++ /dev/null @@ -1,320 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "encoding/json" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/sets" - - "github.com/knative/pkg/apis" - "github.com/knative/pkg/webhook" - "k8s.io/apimachinery/pkg/runtime" -) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// Feed connects an event trigger with an action that processes events produced -// by the trigger. Feeds are building blocks used to implement Flows and are not -// expected to be used directly. -type Feed struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec FeedSpec `json:"spec"` - Status FeedStatus `json:"status"` -} - -var _ apis.Validatable = (*Feed)(nil) -var _ apis.Defaultable = (*Feed)(nil) -var _ runtime.Object = (*Feed)(nil) -var _ webhook.GenericCRD = (*Feed)(nil) - -// FeedSpec is the spec for a Feed resource. -type FeedSpec struct { - // TODO: Generation does not work correctly with CRD. They are scrubbed - // by the APIserver (https://github.com/kubernetes/kubernetes/issues/58778) - // So, we add Generation here. Once that gets fixed, remove this and use - // ObjectMeta.Generation instead. - // +optional - Generation int64 `json:"generation,omitempty"` - - // Action specifies the target handler for the events - Action FeedAction `json:"action"` - - // Trigger specifies the trigger producing events for this feed - Trigger EventTrigger `json:"trigger"` - - // Service Account to run feed container. If left out, uses "default" - ServiceAccountName string `json:"serviceAccountName,omitempty"` -} - -// FeedAction specifies the target handler - a Knative route or channel - for -// events produced by an EventTrigger. -type FeedAction struct { - // DNSName is the target for this feed. - DNSName string `json:"dnsName,omitempty"` -} - -// EventTrigger specifies the intention that a particular event type and -// resource should be consumed. -type EventTrigger struct { - // EventType or ClusterEventType Required. The type of event to observe. - // For example: - // `google.storage.object.finalize` and - // `google.firebase.analytics.event.log`. - // - // Event type consists of three parts: - // 1. namespace: The domain name of the organization in reverse-domain - // notation (e.g. `acme.net` appears as `net.acme`) and any orginization - // specific subdivisions. If the organization's top-level domain is `com`, - // the top-level domain is omitted (e.g. `google.com` appears as - // `google`). For example, `google.storage` and - // `google.firebase.analytics`. - // 2. resource type: The type of resource on which event occurs. For - // example, the Google Cloud Storage API includes the types `object` - // and `bucket`. - // 3. action: The action that generates the event. For example, actions for - // a Google Cloud Storage Object include 'finalize' and 'delete'. - // These parts are lower case and joined by '.'. - EventType string `json:"eventType"` - - // EventType or ClusterEventType Required. ClusterEventType is the same as - // EventType but Cluster scoped. - ClusterEventType string `json:"clusterEventType"` - - // Required. The resource(s) from which to observe events, for example, - // `projects/_/buckets/myBucket/objects/{objectPath=**}`. - // - // Can be a specific resource or use wildcards to match a set of resources. - // Wildcards can either match a single segment in the resource name, - // using '*', or multiple segments, using '**'. For example, - // `projects/myProject/buckets/*/objects/**` would match all objects in all - // buckets in the 'myProject' project. - // - // The contents of wildcards can also be captured. This is done by assigning - // it to a variable name in braces. For example, - // `projects/myProject/buckets/{bucket_id=*}/objects/{object_path=**}`. - // Additionally, a single segment capture can omit `=*` and a multiple segment - // capture can specify additional structure. For example, the following - // all match the same buckets, but capture different data: - // `projects/myProject/buckets/*/objects/users/*/data/**` - // `projects/myProject/buckets/{bucket_id=*}/objects/users/{user_id}/data/{data_path=**}` - // `projects/myProject/buckets/{bucket_id}/objects/{object_path=users/*/data/**}` - // - // Not all syntactically correct values are accepted by all services. For - // example: - // - // 1. The authorization model must support it. Google Cloud Functions - // only allows EventTriggers to be deployed that observe resources in the - // same project as the `CloudFunction`. - // 2. The resource type must match the pattern expected for an - // `event_type`. For example, an `EventTrigger` that has an - // `event_type` of "google.pubsub.topic.publish" should have a resource - // that matches Google Cloud Pub/Sub topics. - // - // Additionally, some services may support short names when creating an - // `EventTrigger`. These will always be returned in the normalized "long" - // format. - // - // See each *service's* documentation for supported formats. - Resource string `json:"resource"` - - // The hostname of the service that should be observed. - // - // If no string is provided, the default service implementing the API will - // be used. For example, `storage.googleapis.com` is the default for all - // event types in the 'google.storage` namespace. - Service string `json:"service"` - - // Parameters is what's necessary to create the subscription. - // This is specific to each Source. Opaque to platform, only consumed - // by the actual trigger actuator. - // NOTE: experimental field. - Parameters *runtime.RawExtension `json:"parameters,omitempty"` - - // ParametersFrom are pointers to secrets that contain sensitive - // parameters. Opaque to platform, merged in with Parameters and consumed - // by the actual trigger actuator. - // NOTE: experimental field. All secrets in ParametersFrom will be - // resolved and given to event sources in the Parameters field. - ParametersFrom []ParametersFromSource `json:"parametersFrom,omitempty"` -} - -// ParametersFromSource represents the source of a set of Parameters -// TODO: consider making this into a new secret type. -type ParametersFromSource struct { - // The Secret key to select from. - // The value must be a JSON object. - //+optional - SecretKeyRef *SecretKeyReference `json:"secretKeyRef,omitempty"` -} - -// SecretKeyReference references a key of a Secret. -type SecretKeyReference struct { - // The name of the secret in the resource's namespace to select from. - Name string `json:"name"` - // The key of the secret to select from. Must be a valid secret key. - Key string `json:"key"` -} - -// FeedStatus is the status for a Feed resource -type FeedStatus struct { - Conditions []FeedCondition `json:"conditions,omitempty"` - - // FeedContext is what the Feed operation returns and holds enough information - // for the event source to stop the Feed. - // This is specific to each Feed. Opaque to platform, only consumed - // by the actual trigger actuator. - // NOTE: experimental field. - FeedContext *runtime.RawExtension `json:"feedContext,omitempty"` -} - -type FeedConditionType string - -const ( - // FeedConditionReady specifies that the feed has started successfully. - FeedConditionReady FeedConditionType = "Ready" - - // FeedConditionDependenciesSatisfied specifies that all the dependencies for - // feed have been satisfied - FeedConditionDependenciesSatisfied FeedConditionType = "DependenciesSatisfied" -) - -// FeedCondition defines a readiness condition for a Feed. -// See: https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#typical-status-properties -type FeedCondition struct { - Type FeedConditionType `json:"type"` - - Status corev1.ConditionStatus `json:"status" description:"status of the condition, one of True, False, Unknown"` - // +optional - Reason string `json:"reason,omitempty" description:"one-word CamelCase reason for the condition's last transition"` - // +optional - Message string `json:"message,omitempty" description:"human-readable message indicating details about last transition"` -} - -func (fs *FeedStatus) GetCondition(t FeedConditionType) *FeedCondition { - for _, cond := range fs.Conditions { - if cond.Type == t { - return &cond - } - } - return nil -} - -func (fs *FeedStatus) SetCondition(new *FeedCondition) { - if new == nil || new.Type == "" { - return - } - - t := new.Type - var conditions []FeedCondition - for _, cond := range fs.Conditions { - if cond.Type != t { - conditions = append(conditions, cond) - } - } - conditions = append(conditions, *new) - fs.Conditions = conditions -} - -func (fs *FeedStatus) RemoveCondition(t FeedConditionType) { - var conditions []FeedCondition - for _, cond := range fs.Conditions { - if cond.Type != t { - conditions = append(conditions, cond) - } - } - fs.Conditions = conditions -} - -func (fs *FeedStatus) InitializeConditions() { - for _, cond := range []FeedConditionType{ - FeedConditionReady, - } { - if fc := fs.GetCondition(cond); fc == nil { - fs.SetCondition(&FeedCondition{ - Type: cond, - Status: corev1.ConditionUnknown, - }) - } - } -} - -// AddFinalizer adds the given value to the list of finalizers if it doesn't -// already exist. -func (f *Feed) AddFinalizer(value string) { - finalizers := sets.NewString(f.GetFinalizers()...) - finalizers.Insert(value) - f.SetFinalizers(finalizers.List()) -} - -// RemoveFinalizer removes the given value from the list of finalizers if it -// exists. -func (f *Feed) RemoveFinalizer(value string) { - finalizers := sets.NewString(f.GetFinalizers()...) - finalizers.Delete(value) - if finalizers.Len() == 0 { - // if no finalizers, set to nil list, not an empty slice. - f.SetFinalizers([]string(nil)) - } else { - f.SetFinalizers(finalizers.List()) - } -} - -// HasFinalizer returns true if a finalizer exists, or false otherwise. -func (f *Feed) HasFinalizer(value string) bool { - for _, f := range f.GetFinalizers() { - if f == value { - return true - } - } - return false -} - -// SetOwnerReference adds the given owner reference to the list of owner -// references, replacing the corresponding owner reference if it exists. -func (f *Feed) SetOwnerReference(or *metav1.OwnerReference) { - var refs []metav1.OwnerReference - - for _, ref := range f.GetOwnerReferences() { - if !(ref.APIVersion == or.APIVersion && - ref.Kind == or.Kind && - ref.Name == or.Name) { - refs = append(refs, ref) - } - } - refs = append(refs, *or) - f.SetOwnerReferences(refs) -} - -func (f *Feed) GetSpecJSON() ([]byte, error) { - return json.Marshal(f.Spec) -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// FeedList is a list of Feed resources -type FeedList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []Feed `json:"items"` -} diff --git a/pkg/apis/feeds/v1alpha1/feed_types_test.go b/pkg/apis/feeds/v1alpha1/feed_types_test.go deleted file mode 100644 index 37068267b21..00000000000 --- a/pkg/apis/feeds/v1alpha1/feed_types_test.go +++ /dev/null @@ -1,112 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "fmt" - "testing" -) - -func TestFeedCondition_GetConditionNotFound(t *testing.T) { - feed := Feed{} - if feed.Status.GetCondition(FeedConditionReady) != nil { - t.Fatalf("Got a non-nil for non-existent conditiontype") - } -} - -func TestFeedCondition_GetCondition(t *testing.T) { - testcases := []struct { - name string - types []FeedConditionType - get FeedConditionType - want FeedConditionType - }{ - {"FeedConditionReady", []FeedConditionType{FeedConditionReady}, FeedConditionReady, FeedConditionReady}, - } - - for _, tc := range testcases { - testName := fmt.Sprintf("%s - %s", "Feed", tc.name) - t.Run(testName, func(t *testing.T) { - feed := Feed{} - for _, t := range tc.types { - c := &FeedCondition{Type: t} - feed.Status.SetCondition(c) - } - - if want, got := tc.want, feed.Status.GetCondition(tc.get).Type; want != got { - t.Fatalf("Failed to get expected condition. \nwant:\t%#v\ngot:\t%#v", want, got) - } - }) - } -} - -func TestFeedCondition_SetCondition(t *testing.T) { - testcases := []struct { - name string - types []FeedConditionType - want int - }{ - {"One", []FeedConditionType{FeedConditionReady}, 1}, - {"Replace", []FeedConditionType{FeedConditionReady, FeedConditionReady}, 1}, - {"Invalid", []FeedConditionType{""}, 0}, - } - - for _, tc := range testcases { - testName := fmt.Sprintf("%s - %s", "Feed", tc.name) - t.Run(testName, func(t *testing.T) { - feed := Feed{} - for _, t := range tc.types { - c := &FeedCondition{Type: t} - feed.Status.SetCondition(c) - } - if want, got := tc.want, len(feed.Status.Conditions); want != got { - t.Fatalf("Failed to return expected number of conditions. \nwant:\t%#v\ngot:\t%#v", want, got) - } - }) - } -} - -func TestFeedCondition_RemoveCondition(t *testing.T) { - testcases := []struct { - name string - set []FeedConditionType - remove []FeedConditionType - want int - }{ - {"RemoveOne", []FeedConditionType{FeedConditionReady}, []FeedConditionType{FeedConditionReady}, 0}, - {"RemoveNonExistent", []FeedConditionType{FeedConditionReady}, []FeedConditionType{"notthere"}, 1}, - {"Invalid", []FeedConditionType{FeedConditionReady}, []FeedConditionType{""}, 1}, - } - - for _, tc := range testcases { - testName := fmt.Sprintf("%s - %s", "Feed", tc.name) - t.Run(testName, func(t *testing.T) { - feed := Feed{} - for _, t := range tc.set { - c := &FeedCondition{Type: t} - feed.Status.SetCondition(c) - } - for _, t := range tc.remove { - feed.Status.RemoveCondition(t) - } - - if want, got := tc.want, len(feed.Status.Conditions); want != got { - t.Fatalf("Failed to return expected number of conditions. \nwant:\t%#v\ngot:\t%#v", want, got) - } - }) - } -} diff --git a/pkg/apis/feeds/v1alpha1/feed_validation.go b/pkg/apis/feeds/v1alpha1/feed_validation.go deleted file mode 100644 index c8d2ff879f4..00000000000 --- a/pkg/apis/feeds/v1alpha1/feed_validation.go +++ /dev/null @@ -1,72 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "github.com/knative/pkg/apis" - - "k8s.io/apimachinery/pkg/util/validation" - "strings" -) - -func (f *Feed) Validate() *apis.FieldError { - return f.Spec.Validate().ViaField("spec") -} - -func (fs *FeedSpec) Validate() *apis.FieldError { - if err := fs.Trigger.Validate(); err != nil { - return err.ViaField("trigger") - } - if err := fs.Action.Validate(); err != nil { - return err.ViaField("action") - } - return nil -} - -func (et *EventTrigger) Validate() *apis.FieldError { - switch { - case len(et.EventType) != 0 && len(et.ClusterEventType) != 0: - return apis.ErrMultipleOneOf("eventType", "clusterEventType") - case len(et.EventType) != 0: - if errs := validation.IsQualifiedName(et.EventType); len(errs) > 0 { - return apis.ErrInvalidKeyName(et.EventType, "eventType", errs...) - } - case len(et.ClusterEventType) != 0: - if errs := validation.IsQualifiedName(et.ClusterEventType); len(errs) > 0 { - return apis.ErrInvalidKeyName(et.ClusterEventType, "clusterEventType", errs...) - } - default: - return apis.ErrMissingOneOf("eventType", "clusterEventType") - } - - if et.Resource == "" { - return apis.ErrMissingField("resource") - } - - return nil -} - -func (fa *FeedAction) Validate() *apis.FieldError { - if len(fa.DNSName) != 0 { - if errs := validation.IsDNS1123Subdomain(fa.DNSName); len(errs) > 0 { - err := apis.ErrInvalidValue(fa.DNSName, "dnsName") - err.Details = strings.Join(errs, ", ") - return err - } - } - return nil -} diff --git a/pkg/apis/feeds/v1alpha1/feed_validation_test.go b/pkg/apis/feeds/v1alpha1/feed_validation_test.go deleted file mode 100644 index c52e06ecae5..00000000000 --- a/pkg/apis/feeds/v1alpha1/feed_validation_test.go +++ /dev/null @@ -1,118 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "github.com/google/go-cmp/cmp" - "github.com/knative/pkg/apis" - "testing" -) - -func TestFeedSpecValidation(t *testing.T) { - tests := []struct { - name string - f *FeedSpec - want *apis.FieldError - }{{ - name: "valid namespaced", - f: &FeedSpec{ - Trigger: EventTrigger{ - EventType: "foo", - Resource: "baz", - }, - }, - }, { - name: "valid cluster", - f: &FeedSpec{ - Trigger: EventTrigger{ - ClusterEventType: "foo", - Resource: "baz", - }, - }, - }, { - name: "empty", - f: &FeedSpec{}, - want: apis.ErrMissingOneOf("eventType", "clusterEventType").ViaField("trigger"), - }, { - name: "empty trigger", - f: &FeedSpec{Trigger: EventTrigger{}}, - want: apis.ErrMissingOneOf("eventType", "clusterEventType").ViaField("trigger"), - }, { - name: "mutually exclusive missing", - f: &FeedSpec{ - ServiceAccountName: "Sue", - Trigger: EventTrigger{ - Resource: "baz", - }, - }, - want: apis.ErrMissingOneOf("eventType", "clusterEventType").ViaField("trigger"), - }, { - name: "mutually exclusive both", - f: &FeedSpec{ - Trigger: EventTrigger{ - EventType: "foo", - ClusterEventType: "bar", - Resource: "baz", - }, - }, - want: apis.ErrMultipleOneOf("eventType", "clusterEventType").ViaField("trigger"), - }, { - name: "valid dns name", - f: &FeedSpec{ - Trigger: EventTrigger{ - EventType: "foo", - Resource: "baz", - }, - Action: FeedAction{ - DNSName: "valid.com", - }, - }, - }, { - name: "missing trigger.resource", - f: &FeedSpec{ - Trigger: EventTrigger{ - EventType: "foo", - }, - }, - want: apis.ErrMissingField("resource").ViaField("trigger"), - }, { - name: "invalid dns name", - f: &FeedSpec{ - Trigger: EventTrigger{ - EventType: "foo", - Resource: "baz", - }, - Action: FeedAction{ - DNSName: "inv@lid.com", - }, - }, - want: &apis.FieldError{ - Message: `invalid value "inv@lid.com"`, - Paths: []string{"action.dnsName"}, - Details: "a DNS-1123 subdomain must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character (e.g. 'example.com', regex used for validation is '[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*')", - }, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.f.Validate() - if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { - t.Errorf("validateFeed (-want, +got) = %v", diff) - } - }) - } -} diff --git a/pkg/apis/feeds/v1alpha1/register.go b/pkg/apis/feeds/v1alpha1/register.go deleted file mode 100644 index c5a15aa2f09..00000000000 --- a/pkg/apis/feeds/v1alpha1/register.go +++ /dev/null @@ -1,61 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "github.com/knative/eventing/pkg/apis/feeds" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -// SchemeGroupVersion is group version used to register these objects -var SchemeGroupVersion = schema.GroupVersion{Group: feeds.GroupName, Version: "v1alpha1"} - -// Kind takes an unqualified kind and returns back a Group qualified GroupKind -func Kind(kind string) schema.GroupKind { - return SchemeGroupVersion.WithKind(kind).GroupKind() -} - -// Resource takes an unqualified resource and returns a Group qualified GroupResource -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} - -var ( - SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) - AddToScheme = SchemeBuilder.AddToScheme -) - -// Adds the list of known types to Scheme. -func addKnownTypes(scheme *runtime.Scheme) error { - scheme.AddKnownTypes(SchemeGroupVersion, - &ClusterEventSource{}, - &ClusterEventSourceList{}, - &ClusterEventType{}, - &ClusterEventTypeList{}, - &Feed{}, - &FeedList{}, - &EventSource{}, - &EventSourceList{}, - &EventType{}, - &EventTypeList{}, - ) - metav1.AddToGroupVersion(scheme, SchemeGroupVersion) - return nil -} diff --git a/pkg/apis/feeds/v1alpha1/zz_generated.deepcopy.go b/pkg/apis/feeds/v1alpha1/zz_generated.deepcopy.go deleted file mode 100644 index eefd57179a4..00000000000 --- a/pkg/apis/feeds/v1alpha1/zz_generated.deepcopy.go +++ /dev/null @@ -1,752 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by deepcopy-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterEventSource) DeepCopyInto(out *ClusterEventSource) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterEventSource. -func (in *ClusterEventSource) DeepCopy() *ClusterEventSource { - if in == nil { - return nil - } - out := new(ClusterEventSource) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ClusterEventSource) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterEventSourceList) DeepCopyInto(out *ClusterEventSourceList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]ClusterEventSource, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterEventSourceList. -func (in *ClusterEventSourceList) DeepCopy() *ClusterEventSourceList { - if in == nil { - return nil - } - out := new(ClusterEventSourceList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ClusterEventSourceList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterEventSourceSpec) DeepCopyInto(out *ClusterEventSourceSpec) { - *out = *in - in.CommonEventSourceSpec.DeepCopyInto(&out.CommonEventSourceSpec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterEventSourceSpec. -func (in *ClusterEventSourceSpec) DeepCopy() *ClusterEventSourceSpec { - if in == nil { - return nil - } - out := new(ClusterEventSourceSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterEventSourceStatus) DeepCopyInto(out *ClusterEventSourceStatus) { - *out = *in - in.CommonEventSourceStatus.DeepCopyInto(&out.CommonEventSourceStatus) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterEventSourceStatus. -func (in *ClusterEventSourceStatus) DeepCopy() *ClusterEventSourceStatus { - if in == nil { - return nil - } - out := new(ClusterEventSourceStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterEventType) DeepCopyInto(out *ClusterEventType) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterEventType. -func (in *ClusterEventType) DeepCopy() *ClusterEventType { - if in == nil { - return nil - } - out := new(ClusterEventType) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ClusterEventType) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterEventTypeList) DeepCopyInto(out *ClusterEventTypeList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]ClusterEventType, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterEventTypeList. -func (in *ClusterEventTypeList) DeepCopy() *ClusterEventTypeList { - if in == nil { - return nil - } - out := new(ClusterEventTypeList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ClusterEventTypeList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterEventTypeSpec) DeepCopyInto(out *ClusterEventTypeSpec) { - *out = *in - in.CommonEventTypeSpec.DeepCopyInto(&out.CommonEventTypeSpec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterEventTypeSpec. -func (in *ClusterEventTypeSpec) DeepCopy() *ClusterEventTypeSpec { - if in == nil { - return nil - } - out := new(ClusterEventTypeSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterEventTypeStatus) DeepCopyInto(out *ClusterEventTypeStatus) { - *out = *in - in.CommonEventTypeStatus.DeepCopyInto(&out.CommonEventTypeStatus) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterEventTypeStatus. -func (in *ClusterEventTypeStatus) DeepCopy() *ClusterEventTypeStatus { - if in == nil { - return nil - } - out := new(ClusterEventTypeStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CommonEventSourceCondition) DeepCopyInto(out *CommonEventSourceCondition) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CommonEventSourceCondition. -func (in *CommonEventSourceCondition) DeepCopy() *CommonEventSourceCondition { - if in == nil { - return nil - } - out := new(CommonEventSourceCondition) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CommonEventSourceSpec) DeepCopyInto(out *CommonEventSourceSpec) { - *out = *in - if in.Parameters != nil { - in, out := &in.Parameters, &out.Parameters - if *in == nil { - *out = nil - } else { - *out = new(runtime.RawExtension) - (*in).DeepCopyInto(*out) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CommonEventSourceSpec. -func (in *CommonEventSourceSpec) DeepCopy() *CommonEventSourceSpec { - if in == nil { - return nil - } - out := new(CommonEventSourceSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CommonEventSourceStatus) DeepCopyInto(out *CommonEventSourceStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make([]CommonEventSourceCondition, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CommonEventSourceStatus. -func (in *CommonEventSourceStatus) DeepCopy() *CommonEventSourceStatus { - if in == nil { - return nil - } - out := new(CommonEventSourceStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CommonEventTypeCondition) DeepCopyInto(out *CommonEventTypeCondition) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CommonEventTypeCondition. -func (in *CommonEventTypeCondition) DeepCopy() *CommonEventTypeCondition { - if in == nil { - return nil - } - out := new(CommonEventTypeCondition) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CommonEventTypeSpec) DeepCopyInto(out *CommonEventTypeSpec) { - *out = *in - if in.SubscribeSchema != nil { - in, out := &in.SubscribeSchema, &out.SubscribeSchema - if *in == nil { - *out = nil - } else { - *out = new(runtime.RawExtension) - (*in).DeepCopyInto(*out) - } - } - if in.EventSchema != nil { - in, out := &in.EventSchema, &out.EventSchema - if *in == nil { - *out = nil - } else { - *out = new(runtime.RawExtension) - (*in).DeepCopyInto(*out) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CommonEventTypeSpec. -func (in *CommonEventTypeSpec) DeepCopy() *CommonEventTypeSpec { - if in == nil { - return nil - } - out := new(CommonEventTypeSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CommonEventTypeStatus) DeepCopyInto(out *CommonEventTypeStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make([]CommonEventTypeCondition, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CommonEventTypeStatus. -func (in *CommonEventTypeStatus) DeepCopy() *CommonEventTypeStatus { - if in == nil { - return nil - } - out := new(CommonEventTypeStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *EventSource) DeepCopyInto(out *EventSource) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EventSource. -func (in *EventSource) DeepCopy() *EventSource { - if in == nil { - return nil - } - out := new(EventSource) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *EventSource) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *EventSourceList) DeepCopyInto(out *EventSourceList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]EventSource, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EventSourceList. -func (in *EventSourceList) DeepCopy() *EventSourceList { - if in == nil { - return nil - } - out := new(EventSourceList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *EventSourceList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *EventSourceSpec) DeepCopyInto(out *EventSourceSpec) { - *out = *in - in.CommonEventSourceSpec.DeepCopyInto(&out.CommonEventSourceSpec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EventSourceSpec. -func (in *EventSourceSpec) DeepCopy() *EventSourceSpec { - if in == nil { - return nil - } - out := new(EventSourceSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *EventSourceStatus) DeepCopyInto(out *EventSourceStatus) { - *out = *in - in.CommonEventSourceStatus.DeepCopyInto(&out.CommonEventSourceStatus) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EventSourceStatus. -func (in *EventSourceStatus) DeepCopy() *EventSourceStatus { - if in == nil { - return nil - } - out := new(EventSourceStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *EventTrigger) DeepCopyInto(out *EventTrigger) { - *out = *in - if in.Parameters != nil { - in, out := &in.Parameters, &out.Parameters - if *in == nil { - *out = nil - } else { - *out = new(runtime.RawExtension) - (*in).DeepCopyInto(*out) - } - } - if in.ParametersFrom != nil { - in, out := &in.ParametersFrom, &out.ParametersFrom - *out = make([]ParametersFromSource, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EventTrigger. -func (in *EventTrigger) DeepCopy() *EventTrigger { - if in == nil { - return nil - } - out := new(EventTrigger) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *EventType) DeepCopyInto(out *EventType) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EventType. -func (in *EventType) DeepCopy() *EventType { - if in == nil { - return nil - } - out := new(EventType) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *EventType) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *EventTypeList) DeepCopyInto(out *EventTypeList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]EventType, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EventTypeList. -func (in *EventTypeList) DeepCopy() *EventTypeList { - if in == nil { - return nil - } - out := new(EventTypeList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *EventTypeList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *EventTypeSpec) DeepCopyInto(out *EventTypeSpec) { - *out = *in - in.CommonEventTypeSpec.DeepCopyInto(&out.CommonEventTypeSpec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EventTypeSpec. -func (in *EventTypeSpec) DeepCopy() *EventTypeSpec { - if in == nil { - return nil - } - out := new(EventTypeSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *EventTypeStatus) DeepCopyInto(out *EventTypeStatus) { - *out = *in - in.CommonEventTypeStatus.DeepCopyInto(&out.CommonEventTypeStatus) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EventTypeStatus. -func (in *EventTypeStatus) DeepCopy() *EventTypeStatus { - if in == nil { - return nil - } - out := new(EventTypeStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Feed) DeepCopyInto(out *Feed) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Feed. -func (in *Feed) DeepCopy() *Feed { - if in == nil { - return nil - } - out := new(Feed) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Feed) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *FeedAction) DeepCopyInto(out *FeedAction) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FeedAction. -func (in *FeedAction) DeepCopy() *FeedAction { - if in == nil { - return nil - } - out := new(FeedAction) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *FeedCondition) DeepCopyInto(out *FeedCondition) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FeedCondition. -func (in *FeedCondition) DeepCopy() *FeedCondition { - if in == nil { - return nil - } - out := new(FeedCondition) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *FeedList) DeepCopyInto(out *FeedList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Feed, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FeedList. -func (in *FeedList) DeepCopy() *FeedList { - if in == nil { - return nil - } - out := new(FeedList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *FeedList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *FeedSpec) DeepCopyInto(out *FeedSpec) { - *out = *in - out.Action = in.Action - in.Trigger.DeepCopyInto(&out.Trigger) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FeedSpec. -func (in *FeedSpec) DeepCopy() *FeedSpec { - if in == nil { - return nil - } - out := new(FeedSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *FeedStatus) DeepCopyInto(out *FeedStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make([]FeedCondition, len(*in)) - copy(*out, *in) - } - if in.FeedContext != nil { - in, out := &in.FeedContext, &out.FeedContext - if *in == nil { - *out = nil - } else { - *out = new(runtime.RawExtension) - (*in).DeepCopyInto(*out) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FeedStatus. -func (in *FeedStatus) DeepCopy() *FeedStatus { - if in == nil { - return nil - } - out := new(FeedStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ParametersFromSource) DeepCopyInto(out *ParametersFromSource) { - *out = *in - if in.SecretKeyRef != nil { - in, out := &in.SecretKeyRef, &out.SecretKeyRef - if *in == nil { - *out = nil - } else { - *out = new(SecretKeyReference) - **out = **in - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ParametersFromSource. -func (in *ParametersFromSource) DeepCopy() *ParametersFromSource { - if in == nil { - return nil - } - out := new(ParametersFromSource) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SecretKeyReference) DeepCopyInto(out *SecretKeyReference) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SecretKeyReference. -func (in *SecretKeyReference) DeepCopy() *SecretKeyReference { - if in == nil { - return nil - } - out := new(SecretKeyReference) - in.DeepCopyInto(out) - return out -} diff --git a/pkg/apis/flows/logkey/constants.go b/pkg/apis/flows/logkey/constants.go deleted file mode 100644 index 1136af2097b..00000000000 --- a/pkg/apis/flows/logkey/constants.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright 2018 The Knative 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 logkey - -const ( - kNative = "knative.dev/" - - // Flow is the key used for flow name in structured logs - Flow = kNative + "flow" -) diff --git a/pkg/apis/flows/v1alpha1/doc.go b/pkg/apis/flows/v1alpha1/doc.go deleted file mode 100644 index 21b483017e4..00000000000 --- a/pkg/apis/flows/v1alpha1/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// +k8s:deepcopy-gen=package -// Package v1alpha1 is the v1alpha1 version of the API. -// +groupName=flows.knative.dev -package v1alpha1 diff --git a/pkg/apis/flows/v1alpha1/flow_defaults.go b/pkg/apis/flows/v1alpha1/flow_defaults.go deleted file mode 100644 index d02436f284d..00000000000 --- a/pkg/apis/flows/v1alpha1/flow_defaults.go +++ /dev/null @@ -1,34 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -func (f *Flow) SetDefaults() { - f.Spec.SetDefaults() -} - -func (fs *FlowSpec) SetDefaults() { - fs.Action.SetDefaults() - fs.Trigger.SetDefaults() -} - -func (fa *FlowAction) SetDefaults() { - // nothing to do -} - -func (et *EventTrigger) SetDefaults() { - // // nothing to do -} diff --git a/pkg/apis/flows/v1alpha1/flow_types.go b/pkg/apis/flows/v1alpha1/flow_types.go deleted file mode 100644 index bbb6882ac18..00000000000 --- a/pkg/apis/flows/v1alpha1/flow_types.go +++ /dev/null @@ -1,410 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "encoding/json" - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - feedsv1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - "github.com/knative/pkg/apis" - "github.com/knative/pkg/webhook" - "k8s.io/apimachinery/pkg/runtime" -) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// Flow connects an event source with an action that processes events produced -// by the event source. The flow controller handles creating the lower-level -// eventing primitives (Feeds, Channels, Subscriptions) used to implement flows. -type Flow struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec FlowSpec `json:"spec"` - Status FlowStatus `json:"status"` -} - -// Check that Flow can be validated and can be defaulted. -var _ apis.Validatable = (*Flow)(nil) -var _ apis.Defaultable = (*Flow)(nil) -var _ runtime.Object = (*Flow)(nil) -var _ webhook.GenericCRD = (*Flow)(nil) - -// FlowSpec is the spec for a Flow resource. -type FlowSpec struct { - // TODO: Generation does not work correctly with CRD. They are scrubbed - // by the APIserver (https://github.com/kubernetes/kubernetes/issues/58778) - // So, we add Generation here. Once that gets fixed, remove this and use - // ObjectMeta.Generation instead. - // +optional - Generation int64 `json:"generation,omitempty"` - - // Action specifies the target handler for the events - Action FlowAction `json:"action"` - - // Trigger specifies the trigger we're creating a Flow to - Trigger EventTrigger `json:"trigger"` - - // Service Account to use when creating the underlying Feed. - // If left out, uses "default" - ServiceAccountName string `json:"serviceAccountName,omitempty"` -} - -// FlowAction specifies the reference to an object that's expected to -// provide the resolved target of the action. Currently we inspect -// the objects Status and see if there's a predefined Status field -// that we will then use to give to Feed object as the target. Currently -// must resolve to a k8s service or Istio virtual service. Note that by -// in the future we should try to utilize subresources (/resolve ?) to -// utilize this, but CRDs do not support subresources yet, so we need -// to rely on a specified Status field today. By relying on this behaviour -// we can utilize a dynamic client instead of having to understand all -// kinds of different types of objects. As long as they adhere to this -// particular contract, they can be used as a Target. -// To ensure that we can support external targets and for ease of use -// we also allow for an URI to be specified. -type FlowAction struct { - // Only one of these can be specified - - // Reference to an object that will be used to find the target - // endpoint. - // For example, this could be a reference to a Route resource - // or a Configuration resource. - // TODO: Specify the required fields the target object must - // have in the status. - // You can specify only the following fields of the ObjectReference: - // - Kind - // - APIVersion - // - Name - // +optional - Target *corev1.ObjectReference `json:"target,omitempty"` - - // Reference to a 'known' endpoint where no resolving be done. - // http://k8s-service for example - // http://myexternalhandler.example.com/foo/bar - // +optional - TargetURI *string `json:"targetURI,omitempty"` -} - -// EventTrigger specifies the intention that a particular event type and -// resource should be consumed. -type EventTrigger struct { - // Required. The type of event to observe. For example: - // `google.storage.object.finalize` and - // `google.firebase.analytics.event.log`. - // - // Event type consists of three parts: - // 1. namespace: The domain name of the organization in reverse-domain - // notation (e.g. `acme.net` appears as `net.acme`) and any orginization - // specific subdivisions. If the organization's top-level domain is `com`, - // the top-level domain is omitted (e.g. `google.com` appears as - // `google`). For example, `google.storage` and - // `google.firebase.analytics`. - // 2. resource type: The type of resource on which event occurs. For - // example, the Google Cloud Storage API includes the types `object` - // and `bucket`. - // 3. action: The action that generates the event. For example, actions for - // a Google Cloud Storage Object include 'finalize' and 'delete'. - // These parts are lower case and joined by '.'. - EventType string `json:"eventType"` - - // Required. The resource(s) from which to observe events, for example, - // `projects/_/buckets/myBucket/objects/{objectPath=**}`. - // - // Can be a specific resource or use wildcards to match a set of resources. - // Wildcards can either match a single segment in the resource name, - // using '*', or multiple segments, using '**'. For example, - // `projects/myProject/buckets/*/objects/**` would match all objects in all - // buckets in the 'myProject' project. - // - // The contents of wildcards can also be captured. This is done by assigning - // it to a variable name in braces. For example, - // `projects/myProject/buckets/{bucket_id=*}/objects/{object_path=**}`. - // Additionally, a single segment capture can omit `=*` and a multiple segment - // capture can specify additional structure. For example, the following - // all match the same buckets, but capture different data: - // `projects/myProject/buckets/*/objects/users/*/data/**` - // `projects/myProject/buckets/{bucket_id=*}/objects/users/{user_id}/data/{data_path=**}` - // `projects/myProject/buckets/{bucket_id}/objects/{object_path=users/*/data/**}` - // - // Not all syntactically correct values are accepted by all services. For - // example: - // - // 1. The authorization model must support it. Google Cloud Functions - // only allows EventTriggers to be deployed that observe resources in the - // same project as the `CloudFunction`. - // 2. The resource type must match the pattern expected for an - // `event_type`. For example, an `EventTrigger` that has an - // `event_type` of "google.pubsub.topic.publish" should have a resource - // that matches Google Cloud Pub/Sub topics. - // - // Additionally, some services may support short names when creating an - // `EventTrigger`. These will always be returned in the normalized "long" - // format. - // - // See each *service's* documentation for supported formats. - Resource string `json:"resource"` - - // The hostname of the service that should be observed. - // - // If no string is provided, the default service implementing the API will - // be used. For example, `storage.googleapis.com` is the default for all - // event types in the 'google.storage` namespace. - Service string `json:"service"` - - // Parameters is what's necessary to create the subscription. - // This is specific to each Source. Opaque to platform, only consumed - // by the actual trigger actuator. - // NOTE: experimental field. - Parameters *runtime.RawExtension `json:"parameters,omitempty"` - - // ParametersFrom are pointers to secrets that contain sensitive - // parameters. Opaque to platform, merged in with Parameters and consumed - // by the actual trigger actuator. - // NOTE: experimental field. All secrets in ParametersFrom will be - // resolved and given to event sources in the Parameters field. - ParametersFrom []feedsv1alpha1.ParametersFromSource `json:"parametersFrom,omitempty"` -} - -// FlowStatus is the status for a Flow resource -type FlowStatus struct { - Conditions []FlowCondition `json:"conditions,omitempty"` - - // FlowContext is what the Flow operation returns and holds enough information - // to perform cleanup once a Flow is deleted. - // NOTE: experimental field. - FlowContext *runtime.RawExtension `json:"flowContext,omitempty"` - - // ChannelTarget is the name of the target channel - ChannelTarget string `json:"channelTarget,omitempty"` - - // ObservedGeneration is the 'Generation' of the Flow that - // was last reconciled by the controller. - // +optional - ObservedGeneration int64 `json:"observedGeneration,omitempty"` -} - -type FlowConditionType string - -const ( - // FlowConditionReady specifies that the Flow has been configured successfully. - FlowConditionReady FlowConditionType = "Ready" - - // FlowConditionFeedReady specifies that the Feed has been configured successfully. - FlowConditionFeedReady FlowConditionType = "FeedReady" - - // FlowConditionChannelReady specifies that the Channel has been configured successfully. - FlowConditionChannelReady FlowConditionType = "ChannelReady" - - // FlowConditionSubscriptionReady specifies that the Subscription has been configured successfully. - FlowConditionSubscriptionReady FlowConditionType = "SubscriptionReady" - - // FlowConditionActionTargetResolved specifies that the Action Target has been resolved - FlowConditionActionTargetResolved FlowConditionType = "ActionTargetResolved" -) - -// FlowCondition defines a readiness condition for a Flow. -// See: https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#typical-status-properties -type FlowCondition struct { - Type FlowConditionType `json:"type"` - - Status corev1.ConditionStatus `json:"status" description:"status of the condition, one of True, False, Unknown"` - // +optional - Reason string `json:"reason,omitempty" description:"one-word CamelCase reason for the condition's last transition"` - // +optional - Message string `json:"message,omitempty" description:"human-readable message indicating details about last transition"` -} - -func (fs *FlowStatus) IsReady() bool { - if c := fs.GetCondition(FlowConditionReady); c != nil { - return c.Status == corev1.ConditionTrue - } - return false -} - -func (fs *FlowStatus) GetCondition(t FlowConditionType) *FlowCondition { - for _, cond := range fs.Conditions { - if cond.Type == t { - return &cond - } - } - return nil -} - -func (fs *FlowStatus) setCondition(new *FlowCondition) { - if new == nil || new.Type == "" { - return - } - - t := new.Type - var conditions []FlowCondition - for _, cond := range fs.Conditions { - if cond.Type != t { - conditions = append(conditions, cond) - } - } - conditions = append(conditions, *new) - fs.Conditions = conditions -} - -func (fs *FlowStatus) removeCondition(t FlowConditionType) { - var conditions []FlowCondition - for _, cond := range fs.Conditions { - if cond.Type != t { - conditions = append(conditions, cond) - } - } - fs.Conditions = conditions -} - -func (fs *FlowStatus) PropagateActionTargetResolved(status corev1.ConditionStatus, reason string, message string) { - fs.setCondition(&FlowCondition{ - Type: FlowConditionActionTargetResolved, - Status: status, - Reason: reason, - Message: message, - }) - fs.checkAndMarkReady() -} - -func (fs *FlowStatus) InitializeConditions() { - for _, cond := range []FlowConditionType{ - FlowConditionReady, - } { - if fc := fs.GetCondition(cond); fc == nil { - fs.setCondition(&FlowCondition{ - Type: cond, - Status: corev1.ConditionUnknown, - }) - } - } -} - -func (fs *FlowStatus) PropagateChannelStatus(cs channelsv1alpha1.ChannelStatus) { - cc := cs.GetCondition(channelsv1alpha1.ChannelReady) - - if cc == nil { - return - } - - fst := []FlowConditionType{FlowConditionChannelReady} - // If the underlying channel reported not ready, then bubble it up. - if cc.Status != corev1.ConditionTrue { - fst = append(fst, FlowConditionReady) - } - - for _, cond := range fst { - fs.setCondition(&FlowCondition{ - Type: cond, - Status: cc.Status, - Reason: cc.Reason, - Message: cc.Message, - }) - } - - fs.ChannelTarget = cs.DomainInternal - - fs.checkAndMarkReady() -} - -func (fs *FlowStatus) PropagateSubscriptionStatus(ss channelsv1alpha1.SubscriptionStatus) { - sc := ss.GetCondition(channelsv1alpha1.SubscriptionDispatching) - - if sc == nil { - return - } - - fst := []FlowConditionType{FlowConditionSubscriptionReady} - // If the underlying subscription reported not ready, then bubble it up. - if sc.Status != corev1.ConditionTrue { - fst = append(fst, FlowConditionReady) - } - - for _, cond := range fst { - fs.setCondition(&FlowCondition{ - Type: cond, - Status: sc.Status, - Reason: sc.Reason, - Message: sc.Message, - }) - } - - fs.checkAndMarkReady() -} - -func (fs *FlowStatus) PropagateFeedStatus(s feedsv1alpha1.FeedStatus) { - // Check to see if Feed is ready - fc := s.GetCondition(feedsv1alpha1.FeedConditionReady) - - if fc == nil { - return - } - fst := []FlowConditionType{FlowConditionFeedReady} - // If the underlying Feed reported not ready, then bubble it up. - if fc.Status != corev1.ConditionTrue { - fst = append(fst, FlowConditionReady) - } - for _, cond := range fst { - fs.setCondition(&FlowCondition{ - Type: cond, - Status: fc.Status, - Reason: fc.Reason, - Message: fc.Message, - }) - } - fs.checkAndMarkReady() -} - -func (fs *FlowStatus) checkAndMarkReady() { - for _, cond := range []FlowConditionType{ - FlowConditionFeedReady, - FlowConditionChannelReady, - FlowConditionSubscriptionReady, - FlowConditionActionTargetResolved, - } { - c := fs.GetCondition(cond) - if c == nil || c.Status != corev1.ConditionTrue { - return - } - } - fs.markReady() -} - -func (fs *FlowStatus) markReady() { - fs.setCondition(&FlowCondition{ - Type: FlowConditionReady, - Status: corev1.ConditionTrue, - }) -} - -func (f *Flow) GetSpecJSON() ([]byte, error) { - return json.Marshal(f.Spec) -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// FlowList is a list of Flow resources -type FlowList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []Flow `json:"items"` -} diff --git a/pkg/apis/flows/v1alpha1/flow_types_test.go b/pkg/apis/flows/v1alpha1/flow_types_test.go deleted file mode 100644 index 9dfc652aff5..00000000000 --- a/pkg/apis/flows/v1alpha1/flow_types_test.go +++ /dev/null @@ -1,356 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "fmt" - "testing" - - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - feedsv1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - corev1 "k8s.io/api/core/v1" -) - -const ( - actionTargetResolveFailMessage = "action target failed to resolve" - actionTargetResolveSuccessMessage = "action target resolved" - - actionTargetResolveFailReason = "ActionTargetResolveFailed" - actionTargetResolveSuccessReason = "ActionTargetResolveSucceeded" -) - -func TestFlowCondition_GetConditionNotFound(t *testing.T) { - flow := Flow{} - flow.Status.setCondition(&FlowCondition{Type: FlowConditionReady}) - if flow.Status.GetCondition(FlowConditionFeedReady) != nil { - t.Fatalf("Got a non-nil for non-existent conditiontype") - } - - flow2 := Flow{} - if flow2.Status.GetCondition(FlowConditionFeedReady) != nil { - t.Fatalf("Got a non-nil for non-existent conditiontype") - } -} - -func TestFlowCondition_GetCondition(t *testing.T) { - testcases := []struct { - name string - types []FlowConditionType - get FlowConditionType - want FlowConditionType - }{ - {"FlowConditionReady", []FlowConditionType{FlowConditionReady}, FlowConditionReady, FlowConditionReady}, - {"FlowConditionFeedReady", []FlowConditionType{FlowConditionFeedReady, FlowConditionReady}, FlowConditionFeedReady, FlowConditionFeedReady}, - {"FlowConditionChannelReady", []FlowConditionType{FlowConditionChannelReady, FlowConditionReady}, FlowConditionChannelReady, FlowConditionChannelReady}, - {"FlowConditionSubscriptionReady", []FlowConditionType{FlowConditionSubscriptionReady}, FlowConditionSubscriptionReady, FlowConditionSubscriptionReady}, - } - - for _, tc := range testcases { - testName := fmt.Sprintf("%s - %s", "Flow", tc.name) - t.Run(testName, func(t *testing.T) { - flow := Flow{} - for _, t := range tc.types { - c := &FlowCondition{Type: t} - flow.Status.setCondition(c) - } - - if want, got := tc.want, flow.Status.GetCondition(tc.get).Type; want != got { - t.Fatalf("Failed to get expected condition. \nwant:\t%#v\ngot:\t%#v", want, got) - } - }) - } -} - -func TestFlowCondition_setCondition(t *testing.T) { - testcases := []struct { - name string - types []FlowConditionType - want int - }{ - {"One", []FlowConditionType{FlowConditionReady}, 1}, - {"Two", []FlowConditionType{FlowConditionReady, FlowConditionFeedReady}, 2}, - {"Replace", []FlowConditionType{FlowConditionReady, FlowConditionReady}, 1}, - {"Invalid", []FlowConditionType{""}, 0}, - } - - for _, tc := range testcases { - testName := fmt.Sprintf("%s - %s", "Flow", tc.name) - t.Run(testName, func(t *testing.T) { - flow := Flow{} - for _, t := range tc.types { - c := &FlowCondition{Type: t} - flow.Status.setCondition(c) - } - if want, got := tc.want, len(flow.Status.Conditions); want != got { - t.Fatalf("Failed to return expected number of conditions. \nwant:\t%#v\ngot:\t%#v", want, got) - } - }) - } -} - -func TestFlowCondition_RemoveCondition(t *testing.T) { - testcases := []struct { - name string - set []FlowConditionType - remove []FlowConditionType - want int - }{ - {"RemoveOnlyOne", []FlowConditionType{FlowConditionReady}, []FlowConditionType{FlowConditionReady}, 0}, - {"RemoveOne", []FlowConditionType{FlowConditionReady, FlowConditionChannelReady}, []FlowConditionType{FlowConditionReady}, 1}, - {"RemoveNonExistent", []FlowConditionType{FlowConditionReady}, []FlowConditionType{FlowConditionSubscriptionReady}, 1}, - {"Invalid", []FlowConditionType{FlowConditionReady}, []FlowConditionType{""}, 1}, - } - - for _, tc := range testcases { - testName := fmt.Sprintf("%s - %s", "Flow", tc.name) - t.Run(testName, func(t *testing.T) { - flow := Flow{} - for _, t := range tc.set { - c := &FlowCondition{Type: t} - flow.Status.setCondition(c) - } - for _, t := range tc.remove { - flow.Status.removeCondition(t) - } - - if want, got := tc.want, len(flow.Status.Conditions); want != got { - t.Fatalf("Failed to return expected number of conditions. \nwant:\t%#v\ngot:\t%#v", want, got) - } - }) - } -} - -func TestFlowCondition_IsReady(t *testing.T) { - testcases := []struct { - name string - set []FlowCondition - want bool - }{ - {"FlowConditionFeedReady", []FlowCondition{{ - Type: FlowConditionFeedReady, - Status: corev1.ConditionTrue, - }}, - false}, - {"FlowConditionFeedAndChannelReady", []FlowCondition{{ - Type: FlowConditionFeedReady, - Status: corev1.ConditionTrue, - }, { - Type: FlowConditionChannelReady, - Status: corev1.ConditionTrue, - }}, - false}, - {"FlowConditionFeedReadyChannelNotReady", []FlowCondition{{ - Type: FlowConditionFeedReady, - Status: corev1.ConditionTrue, - }, { - Type: FlowConditionChannelReady, - Status: corev1.ConditionFalse, - }}, - false}, - {"FlowConditionFeedNotReadyChannelReady", []FlowCondition{{ - Type: FlowConditionFeedReady, - Status: corev1.ConditionFalse, - }, { - Type: FlowConditionChannelReady, - Status: corev1.ConditionTrue, - }}, - false}, - {"FlowConditionFeedReadyChannelReadySubscriptionDispatching", []FlowCondition{{ - Type: FlowConditionFeedReady, - Status: corev1.ConditionTrue, - }, { - Type: FlowConditionChannelReady, - Status: corev1.ConditionTrue, - }, { - Type: FlowConditionSubscriptionReady, - Status: corev1.ConditionTrue, - }}, - false}, - {"FlowConditionFeedReadyChannelReadySubscriptionDispatchingActionTargetResolved", []FlowCondition{{ - Type: FlowConditionFeedReady, - Status: corev1.ConditionTrue, - }, { - Type: FlowConditionChannelReady, - Status: corev1.ConditionTrue, - }, { - Type: FlowConditionSubscriptionReady, - Status: corev1.ConditionTrue, - }, { - Type: FlowConditionActionTargetResolved, - Status: corev1.ConditionTrue, - }}, - true}, - } - - for _, tc := range testcases { - testName := fmt.Sprintf("%s - %s", "Flow", tc.name) - t.Run(testName, func(t *testing.T) { - flow := Flow{} - for _, c := range tc.set { - flow.Status.setCondition(&c) - } - flow.Status.checkAndMarkReady() - if want, got := tc.want, flow.Status.IsReady(); want != got { - t.Fatalf("Failed IsReady check : \nwant:\t%#v\ngot:\t%#v", want, got) - } - }) - } -} - -func TestFlowCondition_PropagateStatus(t *testing.T) { - // These just get set by the - - testcases := []struct { - name string - feedStatuses []feedsv1alpha1.FeedStatus - channelStatuses []channelsv1alpha1.ChannelStatus - subscriptionStatuses []channelsv1alpha1.SubscriptionStatus - actionTargetResolveStatus corev1.ConditionStatus - want bool - }{ - {"NothingReady", - []feedsv1alpha1.FeedStatus{{}}, - []channelsv1alpha1.ChannelStatus{{}}, - []channelsv1alpha1.SubscriptionStatus{{}}, - corev1.ConditionFalse, - false}, - {"FeedReady", - []feedsv1alpha1.FeedStatus{{ - Conditions: []feedsv1alpha1.FeedCondition{{ - Type: feedsv1alpha1.FeedConditionReady, - Status: corev1.ConditionTrue, - }}, - }}, - []channelsv1alpha1.ChannelStatus{}, - []channelsv1alpha1.SubscriptionStatus{}, - corev1.ConditionFalse, - false}, - {"ChannelReady", - []feedsv1alpha1.FeedStatus{}, - []channelsv1alpha1.ChannelStatus{{ - Conditions: []channelsv1alpha1.ChannelCondition{{ - Type: channelsv1alpha1.ChannelReady, - Status: corev1.ConditionTrue, - }}, - DomainInternal: "foobar-channel.default.svc.cluster.local", - }}, - []channelsv1alpha1.SubscriptionStatus{}, - corev1.ConditionFalse, - false}, - {"SubscriptionReady", - []feedsv1alpha1.FeedStatus{}, - []channelsv1alpha1.ChannelStatus{}, - []channelsv1alpha1.SubscriptionStatus{{ - Conditions: []channelsv1alpha1.SubscriptionCondition{{ - Type: channelsv1alpha1.SubscriptionDispatching, - Status: corev1.ConditionTrue, - }}, - }}, - corev1.ConditionFalse, - false}, - {"ActionTargetResolved", - []feedsv1alpha1.FeedStatus{}, - []channelsv1alpha1.ChannelStatus{}, - []channelsv1alpha1.SubscriptionStatus{}, - corev1.ConditionTrue, - false}, - {"AllNotReady", - []feedsv1alpha1.FeedStatus{{ - Conditions: []feedsv1alpha1.FeedCondition{{ - Type: feedsv1alpha1.FeedConditionReady, - Status: corev1.ConditionFalse, - }}, - }}, - []channelsv1alpha1.ChannelStatus{{ - Conditions: []channelsv1alpha1.ChannelCondition{{ - Type: channelsv1alpha1.ChannelReady, - Status: corev1.ConditionFalse, - }}, - DomainInternal: "foobar-channel.default.svc.cluster.local", - }}, - []channelsv1alpha1.SubscriptionStatus{{ - Conditions: []channelsv1alpha1.SubscriptionCondition{{ - Type: channelsv1alpha1.SubscriptionDispatching, - Status: corev1.ConditionFalse, - }}, - }}, - corev1.ConditionFalse, - false}, - {"AllReady", - []feedsv1alpha1.FeedStatus{{ - Conditions: []feedsv1alpha1.FeedCondition{{ - Type: feedsv1alpha1.FeedConditionReady, - Status: corev1.ConditionTrue, - }}, - }}, - []channelsv1alpha1.ChannelStatus{{ - Conditions: []channelsv1alpha1.ChannelCondition{{ - Type: channelsv1alpha1.ChannelReady, - Status: corev1.ConditionTrue, - }}, - DomainInternal: "foobar-channel.default.svc.cluster.local", - }}, - []channelsv1alpha1.SubscriptionStatus{{ - Conditions: []channelsv1alpha1.SubscriptionCondition{{ - Type: channelsv1alpha1.SubscriptionDispatching, - Status: corev1.ConditionTrue, - }}, - }}, - corev1.ConditionTrue, - true}, - } - for _, tc := range testcases { - testName := fmt.Sprintf("%s - %s", "Flow", tc.name) - t.Run(testName, func(t *testing.T) { - flow := Flow{} - for _, fs := range tc.feedStatuses { - flow.Status.PropagateFeedStatus(fs) - } - for _, cs := range tc.channelStatuses { - flow.Status.PropagateChannelStatus(cs) - } - for _, ss := range tc.subscriptionStatuses { - flow.Status.PropagateSubscriptionStatus(ss) - } - if tc.actionTargetResolveStatus == corev1.ConditionTrue { - flow.Status.PropagateActionTargetResolved(corev1.ConditionTrue, actionTargetResolveSuccessReason, actionTargetResolveSuccessMessage) - } else if tc.actionTargetResolveStatus == corev1.ConditionFalse { - flow.Status.PropagateActionTargetResolved(corev1.ConditionFalse, actionTargetResolveFailReason, actionTargetResolveFailMessage) - } else { - flow.Status.PropagateActionTargetResolved(corev1.ConditionUnknown, "Unknown", "Unknown") - } - if want, got := tc.want, flow.Status.IsReady(); want != got { - t.Fatalf("Failed IsReady check : \nwant:\t%#v\ngot:\t%#v", want, got) - } - }) - } -} - -func TestFlowCondition_InitializeConditions(t *testing.T) { - flow := Flow{} - flow.Status.InitializeConditions() - cond := flow.Status.GetCondition(FlowConditionReady) - if cond == nil { - t.Fatalf("InitializeConditions didn't set FlowConditionReady") - } - if want, got := cond.Status, corev1.ConditionUnknown; want != got { - t.Fatalf("Status was not set correctly : \nwant:\t%#v\ngot:\t%#v", want, got) - } - if flow.Status.IsReady() { - t.Fatalf("InitializeConditions marked the flow Ready") - } -} diff --git a/pkg/apis/flows/v1alpha1/flow_validation.go b/pkg/apis/flows/v1alpha1/flow_validation.go deleted file mode 100644 index e11025aa5e4..00000000000 --- a/pkg/apis/flows/v1alpha1/flow_validation.go +++ /dev/null @@ -1,81 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "github.com/knative/pkg/apis" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/util/validation" - "net/url" -) - -// Validate validates the Flow resource. -func (f *Flow) Validate() *apis.FieldError { - return f.Spec.Validate().ViaField("spec") -} - -// Validate validates the flow spec for a valid action and trigger. -func (fs *FlowSpec) Validate() *apis.FieldError { - if equality.Semantic.DeepEqual(fs, &FlowSpec{}) { - return apis.ErrMissingField("trigger", "action") - } - - if err := fs.Trigger.Validate(); err != nil { - return err.ViaField("trigger") - } - if err := fs.Action.Validate(); err != nil { - return err.ViaField("action") - } - return nil -} - -// Validate validates event trigger has both eventType and resource set. -func (et *EventTrigger) Validate() *apis.FieldError { - - if et.EventType == "" { - return apis.ErrMissingField("eventType") - } - if errs := validation.IsQualifiedName(et.EventType); len(errs) > 0 { - return apis.ErrInvalidValue(et.EventType, "eventType") - } - - if et.Resource == "" { - return apis.ErrMissingField("resource") - } - - return nil -} - -// Validate validates flow action has a valid formed target or targetURI, but not both. -func (fa *FlowAction) Validate() *apis.FieldError { - switch { - case fa.Target != nil && fa.TargetURI != nil: - return apis.ErrMultipleOneOf("target", "targetURI") - case fa.Target != nil: - if errs := validation.IsQualifiedName(fa.Target.Name); len(errs) > 0 { - return apis.ErrInvalidValue(fa.Target.Name, "name").ViaField("target") - } - return nil - case fa.TargetURI != nil: - if _, err := url.ParseRequestURI(*fa.TargetURI); err != nil { - return apis.ErrInvalidValue(*fa.TargetURI, "targetURI") - } - return nil - default: - return apis.ErrMissingOneOf("target", "targetURI") - } -} diff --git a/pkg/apis/flows/v1alpha1/flow_validation_test.go b/pkg/apis/flows/v1alpha1/flow_validation_test.go deleted file mode 100644 index aa3e4bfa258..00000000000 --- a/pkg/apis/flows/v1alpha1/flow_validation_test.go +++ /dev/null @@ -1,183 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "github.com/google/go-cmp/cmp" - "github.com/knative/pkg/apis" - "k8s.io/api/core/v1" - "testing" -) - -func TestFlowSpecValidation(t *testing.T) { - tests := []struct { - name string - f *FlowSpec - want *apis.FieldError - }{{ - name: "valid with URI", - f: &FlowSpec{ - Action: FlowAction{ - TargetURI: stringPtr("http://example.com/action"), - }, - Trigger: EventTrigger{ - EventType: "foo", - Resource: "bar", - }, - }, - }, { - name: "valid with Target", - f: &FlowSpec{ - Action: FlowAction{ - Target: &v1.ObjectReference{ - Name: "foo", - }, - }, - Trigger: EventTrigger{ - EventType: "foo", - Resource: "bar", - }, - }, - }, { - name: "invalid with URI", - f: &FlowSpec{ - Action: FlowAction{ - TargetURI: stringPtr("http//example.com/action"), - }, - Trigger: EventTrigger{ - EventType: "foo", - Resource: "bar", - }, - }, - want: &apis.FieldError{ - Message: `invalid value "http//example.com/action"`, - Paths: []string{"action.targetURI"}, - }, - }, { - name: "invalid with Target", - f: &FlowSpec{ - Action: FlowAction{ - Target: &v1.ObjectReference{ - Name: "f@o", - }, - }, - Trigger: EventTrigger{ - EventType: "foo", - Resource: "bar", - }, - }, - want: &apis.FieldError{ - Message: `invalid value "f@o"`, - Paths: []string{"action.target.name"}, - }, - }, { - name: "invalid with both target and targetURI", - f: &FlowSpec{ - Action: FlowAction{ - TargetURI: stringPtr("http://example.com/action"), - Target: &v1.ObjectReference{ - Name: "foo", - }, - }, - Trigger: EventTrigger{ - EventType: "foo", - Resource: "bar", - }, - }, - want: &apis.FieldError{ - Message: `expected exactly one, got both`, - Paths: []string{"action.target", "action.targetURI"}, - }, - }, { - name: "invalid, no target or targetURI", - f: &FlowSpec{ - Action: FlowAction{}, - Trigger: EventTrigger{ - EventType: "foo", - Resource: "bar", - }, - }, - want: &apis.FieldError{ - Message: `expected exactly one, got neither`, - Paths: []string{"action.target", "action.targetURI"}, - }, - }, { - name: "invalid, missing event type", - f: &FlowSpec{ - Action: FlowAction{ - TargetURI: stringPtr("http://example.com/action"), - }, - Trigger: EventTrigger{ - Resource: "bar", - }, - }, - want: &apis.FieldError{ - Message: "missing field(s)", - Paths: []string{"trigger.eventType"}, - }, - }, { - name: "invalid event type", - f: &FlowSpec{ - Action: FlowAction{ - TargetURI: stringPtr("http://example.com/action"), - }, - Trigger: EventTrigger{ - EventType: "f@o", - Resource: "bar", - }, - }, - want: &apis.FieldError{ - Message: `invalid value "f@o"`, - Paths: []string{"trigger.eventType"}, - }, - }, { - name: "invalid, missing resource", - f: &FlowSpec{ - Action: FlowAction{ - TargetURI: stringPtr("http://example.com/action"), - }, - Trigger: EventTrigger{ - EventType: "foo", - }, - }, - want: &apis.FieldError{ - Message: "missing field(s)", - Paths: []string{"trigger.resource"}, - }, - }, { - name: "empty", - f: &FlowSpec{}, - want: &apis.FieldError{ - Message: "missing field(s)", - Paths: []string{"trigger", "action"}, - }, - }} - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := test.f.Validate() - if diff := cmp.Diff(test.want.Error(), got.Error()); diff != "" { - t.Errorf("validateFlow (-want, +got) = %v", diff) - } - }) - } -} - -// stringPtr returns a pointer to the passed string. -func stringPtr(s string) *string { - return &s -} diff --git a/pkg/apis/flows/v1alpha1/zz_generated.deepcopy.go b/pkg/apis/flows/v1alpha1/zz_generated.deepcopy.go deleted file mode 100644 index 03bae2eb6b5..00000000000 --- a/pkg/apis/flows/v1alpha1/zz_generated.deepcopy.go +++ /dev/null @@ -1,218 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by deepcopy-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - feeds_v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - v1 "k8s.io/api/core/v1" - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *EventTrigger) DeepCopyInto(out *EventTrigger) { - *out = *in - if in.Parameters != nil { - in, out := &in.Parameters, &out.Parameters - if *in == nil { - *out = nil - } else { - *out = new(runtime.RawExtension) - (*in).DeepCopyInto(*out) - } - } - if in.ParametersFrom != nil { - in, out := &in.ParametersFrom, &out.ParametersFrom - *out = make([]feeds_v1alpha1.ParametersFromSource, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EventTrigger. -func (in *EventTrigger) DeepCopy() *EventTrigger { - if in == nil { - return nil - } - out := new(EventTrigger) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Flow) DeepCopyInto(out *Flow) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Flow. -func (in *Flow) DeepCopy() *Flow { - if in == nil { - return nil - } - out := new(Flow) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Flow) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *FlowAction) DeepCopyInto(out *FlowAction) { - *out = *in - if in.Target != nil { - in, out := &in.Target, &out.Target - if *in == nil { - *out = nil - } else { - *out = new(v1.ObjectReference) - **out = **in - } - } - if in.TargetURI != nil { - in, out := &in.TargetURI, &out.TargetURI - if *in == nil { - *out = nil - } else { - *out = new(string) - **out = **in - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FlowAction. -func (in *FlowAction) DeepCopy() *FlowAction { - if in == nil { - return nil - } - out := new(FlowAction) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *FlowCondition) DeepCopyInto(out *FlowCondition) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FlowCondition. -func (in *FlowCondition) DeepCopy() *FlowCondition { - if in == nil { - return nil - } - out := new(FlowCondition) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *FlowList) DeepCopyInto(out *FlowList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Flow, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FlowList. -func (in *FlowList) DeepCopy() *FlowList { - if in == nil { - return nil - } - out := new(FlowList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *FlowList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *FlowSpec) DeepCopyInto(out *FlowSpec) { - *out = *in - in.Action.DeepCopyInto(&out.Action) - in.Trigger.DeepCopyInto(&out.Trigger) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FlowSpec. -func (in *FlowSpec) DeepCopy() *FlowSpec { - if in == nil { - return nil - } - out := new(FlowSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *FlowStatus) DeepCopyInto(out *FlowStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make([]FlowCondition, len(*in)) - copy(*out, *in) - } - if in.FlowContext != nil { - in, out := &in.FlowContext, &out.FlowContext - if *in == nil { - *out = nil - } else { - *out = new(runtime.RawExtension) - (*in).DeepCopyInto(*out) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FlowStatus. -func (in *FlowStatus) DeepCopy() *FlowStatus { - if in == nil { - return nil - } - out := new(FlowStatus) - in.DeepCopyInto(out) - return out -} diff --git a/pkg/buses/bus.go b/pkg/buses/bus.go deleted file mode 100644 index 0ee44279a26..00000000000 --- a/pkg/buses/bus.go +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright 2018 The Knative 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 buses - -import ( - "fmt" - - "go.uber.org/zap" - - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" -) - -type bus struct { - ref BusReference - handlerFuncs EventHandlerFuncs - - reconciler *Reconciler - cache *Cache - dispatcher *MessageDispatcher - receiver *MessageReceiver - - logger *zap.SugaredLogger -} - -// BusOpts holds configuration options for new buses. These options are not -// required for proper operation of the bus, but are useful to override the -// default behavior and for testing. -type BusOpts struct { - // Logger to use for the bus and created components - Logger *zap.SugaredLogger - - // MasterURL is the address of the Kubernetes API server. Overrides any - // value in kubeconfig. Only required if out-of-cluster. - MasterURL string - // KubeConfig is the path to a kubeconfig. Only required if out-of-cluster. - KubeConfig string - - // Cache to use for this bus. A cache will be created for the bus if not - // specified. - Cache *Cache - // Reconciler to use for this bus. A reconciler wil be created for the bus - // if not specified. - Reconciler *Reconciler - // MessageDispatcher to use for this bus. The message dispatcher is used to - // send messages from the bus to a subscriber. A message dispatcher will be - // created for the bus if needed and not specified. - MessageDispatcher *MessageDispatcher - // MessageReceiver to use for this bus. The message receiver is used to - // receive message sent to a channel. A message receiver will be created - // for the bus if needed and not specified. - MessageReceiver *MessageReceiver -} - -// BusProvisioner provisions channels and subscriptions for a bus on backing -// infrastructure. -type BusProvisioner interface { - Run(threadiness int, stopCh <-chan struct{}) -} - -// NewBusProvisioner creates a new provisioner for a specific bus. -// EventHandlerFuncs are used to be notified when a channel or subscription is -// created, updated or removed. -func NewBusProvisioner(ref BusReference, handlerFuncs EventHandlerFuncs, opts *BusOpts) BusProvisioner { - if opts == nil { - opts = &BusOpts{} - } - if opts.Logger == nil { - opts.Logger = zap.NewNop().Sugar() - } - if opts.Cache == nil { - opts.Cache = NewCache() - } - if handlerFuncs.logger == nil { - handlerFuncs.logger = opts.Logger.Named(handlerLoggingComponent) - } - if opts.Reconciler == nil { - opts.Reconciler = NewReconciler( - ref, Provisioner, opts.MasterURL, opts.KubeConfig, opts.Cache, - handlerFuncs, opts.Logger.Named(reconcilerLoggingComponent), - ) - } - - return &bus{ - ref: ref, - handlerFuncs: handlerFuncs, - - cache: opts.Cache, - reconciler: opts.Reconciler, - - logger: opts.Logger.Named(busLoggingComponent), - } -} - -// BusDispatcher dispatches messages from channels to subscribers via backing -// infrastructure. -type BusDispatcher interface { - Run(threadiness int, stopCh <-chan struct{}) - DispatchMessage(subscription SubscriptionReference, message *Message) error -} - -// NewBusDispatcher creates a new dispatcher for a specific bus. -// EventHandlerFuncs are used to be notified when a subscription is created, -// updated or removed, or a message is received. -func NewBusDispatcher(ref BusReference, handlerFuncs EventHandlerFuncs, opts *BusOpts) BusDispatcher { - var b *bus - - if opts == nil { - opts = &BusOpts{} - } - if opts.Logger == nil { - opts.Logger = zap.NewNop().Sugar() - } - if opts.Cache == nil { - opts.Cache = NewCache() - } - if handlerFuncs.logger == nil { - handlerFuncs.logger = opts.Logger.Named(handlerLoggingComponent) - } - if opts.Reconciler == nil { - opts.Reconciler = NewReconciler( - ref, Dispatcher, opts.MasterURL, opts.KubeConfig, opts.Cache, - handlerFuncs, opts.Logger.Named(reconcilerLoggingComponent), - ) - } - if opts.MessageDispatcher == nil { - opts.MessageDispatcher = NewMessageDispatcher(opts.Logger.Named(dispatcherLoggingComponent)) - } - if opts.MessageReceiver == nil { - opts.MessageReceiver = NewMessageReceiver(func(channel ChannelReference, message *Message) error { - return b.receiveMessage(channel, message) - }, opts.Logger.Named(receiverLoggingComponent)) - } - - b = &bus{ - ref: ref, - handlerFuncs: handlerFuncs, - - cache: opts.Cache, - reconciler: opts.Reconciler, - dispatcher: opts.MessageDispatcher, - receiver: opts.MessageReceiver, - - logger: opts.Logger, - } - - return b -} - -// Run starts the bus's processing. -func (b bus) Run(threadiness int, stopCh <-chan struct{}) { - go b.reconciler.Run(threadiness, stopCh) - b.reconciler.WaitForCacheSync(stopCh) - if b.receiver != nil { - go b.receiver.Run(stopCh) - } - - <-stopCh -} - -func (b *bus) receiveMessage(channel ChannelReference, message *Message) error { - _, err := b.cache.Channel(channel) - if err != nil { - return ErrUnknownChannel - } - return b.handlerFuncs.onReceiveMessage(channel, message) -} - -// DispatchMessage sends a message to a subscriber. This function is only -// avilable for bus dispatchers. -func (b *bus) DispatchMessage(ref SubscriptionReference, message *Message) error { - subscription, err := b.cache.Subscription(ref) - if err != nil { - return fmt.Errorf("unable to dispatch to unknown subscription %q", ref.String()) - } - return b.dispatchMessage(subscription, message) -} - -func (b *bus) dispatchMessage(subscription *channelsv1alpha1.Subscription, message *Message) error { - subscriber := subscription.Spec.Subscriber - defaults := DispatchDefaults{ - Namespace: subscription.Namespace, - } - return b.dispatcher.DispatchMessage(message, subscriber, subscription.Spec.ReplyTo, defaults) -} diff --git a/pkg/buses/cache.go b/pkg/buses/cache.go deleted file mode 100644 index 009d629fec2..00000000000 --- a/pkg/buses/cache.go +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2018 The Knative 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 buses - -import ( - "fmt" - - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" -) - -// NewCache create a cache that is able to save and retrive Channels and -// Subscriptions by their reference. -func NewCache() *Cache { - return &Cache{ - channels: make(map[ChannelReference]*channelsv1alpha1.Channel), - subscriptions: make(map[SubscriptionReference]*channelsv1alpha1.Subscription), - } -} - -// Cache able to save and retrive Channels and Subscriptions by their -// reference. It is used by the reconciler to track which resources have been -// provisioned and comparing updated resources to the provisioned version. -type Cache struct { - channels map[ChannelReference]*channelsv1alpha1.Channel - subscriptions map[SubscriptionReference]*channelsv1alpha1.Subscription -} - -// Channel returns a cached channel for provided reference or an error if the -// channel is not in the cache. -func (c *Cache) Channel(ref ChannelReference) (*channelsv1alpha1.Channel, error) { - channel, ok := c.channels[ref] - if !ok { - return nil, fmt.Errorf("unknown channel %q", ref.String()) - } - return channel, nil -} - -// Subscription returns a cached subscription for provided reference or an -// error if the subscription is not in the cache. -func (c *Cache) Subscription(ref SubscriptionReference) (*channelsv1alpha1.Subscription, error) { - subscription, ok := c.subscriptions[ref] - if !ok { - return nil, fmt.Errorf("unknown subscription %q", ref.String()) - } - return subscription, nil -} - -// AddChannel adds, or updates, the provided channel to the cache for later -// retrieal by its reference. -func (c *Cache) AddChannel(channel *channelsv1alpha1.Channel) { - if channel == nil { - return - } - ref := NewChannelReference(channel) - c.channels[ref] = channel -} - -// RemoveChannel removes the provided channel from the cache. -func (c *Cache) RemoveChannel(channel *channelsv1alpha1.Channel) { - if channel == nil { - return - } - ref := NewChannelReference(channel) - delete(c.channels, ref) -} - -// AddSubscription adds, or updates, the provided subscription to the cache for -// later retrieal by its reference. -func (c *Cache) AddSubscription(subscription *channelsv1alpha1.Subscription) { - if subscription == nil { - return - } - ref := NewSubscriptionReference(subscription) - c.subscriptions[ref] = subscription -} - -// RemoveSubscription removes the provided subscription from the cache. -func (c *Cache) RemoveSubscription(subscription *channelsv1alpha1.Subscription) { - if subscription == nil { - return - } - ref := NewSubscriptionReference(subscription) - delete(c.subscriptions, ref) -} - -func (c *Cache) AllChannels() []*channelsv1alpha1.Channel { - chans := []*channelsv1alpha1.Channel{} - for _, channel := range c.channels { - chans = append(chans, channel) - } - return chans -} - -func (c *Cache) AllSubscriptions() []*channelsv1alpha1.Subscription { - subs := []*channelsv1alpha1.Subscription{} - for _, sub := range c.subscriptions { - subs = append(subs, sub) - } - return subs -} diff --git a/pkg/buses/cache_test.go b/pkg/buses/cache_test.go deleted file mode 100644 index 2a337c9adc6..00000000000 --- a/pkg/buses/cache_test.go +++ /dev/null @@ -1,201 +0,0 @@ -/* -Copyright 2018 The Knative 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 buses_test - -import ( - "fmt" - "testing" - - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - "github.com/knative/eventing/pkg/buses" - "k8s.io/apimachinery/pkg/api/equality" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -const ( - cacheDefaultNamespace = "default" - cacheTestChannel = "test-channel" - cacheTestSubscription = "test-subscription" -) - -func TestCacheErrsForUnknownChannel(t *testing.T) { - cache := buses.NewCache() - ref := buses.NewChannelReferenceFromNames(cacheTestChannel, cacheDefaultNamespace) - var expected *channelsv1alpha1.Channel - actual, err := cache.Channel(ref) - if err == nil { - t.Errorf("%s expected: %+v got: %+v", "Error", "", err) - } - if expected != actual { - t.Errorf("%s expected: %+v got: %+v", "Unexpected channel", nil, actual) - } -} - -func TestCacheRetrievesKnownChannel(t *testing.T) { - cache := buses.NewCache() - ref := buses.NewChannelReferenceFromNames(cacheTestChannel, cacheDefaultNamespace) - expected := makeChannel(ref) - cache.AddChannel(expected) - actual, err := cache.Channel(ref) - if err != nil { - t.Errorf("%s expected: %+v got: %+v", "Unexpected error", nil, err) - } - if expected != actual { - t.Errorf("%s expected: %+v got: %+v", "Channel", expected, actual) - } -} - -func TestCacheRemovesKnownChannel(t *testing.T) { - cache := buses.NewCache() - ref := buses.NewChannelReferenceFromNames(cacheTestChannel, cacheDefaultNamespace) - channel := makeChannel(ref) - cache.AddChannel(channel) - cache.RemoveChannel(channel) - var expected *channelsv1alpha1.Channel - actual, err := cache.Channel(ref) - if err == nil { - t.Errorf("%s expected: %+v got: %+v", "Unexpected error", nil, err) - } - if expected != actual { - t.Errorf("%s expected: %+v got: %+v", "Channel", expected, actual) - } -} - -func TestCacheNilChannel(t *testing.T) { - cache := buses.NewCache() - var channel *channelsv1alpha1.Channel - cache.AddChannel(channel) - cache.RemoveChannel(channel) -} - -func TestCacheErrsForUnknownSubscription(t *testing.T) { - cache := buses.NewCache() - ref := buses.NewSubscriptionReferenceFromNames(cacheTestSubscription, cacheDefaultNamespace) - var expected *channelsv1alpha1.Subscription - actual, err := cache.Subscription(ref) - if err == nil { - t.Errorf("%s expected: %+v got: %+v", "Error", "", err) - } - if expected != actual { - t.Errorf("%s expected: %+v got: %+v", "Unexpected subscription", nil, actual) - } -} - -func TestCacheRetrievesKnownSubscription(t *testing.T) { - cache := buses.NewCache() - ref := buses.NewSubscriptionReferenceFromNames(cacheTestSubscription, cacheDefaultNamespace) - expected := makeSubscription(ref) - cache.AddSubscription(expected) - actual, err := cache.Subscription(ref) - if err != nil { - t.Errorf("%s expected: %+v got: %+v", "Unexpected error", nil, err) - } - if expected != actual { - t.Errorf("%s expected: %+v got: %+v", "Subscription", expected, actual) - } -} - -func TestCacheRemovesKnownSubscription(t *testing.T) { - cache := buses.NewCache() - ref := buses.NewSubscriptionReferenceFromNames(cacheTestSubscription, cacheDefaultNamespace) - subscription := makeSubscription(ref) - cache.AddSubscription(subscription) - cache.RemoveSubscription(subscription) - var expected *channelsv1alpha1.Subscription - actual, err := cache.Subscription(ref) - if err == nil { - t.Errorf("%s expected: %+v got: %+v", "Unexpected error", nil, err) - } - if expected != actual { - t.Errorf("%s expected: %+v got: %+v", "Subscription", expected, actual) - } -} - -func TestCacheNilSubscription(t *testing.T) { - cache := buses.NewCache() - var subscription *channelsv1alpha1.Subscription - cache.AddSubscription(subscription) - cache.RemoveSubscription(subscription) -} - -func TestCacheAllChannels(t *testing.T) { - cases := []struct { - Channels []*channelsv1alpha1.Channel - }{ - {Channels: []*channelsv1alpha1.Channel{}}, - {Channels: []*channelsv1alpha1.Channel{ - makeChannel(buses.NewChannelReferenceFromNames(cacheTestChannel, cacheDefaultNamespace)), - }}, - } - - for _, tt := range cases { - t.Run(fmt.Sprintf("%v", tt.Channels), func(t *testing.T) { - cache := buses.NewCache() - - for _, channel := range tt.Channels { - cache.AddChannel(channel) - } - - if !equality.Semantic.DeepEqual(tt.Channels, cache.AllChannels()) { - t.Errorf("%v != %v", tt.Channels, cache.AllChannels()) - } - }) - } -} - -func TestCacheAllSubscriptions(t *testing.T) { - cases := []struct { - Subscriptions []*channelsv1alpha1.Subscription - }{ - {Subscriptions: []*channelsv1alpha1.Subscription{}}, - {Subscriptions: []*channelsv1alpha1.Subscription{ - makeSubscription(buses.NewSubscriptionReferenceFromNames(cacheTestSubscription, cacheDefaultNamespace)), - }}, - } - - for _, tt := range cases { - t.Run(fmt.Sprintf("%v", tt.Subscriptions), func(t *testing.T) { - cache := buses.NewCache() - - for _, sub := range tt.Subscriptions { - cache.AddSubscription(sub) - } - - if !equality.Semantic.DeepEqual(tt.Subscriptions, cache.AllSubscriptions()) { - t.Errorf("%v != %v", tt.Subscriptions, cache.AllSubscriptions()) - } - }) - } -} - -func makeChannel(ref buses.ChannelReference) *channelsv1alpha1.Channel { - return &channelsv1alpha1.Channel{ - ObjectMeta: metav1.ObjectMeta{ - Name: ref.Name, - Namespace: ref.Namespace, - }, - } -} - -func makeSubscription(ref buses.SubscriptionReference) *channelsv1alpha1.Subscription { - return &channelsv1alpha1.Subscription{ - ObjectMeta: metav1.ObjectMeta{ - Name: ref.Name, - Namespace: ref.Namespace, - }, - } -} diff --git a/pkg/buses/gcppubsub/bus.go b/pkg/buses/gcppubsub/bus.go deleted file mode 100644 index d8385b0e19d..00000000000 --- a/pkg/buses/gcppubsub/bus.go +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Copyright 2018 The Knative 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 gcppubsub - -import ( - "context" - "fmt" - - "cloud.google.com/go/pubsub" - "github.com/knative/eventing/pkg/buses" - "go.uber.org/zap" -) - -// BusType is the type of the gcppubsub bus -const BusType = "gcppubsub" - -type CloudPubSubBus struct { - ref buses.BusReference - reconciler *buses.Reconciler - dispatcher buses.BusDispatcher - provisioner buses.BusProvisioner - - pubsubClient *pubsub.Client - receivers map[string]context.CancelFunc - - logger *zap.SugaredLogger -} - -func NewCloudPubSubBusDispatcher(ref buses.BusReference, projectID string, opts *buses.BusOpts) (*CloudPubSubBus, error) { - ctx := context.Background() - pubsubClient, err := pubsub.NewClient(ctx, projectID) - if err != nil { - return nil, err - } - - bus := &CloudPubSubBus{ - ref: ref, - pubsubClient: pubsubClient, - } - eventHandlers := buses.EventHandlerFuncs{ - SubscribeFunc: func(channel buses.ChannelReference, subscription buses.SubscriptionReference, parameters buses.ResolvedParameters) error { - return bus.startReceivingEvents(subscription, parameters) - }, - UnsubscribeFunc: func(channel buses.ChannelReference, subscription buses.SubscriptionReference) error { - bus.stopReceivingEvents(subscription) - return nil - }, - ReceiveMessageFunc: func(channel buses.ChannelReference, messgae *buses.Message) error { - return bus.sendEventToTopic(channel, messgae) - }, - } - bus.dispatcher = buses.NewBusDispatcher(ref, eventHandlers, opts) - bus.logger = opts.Logger - bus.reconciler = opts.Reconciler - bus.receivers = make(map[string]context.CancelFunc) - return bus, nil -} - -func NewCloudPubSubBusProvisioner(ref buses.BusReference, projectID string, opts *buses.BusOpts) (*CloudPubSubBus, error) { - ctx := context.Background() - pubsubClient, err := pubsub.NewClient(ctx, projectID) - if err != nil { - return nil, err - } - - bus := &CloudPubSubBus{ - ref: ref, - pubsubClient: pubsubClient, - } - eventHandlers := buses.EventHandlerFuncs{ - ProvisionFunc: func(channel buses.ChannelReference, parameters buses.ResolvedParameters) error { - return bus.createTopic(channel, parameters) - }, - UnprovisionFunc: func(channel buses.ChannelReference) error { - return bus.deleteTopic(channel) - }, - SubscribeFunc: func(channel buses.ChannelReference, subscription buses.SubscriptionReference, parameters buses.ResolvedParameters) error { - return bus.createOrUpdateSubscription(channel, subscription, parameters) - }, - UnsubscribeFunc: func(channel buses.ChannelReference, subscription buses.SubscriptionReference) error { - return bus.deleteSubscription(subscription) - }, - } - bus.provisioner = buses.NewBusProvisioner(ref, eventHandlers, opts) - bus.logger = opts.Logger - return bus, nil -} - -func (b *CloudPubSubBus) Run(threadness int, stopCh <-chan struct{}) { - if b.dispatcher != nil { - b.dispatcher.Run(threadness, stopCh) - } - if b.provisioner != nil { - b.provisioner.Run(threadness, stopCh) - } -} - -// startReceivingEvents will receive events from a Cloud Pub/Sub Subscription for a -// Knative Subscription. This method will not block, but will continue to -// receive events until either this method or StopReceivingEvents is called for -// the same Subscription. -func (b *CloudPubSubBus) startReceivingEvents(ref buses.SubscriptionReference, parameters buses.ResolvedParameters) error { - ctx := context.Background() - cctx, cancel := context.WithCancel(ctx) - - // cancel current subscription receiver, if any - b.stopReceivingEvents(ref) - - subscriptionID := b.subscriptionID(ref) - subscription := b.pubsubClient.Subscription(subscriptionID) - b.receivers[subscriptionID] = cancel - - // check if subscription exists before receiving - if exists, err := subscription.Exists(ctx); err != nil { - return err - } else if !exists { - return fmt.Errorf("cannot receive message for a non-existent subscription %s", subscriptionID) - } - - // subscription.Receive blocks, so run it in a goroutine - go func() { - b.logger.Infof("Start receiving events for subscription %q", subscriptionID) - err := subscription.Receive(cctx, func(ctx context.Context, pubsubMessage *pubsub.Message) { - message := &buses.Message{ - Headers: pubsubMessage.Attributes, - Payload: pubsubMessage.Data, - } - err := b.dispatcher.DispatchMessage(ref, message) - if err != nil { - b.logger.Warnf("Unable to dispatch event %q to %q", pubsubMessage.ID, ref.String()) - pubsubMessage.Nack() - } else { - b.logger.Infof("Dispatched event %q to %q", pubsubMessage.ID, ref.String()) - pubsubMessage.Ack() - } - }) - if err != nil { - b.logger.Errorf("Error receiving messesages for %q: %v", subscriptionID, err) - } - delete(b.receivers, subscriptionID) - b.reconciler.RequeueSubscription(ref) - }() - - return nil -} - -// stopReceivingEvents stops receiving events for a previous call to -// StartReceivingEvents. Calls for a Subscription that is not not actively receiving -// are ignored. -func (b *CloudPubSubBus) stopReceivingEvents(ref buses.SubscriptionReference) { - subscriptionID := b.subscriptionID(ref) - if cancel, ok := b.receivers[subscriptionID]; ok { - b.logger.Infof("Stop receiving events for subscription %q", subscriptionID) - cancel() - delete(b.receivers, subscriptionID) - } -} - -// sendEventToTopic sends a message to the Cloud Pub/Sub Topic backing the -// Channel. -func (b *CloudPubSubBus) sendEventToTopic(channel buses.ChannelReference, message *buses.Message) error { - ctx := context.Background() - - topicID := b.topicID(channel) - topic := b.pubsubClient.Topic(topicID) - - result := topic.Publish(ctx, &pubsub.Message{ - Data: message.Payload, - Attributes: message.Headers, - }) - id, err := result.Get(ctx) - if err != nil { - return err - } - - // TODO allow topics to be reused between publish events, call .Stop after an idle period - topic.Stop() - - b.logger.Infof("Published a message to %s; msg ID: %v", topicID, id) - return nil -} - -// createTopic creates a Topic in Cloud Pub/Sub for the Channel. -func (b *CloudPubSubBus) createTopic(channel buses.ChannelReference, parameters buses.ResolvedParameters) error { - ctx := context.Background() - - topicID := b.topicID(channel) - topic := b.pubsubClient.Topic(topicID) - - // check if topic exists before creating - if exists, err := topic.Exists(ctx); err != nil { - return err - } else if exists { - return nil - } - - b.logger.Infof("Create topic %q", topicID) - topic, err := b.pubsubClient.CreateTopic(ctx, topicID) - if err != nil { - return err - } - - return nil -} - -// deleteTopic deletes the Topic in Cloud Pub/Sub for the Channel. -func (b *CloudPubSubBus) deleteTopic(channel buses.ChannelReference) error { - ctx := context.Background() - - topicID := b.topicID(channel) - topic := b.pubsubClient.Topic(topicID) - - // check if topic exists before deleting - if exists, err := topic.Exists(ctx); err != nil { - return err - } else if !exists { - return nil - } - - b.logger.Infof("Delete topic %q", topicID) - return topic.Delete(ctx) -} - -// createOrUpdateSubscription creates a Subscription in Cloud Pub/Sub for the -// Knative Subscription, or idempotently updates a Subscription if it already -// exists. -func (b *CloudPubSubBus) createOrUpdateSubscription(channel buses.ChannelReference, ref buses.SubscriptionReference, parameters buses.ResolvedParameters) error { - ctx := context.Background() - - subscriptionID := b.subscriptionID(ref) - subscription := b.pubsubClient.Subscription(subscriptionID) - - // check if subscription exists before creating - if exists, err := subscription.Exists(ctx); err != nil { - return err - } else if exists { - // TODO once the bus has configurable params, update subscription configuration - // _, err := subscription.Update(b.ctx, pubsub.SubscriptionConfigToUpdate{}) - // return err - return nil - } - - // create subscription - topicID := b.topicID(channel) - topic := b.pubsubClient.Topic(topicID) - b.logger.Infof("Create subscription %q for topic %q", subscriptionID, topicID) - subscription, err := b.pubsubClient.CreateSubscription(ctx, subscriptionID, pubsub.SubscriptionConfig{ - Topic: topic, - }) - return err -} - -// deleteSubscription removes a Subscription from Cloud Pub/Sub for a Knative -// Subscription. -func (b *CloudPubSubBus) deleteSubscription(ref buses.SubscriptionReference) error { - ctx := context.Background() - - subscriptionID := b.subscriptionID(ref) - subscription := b.pubsubClient.Subscription(subscriptionID) - - // check if subscription exists before deleting - if exists, err := subscription.Exists(ctx); err != nil { - return err - } else if !exists { - return nil - } - - b.logger.Infof("Deleting subscription %q", subscriptionID) - return subscription.Delete(ctx) -} - -func (b *CloudPubSubBus) topicID(channel buses.ChannelReference) string { - return fmt.Sprintf("channel-%s-%s-%s", b.ref.Name, channel.Namespace, channel.Name) -} - -func (b *CloudPubSubBus) subscriptionID(subscription buses.SubscriptionReference) string { - return fmt.Sprintf("subscription-%s-%s-%s", b.ref.Name, subscription.Namespace, subscription.Name) -} diff --git a/pkg/buses/gcppubsub/bus_test.go b/pkg/buses/gcppubsub/bus_test.go deleted file mode 100644 index 326a3924cc8..00000000000 --- a/pkg/buses/gcppubsub/bus_test.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright 2018 The Knative 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 gcppubsub - -import "testing" - -func TestStub(t *testing.T) { - // TODO: Implement tests in this directory, please. - // This file is used to make code coverage on this directly count. -} diff --git a/pkg/buses/gcppubsub/dispatcher/kodata/LICENSE b/pkg/buses/gcppubsub/dispatcher/kodata/LICENSE deleted file mode 120000 index 2a64f9d0fc6..00000000000 --- a/pkg/buses/gcppubsub/dispatcher/kodata/LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../../LICENSE \ No newline at end of file diff --git a/pkg/buses/gcppubsub/dispatcher/kodata/VENDOR-LICENSE b/pkg/buses/gcppubsub/dispatcher/kodata/VENDOR-LICENSE deleted file mode 120000 index 681789ed22f..00000000000 --- a/pkg/buses/gcppubsub/dispatcher/kodata/VENDOR-LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/pkg/buses/gcppubsub/dispatcher/main.go b/pkg/buses/gcppubsub/dispatcher/main.go deleted file mode 100644 index 8718b170e81..00000000000 --- a/pkg/buses/gcppubsub/dispatcher/main.go +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2018 The Knative 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 main - -import ( - "flag" - "os" - - "github.com/knative/eventing/pkg/buses" - "github.com/knative/eventing/pkg/buses/gcppubsub" - "github.com/knative/pkg/signals" - "go.uber.org/zap" -) - -const ( - threadsPerReconciler = 1 -) - -func main() { - ref := buses.NewBusReferenceFromNames( - os.Getenv("BUS_NAME"), - os.Getenv("BUS_NAMESPACE"), - ) - - config := buses.NewLoggingConfig() - logger := buses.NewBusLoggerFromConfig(config) - defer logger.Sync() - logger = logger.With( - zap.String("channels.knative.dev/bus", ref.String()), - zap.String("channels.knative.dev/busType", gcppubsub.BusType), - zap.String("channels.knative.dev/busComponent", buses.Dispatcher), - ) - - projectID := os.Getenv("GOOGLE_CLOUD_PROJECT") - if projectID == "" { - logger.Fatalf("GOOGLE_CLOUD_PROJECT environment variable must be set") - } - - opts := &buses.BusOpts{ - Logger: logger, - } - - flag.StringVar(&opts.KubeConfig, "kubeconfig", "", "Path to a kubeconfig. Only required if out-of-cluster.") - flag.StringVar(&opts.MasterURL, "master", "", "The address of the Kubernetes API server. Overrides any value in kubeconfig. Only required if out-of-cluster.") - flag.Parse() - - bus, err := gcppubsub.NewCloudPubSubBusDispatcher(ref, projectID, opts) - if err != nil { - logger.Fatalf("Error starting pub/sub bus dispatcher: %v", err) - } - - // set up signals so we handle the first shutdown signal gracefully - stopCh := signals.SetupSignalHandler() - bus.Run(threadsPerReconciler, stopCh) -} diff --git a/pkg/buses/gcppubsub/provisioner/kodata/LICENSE b/pkg/buses/gcppubsub/provisioner/kodata/LICENSE deleted file mode 120000 index 2a64f9d0fc6..00000000000 --- a/pkg/buses/gcppubsub/provisioner/kodata/LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../../LICENSE \ No newline at end of file diff --git a/pkg/buses/gcppubsub/provisioner/kodata/VENDOR-LICENSE b/pkg/buses/gcppubsub/provisioner/kodata/VENDOR-LICENSE deleted file mode 120000 index 681789ed22f..00000000000 --- a/pkg/buses/gcppubsub/provisioner/kodata/VENDOR-LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/pkg/buses/gcppubsub/provisioner/main.go b/pkg/buses/gcppubsub/provisioner/main.go deleted file mode 100644 index e2a4fd87384..00000000000 --- a/pkg/buses/gcppubsub/provisioner/main.go +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2018 The Knative 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 main - -import ( - "flag" - "os" - - "github.com/knative/eventing/pkg/buses" - "github.com/knative/eventing/pkg/buses/gcppubsub" - "github.com/knative/pkg/signals" - "go.uber.org/zap" -) - -const ( - threadsPerReconciler = 1 -) - -func main() { - ref := buses.NewBusReferenceFromNames( - os.Getenv("BUS_NAME"), - os.Getenv("BUS_NAMESPACE"), - ) - - config := buses.NewLoggingConfig() - logger := buses.NewBusLoggerFromConfig(config) - defer logger.Sync() - logger = logger.With( - zap.String("channels.knative.dev/bus", ref.String()), - zap.String("channels.knative.dev/busType", gcppubsub.BusType), - zap.String("channels.knative.dev/busComponent", buses.Provisioner), - ) - - projectID := os.Getenv("GOOGLE_CLOUD_PROJECT") - if projectID == "" { - logger.Fatalf("GOOGLE_CLOUD_PROJECT environment variable must be set") - } - - opts := &buses.BusOpts{ - Logger: logger} - - flag.StringVar(&opts.KubeConfig, "kubeconfig", "", "Path to a kubeconfig. Only required if out-of-cluster.") - flag.StringVar(&opts.MasterURL, "master", "", "The address of the Kubernetes API server. Overrides any value in kubeconfig. Only required if out-of-cluster.") - flag.Parse() - - bus, err := gcppubsub.NewCloudPubSubBusProvisioner(ref, projectID, opts) - if err != nil { - logger.Fatalf("Error starting pub/sub bus provisioner: %v", err) - } - - // set up signals so we handle the first shutdown signal gracefully - stopCh := signals.SetupSignalHandler() - bus.Run(threadsPerReconciler, stopCh) -} diff --git a/pkg/buses/handler_funcs.go b/pkg/buses/handler_funcs.go deleted file mode 100644 index 75e899ea0fd..00000000000 --- a/pkg/buses/handler_funcs.go +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Copyright 2018 The Knative 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 buses - -import ( - "fmt" - - "go.uber.org/zap" - - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - "github.com/knative/eventing/pkg/controller/util" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/equality" -) - -const ( - // SuccessSynced is used as part of the Event 'reason' when a resource is synced - successSynced = "Synced" - // ErrResourceSync is used as part of the Event 'reason' when a resource fails - // to sync. - errResourceSync = "ErrResourceSync" -) - -// ResolvedParameters is a map containing parameter names and the resolved -// values from attributes or parameter defaults. -type ResolvedParameters = map[string]string - -// EventHandlerFuncs is a set of handler functions that are called when a bus -// requires sync, channels are provisioned/unprovisioned, or a subscription is -// created or deleted, or if one of the relevant resources is changed. -type EventHandlerFuncs struct { - // BusFunc is invoked when the Bus requires sync. - BusFunc func(bus BusReference) error - - // ProvisionFunc is invoked when a new Channel should be provisioned or when - // the attributes change. - ProvisionFunc func(channel ChannelReference, parameters ResolvedParameters) error - - // UnprovisionFunc in invoked when a Channel should be deleted. - UnprovisionFunc func(channel ChannelReference) error - - // SubscribeFunc is invoked when a new Subscription should be set up or when - // the attributes change. - SubscribeFunc func(channel ChannelReference, subscription SubscriptionReference, parameters ResolvedParameters) error - - // UnsubscribeFunc is invoked when a Subscription should be deleted. - UnsubscribeFunc func(channel ChannelReference, subscription SubscriptionReference) error - - // ReceiveMessageFunc is invoked when a Message is received on a Channel - ReceiveMessageFunc func(channel ChannelReference, message *Message) error - - logger *zap.SugaredLogger -} - -func (h EventHandlerFuncs) onBus(bus channelsv1alpha1.GenericBus, reconciler *Reconciler) error { - if h.BusFunc == nil { - return nil - } - ref := NewBusReference(bus) - err := h.BusFunc(ref) - if err != nil { - reconciler.RecordBusEventf(corev1.EventTypeWarning, errResourceSync, "Error syncing Bus: %s", err) - } else { - reconciler.RecordBusEventf(corev1.EventTypeNormal, successSynced, "Bus synched successfully") - } - return err -} - -func (h EventHandlerFuncs) onProvision(channel *channelsv1alpha1.Channel, reconciler *Reconciler) error { - if h.ProvisionFunc == nil { - return nil - } - parameters, err := h.resolveChannelParameters(reconciler.bus.GetSpec(), channel.Spec) - if err != nil { - return err - } - channelCopy := channel.DeepCopy() - var cond *channelsv1alpha1.ChannelCondition - ref := NewChannelReference(channel) - err = h.ProvisionFunc(ref, parameters) - if err != nil { - reconciler.RecordChannelEventf(ref, corev1.EventTypeWarning, errResourceSync, "Error provisioning channel: %s", err) - cond = util.NewChannelCondition(channelsv1alpha1.ChannelProvisioned, corev1.ConditionFalse, errResourceSync, err.Error()) - } else { - reconciler.RecordChannelEventf(ref, corev1.EventTypeNormal, successSynced, "Channel provisioned successfully") - cond = util.NewChannelCondition(channelsv1alpha1.ChannelProvisioned, corev1.ConditionTrue, successSynced, "Channel provisioned successfully") - } - util.SetChannelCondition(&channelCopy.Status, *cond) - util.ConsolidateChannelCondition(&channelCopy.Status) - if !equality.Semantic.DeepEqual(channel.Status, channelCopy.Status) { - // status has changed, update channel - _, errS := reconciler.eventingClient.ChannelsV1alpha1().Channels(channel.Namespace).Update(channelCopy) - if errS != nil { - h.logger.Warnf("Could not update channel status: %v", errS) - if err != nil { - return fmt.Errorf("error provisioning channel (%v); error updating channel status (%v)", err, errS) - } - return errS - } - } - return err -} - -func (h EventHandlerFuncs) onUnprovision(channel *channelsv1alpha1.Channel, reconciler *Reconciler) error { - if h.UnprovisionFunc == nil { - return nil - } - ref := NewChannelReference(channel) - if err := h.UnprovisionFunc(ref); err != nil { - reconciler.RecordChannelEventf(ref, corev1.EventTypeWarning, errResourceSync, "Error unprovisioning channel: %s", err) - return err - } - reconciler.RecordChannelEventf(ref, corev1.EventTypeNormal, successSynced, "Channel unprovisioned successfully") - // skip updating status conditions since the channel was deleted - return nil -} - -func (h EventHandlerFuncs) onSubscribe(subscription *channelsv1alpha1.Subscription, reconciler *Reconciler) error { - if h.SubscribeFunc == nil { - return nil - } - parameters, err := h.resolveSubscriptionParameters(reconciler.bus.GetSpec(), subscription.Spec) - if err != nil { - return err - } - channel := NewChannelReferenceFromSubscription(subscription) - ref := NewSubscriptionReference(subscription) - subscriptionCopy := subscription.DeepCopy() - var cond *channelsv1alpha1.SubscriptionCondition - err = h.SubscribeFunc(channel, ref, parameters) - if err != nil { - reconciler.RecordSubscriptionEventf(ref, corev1.EventTypeWarning, errResourceSync, "Error subscribing: %s", err) - cond = util.NewSubscriptionCondition(channelsv1alpha1.SubscriptionDispatching, corev1.ConditionFalse, errResourceSync, err.Error()) - } else { - reconciler.RecordSubscriptionEventf(ref, corev1.EventTypeNormal, successSynced, "Subscribed successfully") - cond = util.NewSubscriptionCondition(channelsv1alpha1.SubscriptionDispatching, corev1.ConditionTrue, successSynced, "Subscription dispatcher successfully created") - } - util.SetSubscriptionCondition(&subscriptionCopy.Status, *cond) - if !equality.Semantic.DeepEqual(subscription.Status, subscriptionCopy.Status) { - // status has changed, update subscription - _, errS := reconciler.eventingClient.ChannelsV1alpha1().Subscriptions(subscription.Namespace).Update(subscriptionCopy) - if errS != nil { - h.logger.Warnf("Could not update subscription status: %v", errS) - if err != nil { - return fmt.Errorf("error subscribing (%v); error updating subscription status (%v)", err, errS) - } - return errS - } - } - return err -} - -func (h EventHandlerFuncs) onUnsubscribe(subscription *channelsv1alpha1.Subscription, reconciler *Reconciler) error { - if h.UnsubscribeFunc == nil { - return nil - } - channel := NewChannelReferenceFromSubscription(subscription) - ref := NewSubscriptionReference(subscription) - if err := h.UnsubscribeFunc(channel, ref); err != nil { - reconciler.RecordSubscriptionEventf(ref, corev1.EventTypeWarning, errResourceSync, "Error unsubscribing: %s", err) - return err - } - reconciler.RecordSubscriptionEventf(ref, corev1.EventTypeNormal, successSynced, "Unsubscribed successfully") - // skip updating status conditions since the subscription was deleted - return nil -} - -func (h EventHandlerFuncs) onReceiveMessage(channel ChannelReference, message *Message) error { - if h.ReceiveMessageFunc == nil { - // TODO use a static error - return fmt.Errorf("unable to dispatch message") - } - return h.ReceiveMessageFunc(channel, message) -} - -// resolveChannelParameters resolves the given Channel Parameters and the Bus' -// Channel Parameters, returning an ResolvedParameters or an Error. -func (h EventHandlerFuncs) resolveChannelParameters(bus *channelsv1alpha1.BusSpec, channel channelsv1alpha1.ChannelSpec) (ResolvedParameters, error) { - genericBusParameters := bus.Parameters - var parameters *[]channelsv1alpha1.Parameter - if genericBusParameters != nil { - parameters = genericBusParameters.Channel - } - return h.resolveParameters(parameters, channel.Arguments) -} - -// resolveSubscriptionParameters resolves the given Subscription Parameters and -// the Bus' Subscription Parameters, returning an Attributes or an Error. -func (h EventHandlerFuncs) resolveSubscriptionParameters(bus *channelsv1alpha1.BusSpec, subscription channelsv1alpha1.SubscriptionSpec) (ResolvedParameters, error) { - genericBusParameters := bus.Parameters - var parameters *[]channelsv1alpha1.Parameter - if genericBusParameters != nil { - parameters = genericBusParameters.Subscription - } - return h.resolveParameters(parameters, subscription.Arguments) -} - -// resolveParameters resolves a slice of Parameters and a slice of arguments and -// returns an Attributes or an error if there are missing Arguments. Each -// Parameter represents a variable that must be provided by an Argument or -// optionally defaulted if a default value for the Parameter is specified. -// resolveAttributes combines the given arrays of Parameters and Arguments, -// using default values where necessary and returning an error if there are -// missing Arguments. -func (h EventHandlerFuncs) resolveParameters(parameters *[]channelsv1alpha1.Parameter, arguments *[]channelsv1alpha1.Argument) (ResolvedParameters, error) { - resolved := make(ResolvedParameters) - known := make(map[string]interface{}) - required := make(map[string]interface{}) - - // apply parameters - if parameters != nil { - for _, param := range *parameters { - known[param.Name] = true - if param.Default != nil { - resolved[param.Name] = *param.Default - } else { - required[param.Name] = true - } - } - } - // apply arguments - if arguments != nil { - for _, arg := range *arguments { - if _, ok := known[arg.Name]; !ok { - // ignore arguments not defined by parameters - h.logger.Warnf("Skipping unknown argument: %s", arg.Name) - continue - } - delete(required, arg.Name) - resolved[arg.Name] = arg.Value - } - } - - // check for missing arguments - if len(required) != 0 { - missing := []string{} - for name := range required { - missing = append(missing, name) - } - return nil, fmt.Errorf("missing required arguments: %v", missing) - } - - return resolved, nil -} diff --git a/pkg/buses/kafka/bus.go b/pkg/buses/kafka/bus.go deleted file mode 100644 index 269a8102aa1..00000000000 --- a/pkg/buses/kafka/bus.go +++ /dev/null @@ -1,287 +0,0 @@ -/* - * Copyright 2018 The Knative 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 kafka - -import ( - "fmt" - "strconv" - - "go.uber.org/zap" - - "github.com/Shopify/sarama" - cluster "github.com/bsm/sarama-cluster" - "github.com/knative/eventing/pkg/buses" -) - -const ( - // BusType is the type of the kafka bus - BusType = "kafka" - - initialOffset = "initialOffset" - numPartitions = "NumPartitions" - newest = "Newest" - oldest = "Oldest" -) - -type KafkaBus struct { - ref buses.BusReference - dispatcher buses.BusDispatcher - provisioner buses.BusProvisioner - - kafkaBrokers []string - kafkaClusterAdmin sarama.ClusterAdmin - kafkaAsyncProducer sarama.AsyncProducer - kafkaConsumers map[buses.SubscriptionReference]*cluster.Consumer - - logger *zap.SugaredLogger -} - -func NewKafkaBusDispatcher(ref buses.BusReference, brokers []string, opts *buses.BusOpts) (*KafkaBus, error) { - bus := &KafkaBus{ - ref: ref, - kafkaBrokers: brokers, - } - eventHandlers := buses.EventHandlerFuncs{ - SubscribeFunc: func(channel buses.ChannelReference, subscription buses.SubscriptionReference, parameters buses.ResolvedParameters) error { - return bus.subscribe(channel, subscription, parameters) - }, - UnsubscribeFunc: func(channel buses.ChannelReference, subscription buses.SubscriptionReference) error { - return bus.unsubscribe(channel, subscription) - }, - ReceiveMessageFunc: func(channel buses.ChannelReference, message *buses.Message) error { - bus.kafkaAsyncProducer.Input() <- toKafkaMessage(channel, message) - return nil - }, - } - bus.dispatcher = buses.NewBusDispatcher(ref, eventHandlers, opts) - bus.logger = opts.Logger - bus.kafkaConsumers = make(map[buses.SubscriptionReference]*cluster.Consumer) - - conf := sarama.NewConfig() - conf.Version = sarama.V1_1_0_0 - conf.ClientID = ref.Name + "-dispatcher" - client, err := sarama.NewClient(brokers, conf) - if err != nil { - return nil, fmt.Errorf("unable to create kafka client: %v", err) - } - producer, err := sarama.NewAsyncProducerFromClient(client) - if err != nil { - return nil, fmt.Errorf("unable to create kafka producer: %v", err) - } - bus.kafkaAsyncProducer = producer - - return bus, nil -} - -func NewKafkaBusProvisioner(ref buses.BusReference, brokers []string, opts *buses.BusOpts) (*KafkaBus, error) { - bus := &KafkaBus{ - ref: ref, - kafkaBrokers: brokers, - } - eventHandlers := buses.EventHandlerFuncs{ - ProvisionFunc: func(channel buses.ChannelReference, parameters buses.ResolvedParameters) error { - return bus.provision(channel, parameters) - }, - UnprovisionFunc: func(channel buses.ChannelReference) error { - return bus.unprovision(channel) - }, - } - bus.provisioner = buses.NewBusProvisioner(ref, eventHandlers, opts) - bus.logger = opts.Logger - - conf := sarama.NewConfig() - conf.Version = sarama.V1_1_0_0 - conf.ClientID = ref.Name + "-provisioner" - - clusterAdmin, err := sarama.NewClusterAdmin(brokers, conf) - if err != nil { - return nil, fmt.Errorf("unable to building kafka admin client: %v", err) - } - bus.kafkaClusterAdmin = clusterAdmin - - return bus, nil -} - -func (b *KafkaBus) Run(threadness int, stopCh <-chan struct{}) { - if b.kafkaAsyncProducer != nil { - go func() { - for { - select { - case e := <-b.kafkaAsyncProducer.Errors(): - b.logger.Warnf("Got %v", e) - case s := <-b.kafkaAsyncProducer.Successes(): - b.logger.Infof("Sent %v", s) - case <-stopCh: - return - } - } - }() - } - if b.dispatcher != nil { - b.dispatcher.Run(threadness, stopCh) - } - if b.provisioner != nil { - b.provisioner.Run(threadness, stopCh) - } -} - -func (b *KafkaBus) subscribe(channel buses.ChannelReference, subscription buses.SubscriptionReference, parameters buses.ResolvedParameters) error { - if _, ok := b.kafkaConsumers[subscription]; ok { - // subscribe can be called multiple times for the same subscription, - //unsubscribe before we resubscribe - err := b.unsubscribe(channel, subscription) - if err != nil { - return err - } - } - - b.logger.Infof("Subscribing %q to %q (%v)", subscription.String(), channel.String(), parameters) - - topicName := topicName(channel) - - initialOffset, err := resolveInitialOffset(parameters) - if err != nil { - return err - } - - group := fmt.Sprintf("%s.%s.%s", b.ref.Name, subscription.Namespace, subscription.Name) - consumerConfig := cluster.NewConfig() - consumerConfig.Version = sarama.V1_1_0_0 - consumerConfig.Consumer.Offsets.Initial = initialOffset - consumer, err := cluster.NewConsumer(b.kafkaBrokers, group, []string{topicName}, consumerConfig) - if err != nil { - return err - } - - b.kafkaConsumers[subscription] = consumer - - go func() { - for { - msg, more := <-consumer.Messages() - if more { - b.logger.Infof("Dispatching a message for subscription %q", subscription.String()) - message := fromKafkaMessage(msg) - err := b.dispatcher.DispatchMessage(subscription, message) - if err != nil { - b.logger.Warnf("Got error trying to dispatch message: %v", err) - } - // TODO: handle errors with pluggable strategy - consumer.MarkOffset(msg, "") // Mark message as processed - } else { - break - } - } - b.logger.Infof("Consumer for subscription %q stopped", subscription.String()) - }() - - return nil -} - -func (b *KafkaBus) unsubscribe(channel buses.ChannelReference, subscription buses.SubscriptionReference) error { - b.logger.Infof("Un-Subscribing %q from %q", subscription.String(), channel.String()) - if consumer, ok := b.kafkaConsumers[subscription]; ok { - delete(b.kafkaConsumers, subscription) - return consumer.Close() - } - return nil -} - -func (b *KafkaBus) provision(channel buses.ChannelReference, parameters buses.ResolvedParameters) error { - topicName := topicName(channel) - b.logger.Infof("Provisioning topic %s on bus backed by Kafka", topicName) - - partitions := 1 - if p, ok := parameters[numPartitions]; ok { - var err error - intPartitions, err := strconv.Atoi(p) - if err != nil { - b.logger.Warnf("Could not parse partition count for %q: %s", channel.String(), p) - } else { - partitions = intPartitions - } - } - - err := b.kafkaClusterAdmin.CreateTopic(topicName, &sarama.TopicDetail{ - ReplicationFactor: 1, - NumPartitions: int32(partitions), - }, false) - if err == sarama.ErrTopicAlreadyExists { - return nil - } else if err != nil { - b.logger.Errorf("Error creating topic %s: %v", topicName, err) - } else { - b.logger.Infof("Successfully created topic %s", topicName) - } - return err -} - -func (b *KafkaBus) unprovision(channel buses.ChannelReference) error { - topicName := topicName(channel) - b.logger.Infof("Un-provisioning topic %s from bus backed by Kafka", topicName) - - err := b.kafkaClusterAdmin.DeleteTopic(topicName) - if err == sarama.ErrUnknownTopicOrPartition { - return nil - } else if err != nil { - b.logger.Errorf("Error deleting topic %s: %v", topicName, err) - } else { - b.logger.Infof("Successfully deleted topic %s", topicName) - } - - return err -} - -func toKafkaMessage(channel buses.ChannelReference, message *buses.Message) *sarama.ProducerMessage { - kafkaMessage := sarama.ProducerMessage{ - Topic: topicName(channel), - Value: sarama.ByteEncoder(message.Payload), - } - for h, v := range message.Headers { - kafkaMessage.Headers = append(kafkaMessage.Headers, sarama.RecordHeader{ - Key: []byte(h), - Value: []byte(v), - }) - } - return &kafkaMessage -} - -func fromKafkaMessage(kafkaMessage *sarama.ConsumerMessage) *buses.Message { - headers := make(map[string]string) - for _, header := range kafkaMessage.Headers { - headers[string(header.Key)] = string(header.Value) - } - message := buses.Message{ - Headers: headers, - Payload: kafkaMessage.Value, - } - return &message -} - -func topicName(channel buses.ChannelReference) string { - return fmt.Sprintf("%s.%s", channel.Namespace, channel.Name) -} - -func resolveInitialOffset(parameters buses.ResolvedParameters) (int64, error) { - switch parameters[initialOffset] { - case oldest: - return sarama.OffsetOldest, nil - case newest: - return sarama.OffsetNewest, nil - default: - return 0, fmt.Errorf("unsupported initialOffset value. Must be one of %s or %s", oldest, newest) - } -} diff --git a/pkg/buses/kafka/bus_test.go b/pkg/buses/kafka/bus_test.go deleted file mode 100644 index 59652629577..00000000000 --- a/pkg/buses/kafka/bus_test.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright 2018 The Knative 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 kafka - -import "testing" - -func TestStub(t *testing.T) { - // TODO: Implement tests in this directory, please. - // This file is used to make code coverage on this directly count. -} diff --git a/pkg/buses/kafka/dispatcher/kodata/LICENSE b/pkg/buses/kafka/dispatcher/kodata/LICENSE deleted file mode 120000 index 2a64f9d0fc6..00000000000 --- a/pkg/buses/kafka/dispatcher/kodata/LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../../LICENSE \ No newline at end of file diff --git a/pkg/buses/kafka/dispatcher/kodata/VENDOR-LICENSE b/pkg/buses/kafka/dispatcher/kodata/VENDOR-LICENSE deleted file mode 120000 index 681789ed22f..00000000000 --- a/pkg/buses/kafka/dispatcher/kodata/VENDOR-LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/pkg/buses/kafka/dispatcher/main.go b/pkg/buses/kafka/dispatcher/main.go deleted file mode 100644 index 7014f9d8061..00000000000 --- a/pkg/buses/kafka/dispatcher/main.go +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2018 The Knative 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 main - -import ( - "flag" - "os" - "strings" - - "github.com/Shopify/sarama" - "github.com/knative/eventing/pkg/buses" - "github.com/knative/eventing/pkg/buses/kafka" - "github.com/knative/pkg/signals" - "go.uber.org/zap" -) - -const ( - threadsPerReconciler = 1 -) - -func main() { - ref := buses.NewBusReferenceFromNames( - os.Getenv("BUS_NAME"), - os.Getenv("BUS_NAMESPACE"), - ) - - config := buses.NewLoggingConfig() - logger := buses.NewBusLoggerFromConfig(config) - defer logger.Sync() - logger = logger.With( - zap.String("channels.knative.dev/bus", ref.String()), - zap.String("channels.knative.dev/busType", kafka.BusType), - zap.String("channels.knative.dev/busComponent", buses.Dispatcher), - ) - sarama.Logger = zap.NewStdLog(logger.With(zap.Namespace("Sarama")).Desugar()) - - brokers := strings.Split(os.Getenv("KAFKA_BOOTSTRAP_SERVERS"), ",") - if len(brokers) == 0 { - logger.Fatalf("Environment variable KAFKA_BOOTSTRAP_SERVERS not set") - } - - opts := &buses.BusOpts{ - Logger: logger, - } - - flag.StringVar(&opts.KubeConfig, "kubeconfig", "", "Path to a kubeconfig. Only required if out-of-cluster.") - flag.StringVar(&opts.MasterURL, "master", "", "The address of the Kubernetes API server. Overrides any value in kubeconfig. Only required if out-of-cluster.") - flag.Parse() - - bus, err := kafka.NewKafkaBusDispatcher(ref, brokers, opts) - if err != nil { - logger.Fatalf("Error starting kafka bus dispatcher: %v", err) - } - - // set up signals so we handle the first shutdown signal gracefully - stopCh := signals.SetupSignalHandler() - bus.Run(threadsPerReconciler, stopCh) -} diff --git a/pkg/buses/kafka/provisioner/kodata/LICENSE b/pkg/buses/kafka/provisioner/kodata/LICENSE deleted file mode 120000 index 2a64f9d0fc6..00000000000 --- a/pkg/buses/kafka/provisioner/kodata/LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../../LICENSE \ No newline at end of file diff --git a/pkg/buses/kafka/provisioner/kodata/VENDOR-LICENSE b/pkg/buses/kafka/provisioner/kodata/VENDOR-LICENSE deleted file mode 120000 index 681789ed22f..00000000000 --- a/pkg/buses/kafka/provisioner/kodata/VENDOR-LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/pkg/buses/kafka/provisioner/main.go b/pkg/buses/kafka/provisioner/main.go deleted file mode 100644 index bc07b7dc3a8..00000000000 --- a/pkg/buses/kafka/provisioner/main.go +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2018 The Knative 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 main - -import ( - "flag" - "os" - "strings" - - "github.com/Shopify/sarama" - "github.com/knative/eventing/pkg/buses" - "github.com/knative/eventing/pkg/buses/kafka" - "github.com/knative/pkg/signals" - "go.uber.org/zap" -) - -const ( - threadsPerReconciler = 1 -) - -func main() { - ref := buses.NewBusReferenceFromNames( - os.Getenv("BUS_NAME"), - os.Getenv("BUS_NAMESPACE"), - ) - - config := buses.NewLoggingConfig() - logger := buses.NewBusLoggerFromConfig(config) - defer logger.Sync() - logger = logger.With( - zap.String("channels.knative.dev/bus", ref.String()), - zap.String("channels.knative.dev/busType", kafka.BusType), - zap.String("channels.knative.dev/busComponent", buses.Provisioner), - ) - sarama.Logger = zap.NewStdLog(logger.With(zap.Namespace("Sarama")).Desugar()) - - opts := &buses.BusOpts{ - Logger: logger, - } - - brokers := strings.Split(os.Getenv("KAFKA_BOOTSTRAP_SERVERS"), ",") - if len(brokers) == 0 { - logger.Fatalf("Environment variable KAFKA_BOOTSTRAP_SERVERS not set") - } - - flag.StringVar(&opts.KubeConfig, "kubeconfig", "", "Path to a kubeconfig. Only required if out-of-cluster.") - flag.StringVar(&opts.MasterURL, "master", "", "The address of the Kubernetes API server. Overrides any value in kubeconfig. Only required if out-of-cluster.") - flag.Parse() - - bus, err := kafka.NewKafkaBusProvisioner(ref, brokers, opts) - if err != nil { - logger.Fatalf("Error starting kafka bus provisioner: %v", err) - } - - // set up signals so we handle the first shutdown signal gracefully - stopCh := signals.SetupSignalHandler() - bus.Run(threadsPerReconciler, stopCh) -} diff --git a/pkg/buses/logger.go b/pkg/buses/logger.go index 261b583a5f9..ed439cc34ae 100644 --- a/pkg/buses/logger.go +++ b/pkg/buses/logger.go @@ -24,8 +24,6 @@ import ( const ( busLoggingComponent = "bus" - reconcilerLoggingComponent = "reconciler" - handlerLoggingComponent = "handler" dispatcherLoggingComponent = "dispatcher" receiverLoggingComponent = "receiver" ) diff --git a/pkg/buses/message_dispatcher.go b/pkg/buses/message_dispatcher.go index c04b99508dc..39346b7eb2d 100644 --- a/pkg/buses/message_dispatcher.go +++ b/pkg/buses/message_dispatcher.go @@ -63,25 +63,25 @@ func NewMessageDispatcher(logger *zap.SugaredLogger) *MessageDispatcher { // DispatchMessage dispatches a message to a destination over HTTP. // -// The destination and replyTo are DNS names. For names with a single label, +// The destination and reply are DNS names. For names with a single label, // the default namespace is used to expand it into a fully qualified name // within the cluster. -func (d *MessageDispatcher) DispatchMessage(message *Message, destination, replyTo string, defaults DispatchDefaults) error { +func (d *MessageDispatcher) DispatchMessage(message *Message, destination, reply string, defaults DispatchDefaults) error { var err error // Default to replying with the original message. If there is a destination, then replace it // with the response from the call to the destination instead. - reply := message + response := message if destination != "" { destinationURL := d.resolveURL(destination, defaults.Namespace) - reply, err = d.executeRequest(destinationURL, message) + response, err = d.executeRequest(destinationURL, message) if err != nil { return fmt.Errorf("Unable to complete request %v", err) } } - if replyTo != "" && reply != nil { - replyToURL := d.resolveURL(replyTo, defaults.Namespace) - _, err = d.executeRequest(replyToURL, reply) + if reply != "" && response != nil { + replyURL := d.resolveURL(reply, defaults.Namespace) + _, err = d.executeRequest(replyURL, response) if err != nil { return fmt.Errorf("Failed to forward reply %v", err) } diff --git a/pkg/buses/message_dispatcher_test.go b/pkg/buses/message_dispatcher_test.go index 4ccee0d462b..ab173169080 100644 --- a/pkg/buses/message_dispatcher_test.go +++ b/pkg/buses/message_dispatcher_test.go @@ -18,14 +18,15 @@ package buses import ( "bytes" - "github.com/google/go-cmp/cmp" - "go.uber.org/zap" "io/ioutil" "net/http" "net/http/httptest" "net/url" "strings" "testing" + + "github.com/google/go-cmp/cmp" + "go.uber.org/zap" ) var ( @@ -110,7 +111,7 @@ func TestDispatchMessage(t *testing.T) { "knative-2": "knative-2-value", "ce-abc": "ce-abc-value", }, - Payload: []byte("replyTo"), + Payload: []byte("reply"), }, expectedReplyRequest: &requestValidation{ Headers: map[string][]string{ @@ -119,7 +120,7 @@ func TestDispatchMessage(t *testing.T) { "knative-2": {"knative-2-value"}, "ce-abc": {"ce-abc-value"}, }, - Body: "replyTo", + Body: "reply", }, }, "reply - only -- error": { @@ -133,7 +134,7 @@ func TestDispatchMessage(t *testing.T) { "knative-2": "knative-2-value", "ce-abc": "ce-abc-value", }, - Payload: []byte("replyTo"), + Payload: []byte("reply"), }, expectedReplyRequest: &requestValidation{ Headers: map[string][]string{ @@ -142,7 +143,7 @@ func TestDispatchMessage(t *testing.T) { "knative-2": {"knative-2-value"}, "ce-abc": {"ce-abc-value"}, }, - Body: "replyTo", + Body: "reply", }, fakeResponse: &http.Response{ StatusCode: http.StatusNotFound, diff --git a/pkg/buses/reconciler.go b/pkg/buses/reconciler.go deleted file mode 100644 index a0605c03188..00000000000 --- a/pkg/buses/reconciler.go +++ /dev/null @@ -1,681 +0,0 @@ -/* - * Copyright 2018 The Knative 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 buses - -import ( - "fmt" - "strings" - "time" - - "go.uber.org/zap" - - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - eventingclientset "github.com/knative/eventing/pkg/client/clientset/versioned" - eventingscheme "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" - eventinginformers "github.com/knative/eventing/pkg/client/informers/externalversions" - channelslisters "github.com/knative/eventing/pkg/client/listers/channels/v1alpha1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/wait" - kubernetesclientset "k8s.io/client-go/kubernetes" - typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1" - informercache "k8s.io/client-go/tools/cache" - "k8s.io/client-go/tools/clientcmd" - "k8s.io/client-go/tools/record" - "k8s.io/client-go/util/workqueue" -) - -const ( - // Dispatcher manages the data plane for a bus - Dispatcher = "dispatcher" - // Provisioner manages the control plane for a bus - Provisioner = "provisioner" - - busKind = "Bus" - clusterBusKind = "ClusterBus" - channelKind = "Channel" - subscriptionKind = "Subscription" -) - -// Reconciler is a utility mix-in intended to be used by Bus authors to easily -// write provisioners and dispatchers for buses. Bus provisioners are -// responsible for managing the storage asset(s) that back a channel. Bus -// dispatchers are responsible for dispatching events on the Channel to the -// Channel's Subscriptions. Reconciler handles setting up informers that watch -// a Bus, its Channels, and their Subscriptions and allows Bus authors to -// register event handler functions to be called when Provision/Unprovision and -// Subscribe/Unsubscribe happen. -type Reconciler struct { - bus channelsv1alpha1.GenericBus - ref BusReference - handler EventHandlerFuncs - cache *Cache - - eventingInformerFactory eventinginformers.SharedInformerFactory - eventingClient eventingclientset.Interface - busesLister channelslisters.BusLister - busesSynced informercache.InformerSynced - clusterBusesLister channelslisters.ClusterBusLister - clusterBusesSynced informercache.InformerSynced - channelsLister channelslisters.ChannelLister - channelsSynced informercache.InformerSynced - subscriptionsLister channelslisters.SubscriptionLister - subscriptionsSynced informercache.InformerSynced - - // workqueue is a rate limited work queue. This is used to queue work to be - // processed instead of performing it as soon as a change happens. This - // means we can ensure we only process a fixed amount of resources at a - // time, and makes it easy to ensure we are never processing the same item - // simultaneously in two different workers. - workqueue workqueue.RateLimitingInterface - // recorder is an event recorder for recording Event resources to the - // Kubernetes API. - recorder record.EventRecorder - - logger *zap.SugaredLogger -} - -// NewReconciler creates a reconciler for a bus given: -// -// component: the name of the component this reconciler should use in created k8s events -// masterURL: the URL of the API server the reconciler should communicate with -// kubeconfig: the path of a kubeconfig file to create a client connection to the masterURL with -// handler: a EventHandlerFuncs with handler functions for the reconciler to call -func NewReconciler( - ref BusReference, - component, masterURL, kubeconfig string, - cache *Cache, handler EventHandlerFuncs, - logger *zap.SugaredLogger, -) *Reconciler { - cfg, err := clientcmd.BuildConfigFromFlags(masterURL, kubeconfig) - if err != nil { - logger.Fatalf("Error building kubeconfig: %v", err) - } - - kubeClient, err := kubernetesclientset.NewForConfig(cfg) - if err != nil { - logger.Fatalf("Error building kubernetes clientset: %v", err) - } - - eventingClient, err := eventingclientset.NewForConfig(cfg) - if err != nil { - logger.Fatalf("Error building eventing clientset: %v", err) - } - - eventingInformerFactory := eventinginformers.NewSharedInformerFactory(eventingClient, time.Second*30) - busInformer := eventingInformerFactory.Channels().V1alpha1().Buses() - clusterBusInformer := eventingInformerFactory.Channels().V1alpha1().ClusterBuses() - channelInformer := eventingInformerFactory.Channels().V1alpha1().Channels() - subscriptionInformer := eventingInformerFactory.Channels().V1alpha1().Subscriptions() - - // Create event broadcaster - // Add types to the default Kubernetes Scheme so Events can be logged for the component. - eventingscheme.AddToScheme(eventingscheme.Scheme) - logger.Info("Creating event broadcaster") - eventBroadcaster := record.NewBroadcaster() - eventBroadcaster.StartLogging(logger.Infof) - eventBroadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: kubeClient.CoreV1().Events("")}) - recorder := eventBroadcaster.NewRecorder(eventingscheme.Scheme, corev1.EventSource{Component: component}) - - reconciler := &Reconciler{ - bus: nil, - ref: ref, - handler: handler, - cache: cache, - - eventingClient: eventingClient, - eventingInformerFactory: eventingInformerFactory, - busesLister: busInformer.Lister(), - busesSynced: busInformer.Informer().HasSynced, - clusterBusesLister: clusterBusInformer.Lister(), - clusterBusesSynced: clusterBusInformer.Informer().HasSynced, - channelsLister: channelInformer.Lister(), - channelsSynced: channelInformer.Informer().HasSynced, - subscriptionsLister: subscriptionInformer.Lister(), - subscriptionsSynced: subscriptionInformer.Informer().HasSynced, - - workqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "Reconciler"), - recorder: recorder, - - logger: logger, - } - - logger.Info("Setting up event handlers") - if reconciler.ref.IsNamespaced() { - // Set up an event handler for when Bus resources change - busInformer.Informer().AddEventHandler(informercache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { - bus := obj.(*channelsv1alpha1.Bus) - reconciler.workqueue.AddRateLimited(makeWorkqueueKeyForBus(bus)) - }, - UpdateFunc: func(old, new interface{}) { - oldBus := old.(*channelsv1alpha1.Bus) - newBus := new.(*channelsv1alpha1.Bus) - - if oldBus.ResourceVersion == newBus.ResourceVersion { - // Periodic resync will send update events for all known Buses. - // Two different versions of the same Bus will always have different RVs. - return - } - - reconciler.workqueue.AddRateLimited(makeWorkqueueKeyForBus(newBus)) - }, - }) - } else { - // Set up an event handler for when ClusterBus resources change - clusterBusInformer.Informer().AddEventHandler(informercache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { - clusterBus := obj.(*channelsv1alpha1.ClusterBus) - reconciler.workqueue.AddRateLimited(makeWorkqueueKeyForClusterBus(clusterBus)) - }, - UpdateFunc: func(old, new interface{}) { - oldClusterBus := old.(*channelsv1alpha1.ClusterBus) - newClusterBus := new.(*channelsv1alpha1.ClusterBus) - - if oldClusterBus.ResourceVersion == newClusterBus.ResourceVersion { - // Periodic resync will send update events for all known ClusterBuses. - // Two different versions of the same ClusterBus will always have different RVs. - return - } - - reconciler.workqueue.AddRateLimited(makeWorkqueueKeyForClusterBus(newClusterBus)) - }, - }) - } - // Set up an event handler for when Channel resources change - channelInformer.Informer().AddEventHandler(informercache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { - channel := obj.(*channelsv1alpha1.Channel) - reconciler.workqueue.AddRateLimited(makeWorkqueueKeyForChannel(channel)) - }, - UpdateFunc: func(old, new interface{}) { - oldChannel := old.(*channelsv1alpha1.Channel) - newChannel := new.(*channelsv1alpha1.Channel) - - if oldChannel.ResourceVersion == newChannel.ResourceVersion { - // Periodic resync will send update events for all known Channels. - // Two different versions of the same Channel will always have different RVs. - return - } - - reconciler.workqueue.AddRateLimited(makeWorkqueueKeyForChannel(newChannel)) - }, - DeleteFunc: func(obj interface{}) { - channel := obj.(*channelsv1alpha1.Channel) - reconciler.workqueue.AddRateLimited(makeWorkqueueKeyForChannel(channel)) - }, - }) - // Set up an event handler for when Subscription resources change - subscriptionInformer.Informer().AddEventHandler(informercache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { - subscription := obj.(*channelsv1alpha1.Subscription) - reconciler.workqueue.AddRateLimited(makeWorkqueueKeyForSubscription(subscription)) - }, - UpdateFunc: func(old, new interface{}) { - oldSubscription := old.(*channelsv1alpha1.Subscription) - newSubscription := new.(*channelsv1alpha1.Subscription) - - if oldSubscription.ResourceVersion == newSubscription.ResourceVersion { - // Periodic resync will send update events for all known Subscriptions. - // Two different versions of the same Subscription will always have different RVs. - return - } - - reconciler.workqueue.AddRateLimited(makeWorkqueueKeyForSubscription(newSubscription)) - }, - DeleteFunc: func(obj interface{}) { - subscription := obj.(*channelsv1alpha1.Subscription) - reconciler.workqueue.AddRateLimited(makeWorkqueueKeyForSubscription(subscription)) - }, - }) - - return reconciler -} - -// RequeueSubscription will add the Subscription to the workqueue for future -// processing. Reprocessing a Subscription is often used within a dispatcher -// when a long lived receiver is interrupted by an asynchronous error. -func (r *Reconciler) RequeueSubscription(subscription SubscriptionReference) { - r.logger.Infof("Requeue subscription %q", subscription.String()) - r.workqueue.AddRateLimited(makeWorkqueueKey(subscriptionKind, subscription.Namespace, subscription.Name)) -} - -// RecordBusEventf creates a new event for the reconciled bus and records it -// with the api server. -func (r *Reconciler) RecordBusEventf(eventtype, reason, messageFmt string, args ...interface{}) { - r.recorder.Eventf(r.bus, eventtype, reason, messageFmt, args...) -} - -// RecordChannelEventf creates a new event for the channel and records it with -// the api server. Attempts to records an event for an unknown channel are -// ignored. -func (r *Reconciler) RecordChannelEventf(ref ChannelReference, eventtype, reason, messageFmt string, args ...interface{}) { - channel, err := r.cache.Channel(ref) - if err != nil { - // TODO handle error - return - } - r.recorder.Eventf(channel, eventtype, reason, messageFmt, args...) -} - -// RecordSubscriptionEventf creates a new event for the subscription and -// records it with the api server. Attempts to records an event for an unknown -// subscription are ignored. -func (r *Reconciler) RecordSubscriptionEventf(ref SubscriptionReference, eventtype, reason, messageFmt string, args ...interface{}) { - subscription, err := r.cache.Subscription(ref) - if err != nil { - // TODO handle error - return - } - r.recorder.Eventf(subscription, eventtype, reason, messageFmt, args...) -} - -// Run will set up the event handlers for types we are interested in, as well -// as syncing informer caches and starting workers. It will block until stopCh -// is closed, at which point it will shutdown the workqueue and wait for -// workers to finish processing their current work items. -func (r *Reconciler) Run(threadiness int, stopCh <-chan struct{}) error { - defer runtime.HandleCrash() - defer r.workqueue.ShutDown() - - // Start the informer factories to begin populating the informer caches - r.logger.Info("Starting reconciler") - go r.eventingInformerFactory.Start(stopCh) - - // Wait for the caches to be synced before starting workers - r.logger.Info("Waiting for informer caches to sync") - if err := r.WaitForCacheSync(stopCh); err != nil { - return err - } - - if r.ref.IsNamespaced() { - // reconciler is for a namespaced Bus - bus, err := r.busesLister.Buses(r.ref.Namespace).Get(r.ref.Name) - if err != nil { - r.logger.Fatalf("Unknown bus %q: %v", r.ref.String(), err) - } - r.bus = bus.DeepCopy() - } else { - // reconciler is for a ClusterBus - clusterBus, err := r.clusterBusesLister.Get(r.ref.Name) - if err != nil { - r.logger.Fatalf("Unknown clusterbus %q: %v", r.ref.String(), err) - } - r.bus = clusterBus.DeepCopy() - } - - r.logger.Info("Starting workers") - // Launch workers to process resources - for i := 0; i < threadiness; i++ { - go wait.Until(r.runWorker, time.Second, stopCh) - } - - r.logger.Info("Started workers") - <-stopCh - r.logger.Info("Shutting down workers") - - return nil -} - -// WaitForCacheSync blocks returning until the reconciler's informers have -// synchronized. It returns an error if the caches cannot sync. -func (r *Reconciler) WaitForCacheSync(stopCh <-chan struct{}) error { - var busesSynced informercache.InformerSynced - // get correct synced reference for bus type - if r.ref.IsNamespaced() { - busesSynced = r.busesSynced - } else { - busesSynced = r.clusterBusesSynced - } - if ok := informercache.WaitForCacheSync(stopCh, busesSynced, r.channelsSynced, r.subscriptionsSynced); !ok { - return fmt.Errorf("failed to wait for caches to sync") - } - return nil -} - -// runWorker is a long-running function that will continually call the -// processNextWorkItem function in order to read and process a message on the -// workqueue. -func (r *Reconciler) runWorker() { - for r.processNextWorkItem() { - } -} - -// processNextWorkItem will read a single work item off the workqueue and -// attempt to process it, by calling the syncHandler. -func (r *Reconciler) processNextWorkItem() bool { - obj, shutdown := r.workqueue.Get() - - if shutdown { - return false - } - - // We wrap this block in a func so we can defer r.workqueue.Done. - err := func(obj interface{}) error { - // We call Done here so the workqueue knows we have finished - // processing this item. We also must remember to call Forget if we - // do not want this work item being re-queued. For example, we do - // not call Forget if a transient error occurs, instead the item is - // put back on the workqueue and attempted again after a back-off - // period. - defer r.workqueue.Done(obj) - var key string - var ok bool - // We expect strings to come off the workqueue. These are of the - // form kind/namespace/name. We do this as the delayed nature of the - // workqueue means the items in the informer cache may actually be - // more up to date that when the item was initially put onto the - // workqueue. - if key, ok = obj.(string); !ok { - // As the item in the workqueue is actually invalid, we call - // Forget here else we'd go into a loop of attempting to - // process a work item that is invalid. - r.workqueue.Forget(obj) - runtime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj)) - return nil - } - // Run the syncHandler, passing it the kind/namespace/name key of the - // resource to be synced. - if err := r.syncHandler(key); err != nil { - r.workqueue.AddRateLimited(obj) - return fmt.Errorf("error syncing reconciler '%s': %v", key, err) - } - // Finally, if no error occurs we Forget this item so it does not - // get queued again until another change happens. - r.workqueue.Forget(obj) - r.logger.Infof("Successfully synced reconciler '%s'", key) - return nil - }(obj) - - if err != nil { - runtime.HandleError(err) - return true - } - - return true -} - -// syncHandler compares the actual state with the desired, and attempts to -// converge the two. It then updates the Status block of the resource with the -// current status. -func (r *Reconciler) syncHandler(key string) error { - // Convert the kind/namespace/name string into a distinct kind, namespace and name - kind, namespace, name, err := splitWorkqueueKey(key) - if err != nil { - runtime.HandleError(fmt.Errorf("invalid resource key: %s", key)) - return nil - } - - switch kind { - case busKind: - err = r.syncBus(namespace, name) - case clusterBusKind: - err = r.syncClusterBus(name) - case channelKind: - err = r.syncChannel(namespace, name) - case subscriptionKind: - err = r.syncSubscription(namespace, name) - default: - runtime.HandleError(fmt.Errorf("Unknown resource kind %s", kind)) - return nil - } - - if err != nil { - return err - } - - return nil -} - -func (r *Reconciler) syncBus(namespace string, name string) error { - // Get the Bus resource with this namespace/name - bus, err := r.busesLister.Buses(namespace).Get(name) - if err != nil { - // The Bus resource may no longer exist - if errors.IsNotFound(err) { - // nothing to do - return nil - } - - return err - } - - // Sync the Bus - err = r.createOrUpdateBus(bus.DeepCopy()) - if err != nil { - return err - } - - return nil -} - -func (r *Reconciler) syncClusterBus(name string) error { - // Get the ClusterBus resource with this name - clusterBus, err := r.clusterBusesLister.Get(name) - if err != nil { - // The ClusterBus resource may no longer exist - if errors.IsNotFound(err) { - // nothing to do - return nil - } - - return err - } - - // Sync the ClusterBus - err = r.createOrUpdateBus(clusterBus.DeepCopy()) - if err != nil { - return err - } - - return nil -} - -func (r *Reconciler) syncChannel(namespace string, name string) error { - // Get the Channel resource with this namespace/name - channel, err := r.channelsLister.Channels(namespace).Get(name) - if err != nil { - // The Channel resource may no longer exist - if errors.IsNotFound(err) { - ref := NewChannelReferenceFromNames(name, namespace) - err = r.removeChannel(ref) - if err != nil { - return err - } - return nil - } - - return err - } - - // Sync the Channel - err = r.createOrUpdateChannel(channel) - if err != nil { - return err - } - - return nil -} - -func (r *Reconciler) syncSubscription(namespace string, name string) error { - // Get the Subscription resource with this namespace/name - subscription, err := r.subscriptionsLister.Subscriptions(namespace).Get(name) - if err != nil { - // The Subscription resource may no longer exist - if errors.IsNotFound(err) { - ref := NewSubscriptionReferenceFromNames(name, namespace) - err = r.removeSubscription(ref) - if err != nil { - return err - } - return nil - } - - return err - } - - // Sync the Subscription - err = r.createOrUpdateSubscription(subscription) - if err != nil { - return err - } - - return nil -} - -func (r *Reconciler) createOrUpdateBus(bus channelsv1alpha1.GenericBus) error { - if r.ref != NewBusReference(bus) { - // not the bus for this reconciler - return nil - } - - // stash the new bus on the reconciler while retaining the old bus. This - // operation is threadsafe because there is only a single Bus/ClusterBus - // that is valid for the Reconciler and the workqueue guarantees that it - // will not emit the same key concurrently. Any bus received is an updated - // revision of the current bus. - bus, r.bus = r.bus, bus - - if !equality.Semantic.DeepEqual(r.bus.GetSpec(), bus.GetSpec()) { - err := r.handler.onBus(r.bus, r) - if err != nil { - return err - } - - oldParams := bus.GetSpec().Parameters - newParams := r.bus.GetSpec().Parameters - // If channel parameters changed we need to reprovision - if !equality.Semantic.DeepEqual(oldParams.Channel, newParams.Channel) { - r.logger.Infof("Bus channel parameters changed. Reprovisioning channels.") - for _, channel := range r.cache.AllChannels() { - r.workqueue.AddRateLimited(makeWorkqueueKeyForChannel(channel)) - } - } - - // If subscription parameters changed we need to resubscribe - if !equality.Semantic.DeepEqual(oldParams.Subscription, newParams.Subscription) { - r.logger.Infof("Bus subscription parameters changed. Resubscribing.") - for _, subscription := range r.cache.AllSubscriptions() { - r.workqueue.AddRateLimited(makeWorkqueueKeyForSubscription(subscription)) - } - } - } - - return nil -} - -func (r *Reconciler) createOrUpdateChannel(channel *channelsv1alpha1.Channel) error { - if !r.bus.BacksChannel(channel) { - return nil - } - - r.cache.AddChannel(channel) - err := r.handler.onProvision(channel, r) - if err != nil { - return err - } - - return nil -} - -func (r *Reconciler) removeChannel(ref ChannelReference) error { - channel, err := r.cache.Channel(ref) - if err != nil { - // the channel isn't provisioned - return nil - } - - err = r.handler.onUnprovision(channel, r) - if err != nil { - return err - } - r.cache.RemoveChannel(channel) - - return nil -} - -func (r *Reconciler) createOrUpdateSubscription(subscription *channelsv1alpha1.Subscription) error { - ref := NewChannelReferenceFromSubscription(subscription) - _, err := r.cache.Channel(ref) - if err != nil { - // channel is not provisioned, before erring we need to check if the channel is provionable - channel, errS := r.channelsLister.Channels(ref.Namespace).Get(ref.Name) - if errS != nil { - return err - } - if !r.bus.BacksChannel(channel) { - return nil - } - return err - } - - r.cache.AddSubscription(subscription) - err = r.handler.onSubscribe(subscription, r) - if err != nil { - return err - } - - return nil -} - -func (r *Reconciler) removeSubscription(ref SubscriptionReference) error { - subscription, err := r.cache.Subscription(ref) - if err != nil { - return nil - } - - err = r.handler.onUnsubscribe(subscription, r) - if err != nil { - return err - } - r.cache.RemoveSubscription(subscription) - - return nil -} - -func makeWorkqueueKeyForBus(bus *channelsv1alpha1.Bus) string { - return makeWorkqueueKey(busKind, bus.Namespace, bus.Name) -} - -func makeWorkqueueKeyForClusterBus(clusterBus *channelsv1alpha1.ClusterBus) string { - return makeWorkqueueKey(clusterBusKind, "", clusterBus.Name) -} - -func makeWorkqueueKeyForChannel(channel *channelsv1alpha1.Channel) string { - return makeWorkqueueKey(channelKind, channel.Namespace, channel.Name) -} - -func makeWorkqueueKeyForSubscription(subscription *channelsv1alpha1.Subscription) string { - return makeWorkqueueKey(subscriptionKind, subscription.Namespace, subscription.Name) -} - -func makeWorkqueueKey(kind string, namespace string, name string) string { - return fmt.Sprintf("%s/%s/%s", kind, namespace, name) -} - -func splitWorkqueueKey(key string) (string, string, string, error) { - chunks := strings.Split(key, "/") - if len(chunks) != 3 { - return "", "", "", fmt.Errorf("Unknown workqueue key %v", key) - } - kind := chunks[0] - namespace := chunks[1] - name := chunks[2] - return kind, namespace, name, nil -} diff --git a/pkg/buses/references.go b/pkg/buses/references.go index 1a0b58608ca..7455022fee5 100644 --- a/pkg/buses/references.go +++ b/pkg/buses/references.go @@ -19,45 +19,9 @@ package buses import ( "fmt" - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" + eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" ) -// BusReference references a Bus or ClusterBus within the cluster by name and -// namespace. For ClusterBus the namespace will be an empty string. -type BusReference struct { - Namespace string - Name string -} - -// NewBusReference creates a BusReference for a bus. -func NewBusReference(bus channelsv1alpha1.GenericBus) BusReference { - meta := bus.GetObjectMeta() - return BusReference{ - Namespace: meta.GetNamespace(), - Name: meta.GetName(), - } -} - -// NewBusReferenceFromNames creates a BusReference for a name and namespace. -func NewBusReferenceFromNames(name, namespace string) BusReference { - return BusReference{ - Namespace: namespace, - Name: name, - } -} - -// IsNamespaced returns true is the reference is for a Bus and not a ClusterBus -func (r *BusReference) IsNamespaced() bool { - return r.Namespace != "" -} - -func (r *BusReference) String() string { - if r.IsNamespaced() { - return fmt.Sprintf("%s/%s", r.Namespace, r.Name) - } - return r.Name -} - // ChannelReference references a Channel within the cluster by name and // namespace. type ChannelReference struct { @@ -66,14 +30,14 @@ type ChannelReference struct { } // NewChannelReference creates a ChannelReference from a Channel -func NewChannelReference(channel *channelsv1alpha1.Channel) ChannelReference { +func NewChannelReference(channel *eventingv1alpha1.Channel) ChannelReference { return NewChannelReferenceFromNames(channel.Name, channel.Namespace) } // NewChannelReferenceFromSubscription creates a ChannelReference from a // Subscription for a Channel. -func NewChannelReferenceFromSubscription(subscription *channelsv1alpha1.Subscription) ChannelReference { - return NewChannelReferenceFromNames(subscription.Spec.Channel, subscription.Namespace) +func NewChannelReferenceFromSubscription(subscription *eventingv1alpha1.Subscription) ChannelReference { + return NewChannelReferenceFromNames(subscription.Spec.Channel.Name, subscription.Namespace) } // NewChannelReferenceFromNames creates a ChannelReference for a name and @@ -88,28 +52,3 @@ func NewChannelReferenceFromNames(name, namespace string) ChannelReference { func (r *ChannelReference) String() string { return fmt.Sprintf("%s/%s", r.Namespace, r.Name) } - -// SubscriptionReference references a Subscription within the cluster by name -// and namespace. -type SubscriptionReference struct { - Namespace string - Name string -} - -// NewSubscriptionReference creates a SubscriptionReference from a Subscription -func NewSubscriptionReference(subscription *channelsv1alpha1.Subscription) SubscriptionReference { - return NewSubscriptionReferenceFromNames(subscription.Name, subscription.Namespace) -} - -// NewSubscriptionReferenceFromNames creates a SubscriptionReference for a name and -// namespace. -func NewSubscriptionReferenceFromNames(name, namespace string) SubscriptionReference { - return SubscriptionReference{ - Namespace: namespace, - Name: name, - } -} - -func (r *SubscriptionReference) String() string { - return fmt.Sprintf("%s/%s", r.Namespace, r.Name) -} diff --git a/pkg/buses/references_test.go b/pkg/buses/references_test.go index febff414ec1..ef75a5070fc 100644 --- a/pkg/buses/references_test.go +++ b/pkg/buses/references_test.go @@ -20,120 +20,20 @@ import ( "fmt" "testing" - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" + eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" "github.com/knative/eventing/pkg/buses" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) const ( referencesTestNamespace = "test-namespace" - referencesTestBusName = "test-bus" - referencesTestClusterBusName = "test-clusterbus" referencesTestChannelName = "test-channel" referencesTestSubscriptionName = "test-subscription" ) -func TestNewBusReference(t *testing.T) { - bus := &channelsv1alpha1.Bus{ - ObjectMeta: metav1.ObjectMeta{ - Name: referencesTestBusName, - Namespace: referencesTestNamespace, - }, - } - expected := buses.BusReference{ - Name: referencesTestBusName, - Namespace: referencesTestNamespace, - } - actual := buses.NewBusReference(bus) - if expected != actual { - t.Errorf("%s expected: %+v got: %+v", "BusReference", expected, actual) - } -} - -func TestNewBusReference_ClusterBus(t *testing.T) { - clusterBus := &channelsv1alpha1.ClusterBus{ - ObjectMeta: metav1.ObjectMeta{ - Name: referencesTestClusterBusName, - }, - } - expected := buses.BusReference{ - Name: referencesTestClusterBusName, - } - actual := buses.NewBusReference(clusterBus) - if expected != actual { - t.Errorf("%s expected: %+v got: %+v", "BusReference", expected, actual) - } -} - -func TestNewBusReferenceFromNames(t *testing.T) { - expected := buses.BusReference{ - Name: referencesTestBusName, - Namespace: referencesTestNamespace, - } - actual := buses.NewBusReferenceFromNames(referencesTestBusName, referencesTestNamespace) - if expected != actual { - t.Errorf("%s expected: %+v got: %+v", "BusReference", expected, actual) - } -} - -func TestNewBusReferenceFromNames_ClusterBus(t *testing.T) { - expected := buses.BusReference{ - Name: referencesTestClusterBusName, - } - actual := buses.NewBusReferenceFromNames(referencesTestClusterBusName, "") - if expected != actual { - t.Errorf("%s expected: %+v got: %+v", "BusReference", expected, actual) - } -} - -func TestBusReference_IsNamespaced(t *testing.T) { - busRef := buses.BusReference{ - Name: referencesTestBusName, - Namespace: referencesTestNamespace, - } - expected := true - actual := busRef.IsNamespaced() - if expected != actual { - t.Errorf("%s expected: %+v got: %+v", "IsNamespaced", expected, actual) - } -} - -func TestBusReference_IsNamespaced_ClusterBus(t *testing.T) { - busRef := buses.BusReference{ - Name: referencesTestClusterBusName, - } - expected := false - actual := busRef.IsNamespaced() - if expected != actual { - t.Errorf("%s expected: %+v got: %+v", "IsNamespaced", expected, actual) - } -} - -func TestBusReference_String(t *testing.T) { - ref := buses.BusReference{ - Name: referencesTestBusName, - Namespace: referencesTestNamespace, - } - expected := fmt.Sprintf("%s/%s", referencesTestNamespace, referencesTestBusName) - actual := ref.String() - if expected != actual { - t.Errorf("%s expected: %+v got: %+v", "BusReference", expected, actual) - } -} - -func TestBusReference_String_ClusterBus(t *testing.T) { - ref := buses.BusReference{ - Name: referencesTestClusterBusName, - } - expected := referencesTestClusterBusName - actual := ref.String() - if expected != actual { - t.Errorf("%s expected: %+v got: %+v", "BusReference", expected, actual) - } -} - func TestNewChannelReference(t *testing.T) { - channel := &channelsv1alpha1.Channel{ + channel := &eventingv1alpha1.Channel{ ObjectMeta: metav1.ObjectMeta{ Name: referencesTestChannelName, Namespace: referencesTestNamespace, @@ -150,13 +50,15 @@ func TestNewChannelReference(t *testing.T) { } func TestNewChannelReferenceFromSubscription(t *testing.T) { - subscription := &channelsv1alpha1.Subscription{ + subscription := &eventingv1alpha1.Subscription{ ObjectMeta: metav1.ObjectMeta{ Name: referencesTestSubscriptionName, Namespace: referencesTestNamespace, }, - Spec: channelsv1alpha1.SubscriptionSpec{ - Channel: referencesTestChannelName, + Spec: eventingv1alpha1.SubscriptionSpec{ + Channel: corev1.ObjectReference{ + Name: referencesTestChannelName, + }, }, } expected := buses.ChannelReference{ @@ -191,43 +93,3 @@ func TestChannelReference_String(t *testing.T) { t.Errorf("%s expected: %+v got: %+v", "ChannelReference", expected, actual) } } - -func TestNewSubscriptionReference(t *testing.T) { - subscription := &channelsv1alpha1.Subscription{ - ObjectMeta: metav1.ObjectMeta{ - Name: referencesTestSubscriptionName, - Namespace: referencesTestNamespace, - }, - } - expected := buses.SubscriptionReference{ - Name: referencesTestSubscriptionName, - Namespace: referencesTestNamespace, - } - actual := buses.NewSubscriptionReference(subscription) - if expected != actual { - t.Errorf("%s expected: %+v got: %+v", "SubscriptionReference", expected, actual) - } -} - -func TestNewSubscriptionReferenceFromNames(t *testing.T) { - expected := buses.SubscriptionReference{ - Name: referencesTestSubscriptionName, - Namespace: referencesTestNamespace, - } - actual := buses.NewSubscriptionReferenceFromNames(referencesTestSubscriptionName, referencesTestNamespace) - if expected != actual { - t.Errorf("%s expected: %+v got: %+v", "SubscriptionReference", expected, actual) - } -} - -func TestSubscriptionReference_String(t *testing.T) { - ref := buses.SubscriptionReference{ - Name: referencesTestSubscriptionName, - Namespace: referencesTestNamespace, - } - expected := fmt.Sprintf("%s/%s", referencesTestNamespace, referencesTestSubscriptionName) - actual := ref.String() - if expected != actual { - t.Errorf("%s expected: %+v got: %+v", "SubscriptionReference", expected, actual) - } -} diff --git a/pkg/buses/stub/bus.go b/pkg/buses/stub/bus.go deleted file mode 100644 index 0376364b17e..00000000000 --- a/pkg/buses/stub/bus.go +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright 2018 The Knative 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 stub - -import ( - "go.uber.org/zap" - - "github.com/knative/eventing/pkg/buses" -) - -// BusType is the type of the stub bus -const BusType = "stub" - -func NewStubBusDispatcher(ref buses.BusReference, opts *buses.BusOpts) *StubBus { - bus := &StubBus{ - channels: make(map[buses.ChannelReference]*stubChannel), - } - handlerFuncs := buses.EventHandlerFuncs{ - ProvisionFunc: func(channel buses.ChannelReference, parameters buses.ResolvedParameters) error { - bus.logger.Infof("Provision channel %q", channel.String()) - bus.addChannel(channel, parameters) - return nil - }, - UnprovisionFunc: func(channel buses.ChannelReference) error { - bus.logger.Infof("Unprovision channel %q", channel.String()) - bus.removeChannel(channel) - return nil - }, - SubscribeFunc: func(channel buses.ChannelReference, subscription buses.SubscriptionReference, parameters buses.ResolvedParameters) error { - bus.logger.Infof("Subscribe %q to %q channel", subscription.String(), channel.String()) - bus.channel(channel).addSubscription(subscription, parameters, bus.dispatcher) - return nil - }, - UnsubscribeFunc: func(channel buses.ChannelReference, subscription buses.SubscriptionReference) error { - bus.logger.Infof("Unsubscribe %q from %q channel", subscription.String(), channel.String()) - bus.channel(channel).removeSubscription(subscription) - return nil - }, - ReceiveMessageFunc: func(channel buses.ChannelReference, message *buses.Message) error { - bus.logger.Infof("Recieved message for %q channel", channel.String()) - bus.channel(channel).receiveMessage(message) - return nil - }, - } - bus.dispatcher = buses.NewBusDispatcher(ref, handlerFuncs, opts) - bus.logger = opts.Logger - - return bus -} - -type StubBus struct { - dispatcher buses.BusDispatcher - channels map[buses.ChannelReference]*stubChannel - - logger *zap.SugaredLogger -} - -func (b *StubBus) Run(threadness int, stopCh <-chan struct{}) { - b.dispatcher.Run(threadness, stopCh) -} - -func (b *StubBus) addChannel(ref buses.ChannelReference, parameters buses.ResolvedParameters) { - if channel, ok := b.channels[ref]; ok { - // update channel - channel.parameters = parameters - } else { - // create channel - b.channels[ref] = &stubChannel{ - ref: ref, - parameters: parameters, - subscriptions: make(map[buses.SubscriptionReference]*stubSubscription), - logger: b.logger.With(zap.String("channels.knative.dev/channel", ref.String())), - } - } -} - -func (b *StubBus) removeChannel(channel buses.ChannelReference) { - delete(b.channels, channel) -} - -func (b *StubBus) channel(channel buses.ChannelReference) *stubChannel { - return b.channels[channel] -} - -type stubChannel struct { - ref buses.ChannelReference - parameters buses.ResolvedParameters - subscriptions map[buses.SubscriptionReference]*stubSubscription - - logger *zap.SugaredLogger -} - -func (c *stubChannel) receiveMessage(message *buses.Message) { - for _, stubSubscription := range c.subscriptions { - go stubSubscription.dispatchMessage(message) - } -} - -func (c *stubChannel) addSubscription(ref buses.SubscriptionReference, parameters buses.ResolvedParameters, bus buses.BusDispatcher) { - if subscription, ok := c.subscriptions[ref]; ok { - // update subscription - subscription.parameters = parameters - } else { - // create subscription - c.subscriptions[ref] = &stubSubscription{ - ref: ref, - bus: bus, - parameters: parameters, - - logger: c.logger.With(zap.String("channels.knative.dev/subscription", ref.String())), - } - } -} - -func (c *stubChannel) removeSubscription(subscription buses.SubscriptionReference) { - delete(c.subscriptions, subscription) -} - -type stubSubscription struct { - ref buses.SubscriptionReference - bus buses.BusDispatcher - parameters buses.ResolvedParameters - - logger *zap.SugaredLogger -} - -func (s *stubSubscription) dispatchMessage(message *buses.Message) error { - err := s.bus.DispatchMessage(s.ref, message) - if err != nil { - s.logger.Warnf("Failed to dispatch message: %v", err) - } - return err -} diff --git a/pkg/buses/stub/bus_test.go b/pkg/buses/stub/bus_test.go deleted file mode 100644 index 2a75accdd4c..00000000000 --- a/pkg/buses/stub/bus_test.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright 2018 The Knative 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 stub - -import "testing" - -func TestStub(t *testing.T) { - // TODO: Implement tests in this directory, please. - // This file is used to make code coverage on this directly count. -} diff --git a/pkg/buses/stub/dispatcher/kodata/LICENSE b/pkg/buses/stub/dispatcher/kodata/LICENSE deleted file mode 120000 index 2a64f9d0fc6..00000000000 --- a/pkg/buses/stub/dispatcher/kodata/LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../../LICENSE \ No newline at end of file diff --git a/pkg/buses/stub/dispatcher/kodata/VENDOR-LICENSE b/pkg/buses/stub/dispatcher/kodata/VENDOR-LICENSE deleted file mode 120000 index 681789ed22f..00000000000 --- a/pkg/buses/stub/dispatcher/kodata/VENDOR-LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/pkg/buses/stub/dispatcher/main.go b/pkg/buses/stub/dispatcher/main.go deleted file mode 100644 index 4064c2c5e8e..00000000000 --- a/pkg/buses/stub/dispatcher/main.go +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2018 The Knative 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 main - -import ( - "flag" - "os" - - "github.com/knative/eventing/pkg/buses" - "github.com/knative/eventing/pkg/buses/stub" - "github.com/knative/pkg/signals" - "go.uber.org/zap" -) - -const ( - threadsPerReconciler = 1 -) - -func main() { - ref := buses.NewBusReferenceFromNames( - os.Getenv("BUS_NAME"), - os.Getenv("BUS_NAMESPACE"), - ) - - config := buses.NewLoggingConfig() - logger := buses.NewBusLoggerFromConfig(config) - defer logger.Sync() - logger = logger.With( - zap.String("channels.knative.dev/bus", ref.String()), - zap.String("channels.knative.dev/busType", stub.BusType), - zap.String("channels.knative.dev/busComponent", buses.Dispatcher), - ) - - opts := &buses.BusOpts{ - Logger: logger, - } - - flag.StringVar(&opts.KubeConfig, "kubeconfig", "", "Path to a kubeconfig. Only required if out-of-cluster.") - flag.StringVar(&opts.MasterURL, "master", "", "The address of the Kubernetes API server. Overrides any value in kubeconfig. Only required if out-of-cluster.") - flag.Parse() - - bus := stub.NewStubBusDispatcher(ref, opts) - - // set up signals so we handle the first shutdown signal gracefully - stopCh := signals.SetupSignalHandler() - bus.Run(threadsPerReconciler, stopCh) -} diff --git a/pkg/channeldefaulter/channel_defaulter.go b/pkg/channeldefaulter/channel_defaulter.go new file mode 100644 index 00000000000..c9469ca2634 --- /dev/null +++ b/pkg/channeldefaulter/channel_defaulter.go @@ -0,0 +1,141 @@ +/* +Copyright 2018 The Knative 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 channeldefaulter + +import ( + "sync/atomic" + + yaml "gopkg.in/yaml.v2" + "k8s.io/apimachinery/pkg/runtime" + + eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + "go.uber.org/zap" + corev1 "k8s.io/api/core/v1" +) + +const ( + // ConfigMapName is the name of the ConfigMap that contains the configuration for the default + // ClusterChannelProvisioner. + ConfigMapName = "default-channel-webhook" + + // channelDefaulterKey is the key in the ConfigMap to get the name of the default + // ClusterChannelProvisioner. + channelDefaulterKey = "default-channel-config" +) + +// Config is the data structure serialized to YAML in the config map. When a Channel needs to be +// defaulted, the Channel's namespace will be used as a key into NamespaceDefaults, if there is +// something present, then that is used. If not, then the ClusterDefault is used. +type Config struct { + // NamespaceDefaults are the default Channel provisioner for each namespace. namespace is the + // key, the value is the default provisioner to use. + NamespaceDefaults map[string]*corev1.ObjectReference `json:"namespaceDefaults,omitempty"` + // ClusterDefault is the default Channel provisioner for all namespaces that are not in + // NamespaceDefaults. + ClusterDefault *corev1.ObjectReference `json:"clusterDefault,omitempty"` +} + +// ChannelDefaulter adds a default ClusterChannelProvisioner to Channels that do not have any +// provisioner specified. The default is stored in a ConfigMap and can be updated at runtime. +type ChannelDefaulter struct { + // The current default ClusterChannelProvisioner to set. This should only be accessed via + // getConfig() and setConfig(), as they correctly enforce the type we require (*Config). + config atomic.Value + logger *zap.Logger +} + +var _ eventingv1alpha1.ChannelProvisionerDefaulter = &ChannelDefaulter{} + +// New creates a new ChannelDefaulter. The caller is expected to set this as the global singleton. +// +// channelDefaulter := channeldefaulter.New(logger) +// eventingv1alpha1.ChannelDefaulterSingleton = channelDefaulter +// configMapWatcher.Watch(channeldefaulter.ConfigMapName, channelDefaulter.UpdateConfigMap) +func New(logger *zap.Logger) *ChannelDefaulter { + return &ChannelDefaulter{ + logger: logger.With(zap.String("role", "channelDefaulter")), + } +} + +// UpdateConfigMap reads in a ConfigMap and updates the internal default ClusterChannelProvisioner +// to use. +func (cd *ChannelDefaulter) UpdateConfigMap(cm *corev1.ConfigMap) { + if cm == nil { + cd.logger.Info("UpdateConfigMap on a nil map") + return + } + defaultChannelConfig, present := cm.Data[channelDefaulterKey] + if !present { + cd.logger.Info("ConfigMap is missing key", zap.String("key", channelDefaulterKey), zap.Any("configMap", cm)) + return + } + + if defaultChannelConfig == "" { + cd.logger.Info("ConfigMap's value was the empty string, ignoring it.", zap.Any("configMap", cm)) + return + } + + config := Config{} + if err := yaml.UnmarshalStrict([]byte(defaultChannelConfig), &config); err != nil { + cd.logger.Error("ConfigMap's value could not be unmarshaled.", zap.Error(err), zap.Any("configMap", cm)) + return + } + + cd.logger.Info("Updated channelDefaulter config", zap.Any("config", config)) + cd.setConfig(&config) +} + +// setConfig is a typed wrapper around config. +func (cd *ChannelDefaulter) setConfig(config *Config) { + cd.config.Store(config) +} + +// getConfig is a typed wrapper around config. +func (cd *ChannelDefaulter) getConfig() *Config { + if config, ok := cd.config.Load().(*Config); ok { + return config + } + return nil +} + +// GetDefault determines the default provisioner and arguments for the provided channel. +func (cd *ChannelDefaulter) GetDefault(c *eventingv1alpha1.Channel) (*corev1.ObjectReference, *runtime.RawExtension) { + // Because we are treating this as a singleton, be tolerant to it having not been setup at all. + if cd == nil { + return nil, nil + } + if c == nil { + return nil, nil + } + config := cd.getConfig() + if config == nil { + return nil, nil + } + + // TODO Don't use a single default, instead use the Channel's arguments to determine the type of + // Channel to use (e.g. it can say whether it needs to be persistent, strictly ordered, etc.). + dp := getDefaultProvisioner(config, c.Namespace) + cd.logger.Info("Defaulting the ClusterChannelProvisioner", zap.Any("defaultClusterChannelProvisioner", dp)) + return dp, nil +} + +func getDefaultProvisioner(config *Config, namespace string) *corev1.ObjectReference { + if dp, ok := config.NamespaceDefaults[namespace]; ok { + return dp + } + return config.ClusterDefault +} diff --git a/pkg/channeldefaulter/channel_defaulter_test.go b/pkg/channeldefaulter/channel_defaulter_test.go new file mode 100644 index 00000000000..1861eb68899 --- /dev/null +++ b/pkg/channeldefaulter/channel_defaulter_test.go @@ -0,0 +1,229 @@ +/* +Copyright 2018 The Knative 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 channeldefaulter + +import ( + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + "go.uber.org/zap" + yaml "gopkg.in/yaml.v2" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +var ( + config = &Config{ + ClusterDefault: &corev1.ObjectReference{ + APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), + Kind: "ClusterChannelProvisioner", + Name: "test-channel-provisioner", + }, + } + // configYaml is the YAML form of config. It is generated in init(). + configYaml string + + testNamespace = "test-namespace" + configWithNamespace = &Config{ + ClusterDefault: &corev1.ObjectReference{ + Name: "cluster-default", + }, + NamespaceDefaults: map[string]*corev1.ObjectReference{ + testNamespace: { + Name: "namespace-default", + }, + }, + } +) + +func init() { + configYamlBytes, _ := yaml.Marshal(config) + configYaml = string(configYamlBytes) +} + +func TestChannelDefaulter_getDefaultProvider(t *testing.T) { + testCases := map[string]struct { + nilChannelDefaulter bool + config *Config + channel *eventingv1alpha1.Channel + expectedProv *corev1.ObjectReference + }{ + "nil channel defaulter": { + nilChannelDefaulter: true, + }, + "nil spec": {}, + "no default set": { + channel: &eventingv1alpha1.Channel{}, + expectedProv: nil, + }, + "cluster defaulted": { + config: config, + channel: &eventingv1alpha1.Channel{}, + expectedProv: config.ClusterDefault, + }, + "namespace defaulted": { + config: configWithNamespace, + channel: &eventingv1alpha1.Channel{ + ObjectMeta: v1.ObjectMeta{ + Namespace: testNamespace, + }, + }, + expectedProv: configWithNamespace.NamespaceDefaults[testNamespace], + }, + } + for n, tc := range testCases { + t.Run(n, func(t *testing.T) { + var cd *ChannelDefaulter + if !tc.nilChannelDefaulter { + cd = New(zap.NewNop()) + } + if tc.config != nil { + cd.setConfig(tc.config) + } + prov, args := cd.GetDefault(tc.channel) + if diff := cmp.Diff(tc.expectedProv, prov); diff != "" { + t.Fatalf("Unexpected provisioner (-want, +got): %s", diff) + } + if args != nil { + t.Fatalf("Unexpected args, expected nil: %v", args) + } + }) + } +} + +func TestChannelDefaulter_UpdateConfigMap(t *testing.T) { + testCases := map[string]struct { + initialConfig *corev1.ConfigMap + expectedAfterInitial *corev1.ObjectReference + updatedConfig *corev1.ConfigMap + expectedAfterUpdate *corev1.ObjectReference + }{ + "nil config map": { + expectedAfterInitial: nil, + expectedAfterUpdate: nil, + }, + "key missing in update": { + initialConfig: &corev1.ConfigMap{ + Data: map[string]string{ + channelDefaulterKey: configYaml, + }, + }, + expectedAfterInitial: config.ClusterDefault, + updatedConfig: &corev1.ConfigMap{}, + expectedAfterUpdate: config.ClusterDefault, + }, + "bad yaml is ignored": { + initialConfig: &corev1.ConfigMap{ + Data: map[string]string{ + channelDefaulterKey: configYaml, + }, + }, + expectedAfterInitial: config.ClusterDefault, + updatedConfig: &corev1.ConfigMap{ + Data: map[string]string{ + channelDefaulterKey: "{foo: bar}", + }, + }, + expectedAfterUpdate: config.ClusterDefault, + }, + "empty config is accepted": { + initialConfig: &corev1.ConfigMap{ + Data: map[string]string{ + channelDefaulterKey: configYaml, + }, + }, + expectedAfterInitial: config.ClusterDefault, + updatedConfig: &corev1.ConfigMap{ + Data: map[string]string{ + channelDefaulterKey: "{}", + }, + }, + expectedAfterUpdate: nil, + }, + "empty string is ignored": { + initialConfig: &corev1.ConfigMap{ + Data: map[string]string{ + channelDefaulterKey: configYaml, + }, + }, + expectedAfterInitial: config.ClusterDefault, + updatedConfig: &corev1.ConfigMap{ + Data: map[string]string{ + channelDefaulterKey: "", + }, + }, + expectedAfterUpdate: config.ClusterDefault, + }, + "update to same provisioner": { + initialConfig: &corev1.ConfigMap{ + Data: map[string]string{ + channelDefaulterKey: configYaml, + }, + }, + expectedAfterInitial: config.ClusterDefault, + updatedConfig: &corev1.ConfigMap{ + Data: map[string]string{ + channelDefaulterKey: configYaml, + }, + }, + expectedAfterUpdate: config.ClusterDefault, + }, + "update to different provisioner": { + initialConfig: &corev1.ConfigMap{ + Data: map[string]string{ + channelDefaulterKey: configYaml, + }, + }, + expectedAfterInitial: config.ClusterDefault, + updatedConfig: &corev1.ConfigMap{ + Data: map[string]string{ + channelDefaulterKey: strings.Replace(configYaml, config.ClusterDefault.Name, "some-other-name", -1), + }, + }, + expectedAfterUpdate: &corev1.ObjectReference{ + APIVersion: config.ClusterDefault.APIVersion, + Kind: config.ClusterDefault.Kind, + Name: "some-other-name", + }, + }, + } + for n, tc := range testCases { + t.Run(n, func(t *testing.T) { + cd := New(zap.NewNop()) + cd.UpdateConfigMap(tc.initialConfig) + + prov, args := cd.GetDefault(&eventingv1alpha1.Channel{}) + if diff := cmp.Diff(tc.expectedAfterInitial, prov); diff != "" { + t.Fatalf("Unexpected difference after intial configMap update (-want, +got): %s", diff) + } + if args != nil { + t.Fatalf("Unexpected args after initial configMap update. Expected nil. %v", args) + } + + cd.UpdateConfigMap(tc.updatedConfig) + prov, args = cd.GetDefault(&eventingv1alpha1.Channel{}) + if diff := cmp.Diff(tc.expectedAfterUpdate, prov); diff != "" { + t.Fatalf("Unexpected difference after update configMap update (-want, +got): %s", diff) + } + if args != nil { + t.Fatalf("Unexpected args after initial configMap update. Expected nil. %v", args) + } + }) + } +} diff --git a/pkg/client/clientset/versioned/clientset.go b/pkg/client/clientset/versioned/clientset.go index c9df07b37da..4f8f6c7c4c3 100644 --- a/pkg/client/clientset/versioned/clientset.go +++ b/pkg/client/clientset/versioned/clientset.go @@ -19,10 +19,7 @@ limitations under the License. package versioned import ( - channelsv1alpha1 "github.com/knative/eventing/pkg/client/clientset/versioned/typed/channels/v1alpha1" eventingv1alpha1 "github.com/knative/eventing/pkg/client/clientset/versioned/typed/eventing/v1alpha1" - feedsv1alpha1 "github.com/knative/eventing/pkg/client/clientset/versioned/typed/feeds/v1alpha1" - flowsv1alpha1 "github.com/knative/eventing/pkg/client/clientset/versioned/typed/flows/v1alpha1" discovery "k8s.io/client-go/discovery" rest "k8s.io/client-go/rest" flowcontrol "k8s.io/client-go/util/flowcontrol" @@ -30,39 +27,16 @@ import ( type Interface interface { Discovery() discovery.DiscoveryInterface - ChannelsV1alpha1() channelsv1alpha1.ChannelsV1alpha1Interface - // Deprecated: please explicitly pick a version if possible. - Channels() channelsv1alpha1.ChannelsV1alpha1Interface EventingV1alpha1() eventingv1alpha1.EventingV1alpha1Interface // Deprecated: please explicitly pick a version if possible. Eventing() eventingv1alpha1.EventingV1alpha1Interface - FeedsV1alpha1() feedsv1alpha1.FeedsV1alpha1Interface - // Deprecated: please explicitly pick a version if possible. - Feeds() feedsv1alpha1.FeedsV1alpha1Interface - FlowsV1alpha1() flowsv1alpha1.FlowsV1alpha1Interface - // Deprecated: please explicitly pick a version if possible. - Flows() flowsv1alpha1.FlowsV1alpha1Interface } // Clientset contains the clients for groups. Each group has exactly one // version included in a Clientset. type Clientset struct { *discovery.DiscoveryClient - channelsV1alpha1 *channelsv1alpha1.ChannelsV1alpha1Client eventingV1alpha1 *eventingv1alpha1.EventingV1alpha1Client - feedsV1alpha1 *feedsv1alpha1.FeedsV1alpha1Client - flowsV1alpha1 *flowsv1alpha1.FlowsV1alpha1Client -} - -// ChannelsV1alpha1 retrieves the ChannelsV1alpha1Client -func (c *Clientset) ChannelsV1alpha1() channelsv1alpha1.ChannelsV1alpha1Interface { - return c.channelsV1alpha1 -} - -// Deprecated: Channels retrieves the default version of ChannelsClient. -// Please explicitly pick a version. -func (c *Clientset) Channels() channelsv1alpha1.ChannelsV1alpha1Interface { - return c.channelsV1alpha1 } // EventingV1alpha1 retrieves the EventingV1alpha1Client @@ -76,28 +50,6 @@ func (c *Clientset) Eventing() eventingv1alpha1.EventingV1alpha1Interface { return c.eventingV1alpha1 } -// FeedsV1alpha1 retrieves the FeedsV1alpha1Client -func (c *Clientset) FeedsV1alpha1() feedsv1alpha1.FeedsV1alpha1Interface { - return c.feedsV1alpha1 -} - -// Deprecated: Feeds retrieves the default version of FeedsClient. -// Please explicitly pick a version. -func (c *Clientset) Feeds() feedsv1alpha1.FeedsV1alpha1Interface { - return c.feedsV1alpha1 -} - -// FlowsV1alpha1 retrieves the FlowsV1alpha1Client -func (c *Clientset) FlowsV1alpha1() flowsv1alpha1.FlowsV1alpha1Interface { - return c.flowsV1alpha1 -} - -// Deprecated: Flows retrieves the default version of FlowsClient. -// Please explicitly pick a version. -func (c *Clientset) Flows() flowsv1alpha1.FlowsV1alpha1Interface { - return c.flowsV1alpha1 -} - // Discovery retrieves the DiscoveryClient func (c *Clientset) Discovery() discovery.DiscoveryInterface { if c == nil { @@ -114,22 +66,10 @@ func NewForConfig(c *rest.Config) (*Clientset, error) { } var cs Clientset var err error - cs.channelsV1alpha1, err = channelsv1alpha1.NewForConfig(&configShallowCopy) - if err != nil { - return nil, err - } cs.eventingV1alpha1, err = eventingv1alpha1.NewForConfig(&configShallowCopy) if err != nil { return nil, err } - cs.feedsV1alpha1, err = feedsv1alpha1.NewForConfig(&configShallowCopy) - if err != nil { - return nil, err - } - cs.flowsV1alpha1, err = flowsv1alpha1.NewForConfig(&configShallowCopy) - if err != nil { - return nil, err - } cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy) if err != nil { @@ -142,10 +82,7 @@ func NewForConfig(c *rest.Config) (*Clientset, error) { // panics if there is an error in the config. func NewForConfigOrDie(c *rest.Config) *Clientset { var cs Clientset - cs.channelsV1alpha1 = channelsv1alpha1.NewForConfigOrDie(c) cs.eventingV1alpha1 = eventingv1alpha1.NewForConfigOrDie(c) - cs.feedsV1alpha1 = feedsv1alpha1.NewForConfigOrDie(c) - cs.flowsV1alpha1 = flowsv1alpha1.NewForConfigOrDie(c) cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c) return &cs @@ -154,10 +91,7 @@ func NewForConfigOrDie(c *rest.Config) *Clientset { // New creates a new Clientset for the given RESTClient. func New(c rest.Interface) *Clientset { var cs Clientset - cs.channelsV1alpha1 = channelsv1alpha1.New(c) cs.eventingV1alpha1 = eventingv1alpha1.New(c) - cs.feedsV1alpha1 = feedsv1alpha1.New(c) - cs.flowsV1alpha1 = flowsv1alpha1.New(c) cs.DiscoveryClient = discovery.NewDiscoveryClient(c) return &cs diff --git a/pkg/client/clientset/versioned/fake/clientset_generated.go b/pkg/client/clientset/versioned/fake/clientset_generated.go index 1a6301babe4..0a4b10bfa14 100644 --- a/pkg/client/clientset/versioned/fake/clientset_generated.go +++ b/pkg/client/clientset/versioned/fake/clientset_generated.go @@ -20,14 +20,8 @@ package fake import ( clientset "github.com/knative/eventing/pkg/client/clientset/versioned" - channelsv1alpha1 "github.com/knative/eventing/pkg/client/clientset/versioned/typed/channels/v1alpha1" - fakechannelsv1alpha1 "github.com/knative/eventing/pkg/client/clientset/versioned/typed/channels/v1alpha1/fake" eventingv1alpha1 "github.com/knative/eventing/pkg/client/clientset/versioned/typed/eventing/v1alpha1" fakeeventingv1alpha1 "github.com/knative/eventing/pkg/client/clientset/versioned/typed/eventing/v1alpha1/fake" - feedsv1alpha1 "github.com/knative/eventing/pkg/client/clientset/versioned/typed/feeds/v1alpha1" - fakefeedsv1alpha1 "github.com/knative/eventing/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake" - flowsv1alpha1 "github.com/knative/eventing/pkg/client/clientset/versioned/typed/flows/v1alpha1" - fakeflowsv1alpha1 "github.com/knative/eventing/pkg/client/clientset/versioned/typed/flows/v1alpha1/fake" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/discovery" @@ -77,16 +71,6 @@ func (c *Clientset) Discovery() discovery.DiscoveryInterface { var _ clientset.Interface = &Clientset{} -// ChannelsV1alpha1 retrieves the ChannelsV1alpha1Client -func (c *Clientset) ChannelsV1alpha1() channelsv1alpha1.ChannelsV1alpha1Interface { - return &fakechannelsv1alpha1.FakeChannelsV1alpha1{Fake: &c.Fake} -} - -// Channels retrieves the ChannelsV1alpha1Client -func (c *Clientset) Channels() channelsv1alpha1.ChannelsV1alpha1Interface { - return &fakechannelsv1alpha1.FakeChannelsV1alpha1{Fake: &c.Fake} -} - // EventingV1alpha1 retrieves the EventingV1alpha1Client func (c *Clientset) EventingV1alpha1() eventingv1alpha1.EventingV1alpha1Interface { return &fakeeventingv1alpha1.FakeEventingV1alpha1{Fake: &c.Fake} @@ -96,23 +80,3 @@ func (c *Clientset) EventingV1alpha1() eventingv1alpha1.EventingV1alpha1Interfac func (c *Clientset) Eventing() eventingv1alpha1.EventingV1alpha1Interface { return &fakeeventingv1alpha1.FakeEventingV1alpha1{Fake: &c.Fake} } - -// FeedsV1alpha1 retrieves the FeedsV1alpha1Client -func (c *Clientset) FeedsV1alpha1() feedsv1alpha1.FeedsV1alpha1Interface { - return &fakefeedsv1alpha1.FakeFeedsV1alpha1{Fake: &c.Fake} -} - -// Feeds retrieves the FeedsV1alpha1Client -func (c *Clientset) Feeds() feedsv1alpha1.FeedsV1alpha1Interface { - return &fakefeedsv1alpha1.FakeFeedsV1alpha1{Fake: &c.Fake} -} - -// FlowsV1alpha1 retrieves the FlowsV1alpha1Client -func (c *Clientset) FlowsV1alpha1() flowsv1alpha1.FlowsV1alpha1Interface { - return &fakeflowsv1alpha1.FakeFlowsV1alpha1{Fake: &c.Fake} -} - -// Flows retrieves the FlowsV1alpha1Client -func (c *Clientset) Flows() flowsv1alpha1.FlowsV1alpha1Interface { - return &fakeflowsv1alpha1.FakeFlowsV1alpha1{Fake: &c.Fake} -} diff --git a/pkg/client/clientset/versioned/fake/register.go b/pkg/client/clientset/versioned/fake/register.go index 9c7ef66dd10..8e722c05baa 100644 --- a/pkg/client/clientset/versioned/fake/register.go +++ b/pkg/client/clientset/versioned/fake/register.go @@ -19,10 +19,7 @@ limitations under the License. package fake import ( - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" - feedsv1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - flowsv1alpha1 "github.com/knative/eventing/pkg/apis/flows/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" schema "k8s.io/apimachinery/pkg/runtime/schema" @@ -53,8 +50,5 @@ func init() { // After this, RawExtensions in Kubernetes types will serialize kube-aggregator types // correctly. func AddToScheme(scheme *runtime.Scheme) { - channelsv1alpha1.AddToScheme(scheme) eventingv1alpha1.AddToScheme(scheme) - feedsv1alpha1.AddToScheme(scheme) - flowsv1alpha1.AddToScheme(scheme) } diff --git a/pkg/client/clientset/versioned/scheme/register.go b/pkg/client/clientset/versioned/scheme/register.go index b3afb7f218d..48c902c17c3 100644 --- a/pkg/client/clientset/versioned/scheme/register.go +++ b/pkg/client/clientset/versioned/scheme/register.go @@ -19,10 +19,7 @@ limitations under the License. package scheme import ( - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" - feedsv1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - flowsv1alpha1 "github.com/knative/eventing/pkg/apis/flows/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" schema "k8s.io/apimachinery/pkg/runtime/schema" @@ -53,8 +50,5 @@ func init() { // After this, RawExtensions in Kubernetes types will serialize kube-aggregator types // correctly. func AddToScheme(scheme *runtime.Scheme) { - channelsv1alpha1.AddToScheme(scheme) eventingv1alpha1.AddToScheme(scheme) - feedsv1alpha1.AddToScheme(scheme) - flowsv1alpha1.AddToScheme(scheme) } diff --git a/pkg/client/clientset/versioned/typed/channels/v1alpha1/bus.go b/pkg/client/clientset/versioned/typed/channels/v1alpha1/bus.go deleted file mode 100644 index 12450331d50..00000000000 --- a/pkg/client/clientset/versioned/typed/channels/v1alpha1/bus.go +++ /dev/null @@ -1,157 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - scheme "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// BusesGetter has a method to return a BusInterface. -// A group's client should implement this interface. -type BusesGetter interface { - Buses(namespace string) BusInterface -} - -// BusInterface has methods to work with Bus resources. -type BusInterface interface { - Create(*v1alpha1.Bus) (*v1alpha1.Bus, error) - Update(*v1alpha1.Bus) (*v1alpha1.Bus, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.Bus, error) - List(opts v1.ListOptions) (*v1alpha1.BusList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Bus, err error) - BusExpansion -} - -// buses implements BusInterface -type buses struct { - client rest.Interface - ns string -} - -// newBuses returns a Buses -func newBuses(c *ChannelsV1alpha1Client, namespace string) *buses { - return &buses{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the bus, and returns the corresponding bus object, and an error if there is any. -func (c *buses) Get(name string, options v1.GetOptions) (result *v1alpha1.Bus, err error) { - result = &v1alpha1.Bus{} - err = c.client.Get(). - Namespace(c.ns). - Resource("buses"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of Buses that match those selectors. -func (c *buses) List(opts v1.ListOptions) (result *v1alpha1.BusList, err error) { - result = &v1alpha1.BusList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("buses"). - VersionedParams(&opts, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested buses. -func (c *buses) Watch(opts v1.ListOptions) (watch.Interface, error) { - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("buses"). - VersionedParams(&opts, scheme.ParameterCodec). - Watch() -} - -// Create takes the representation of a bus and creates it. Returns the server's representation of the bus, and an error, if there is any. -func (c *buses) Create(bus *v1alpha1.Bus) (result *v1alpha1.Bus, err error) { - result = &v1alpha1.Bus{} - err = c.client.Post(). - Namespace(c.ns). - Resource("buses"). - Body(bus). - Do(). - Into(result) - return -} - -// Update takes the representation of a bus and updates it. Returns the server's representation of the bus, and an error, if there is any. -func (c *buses) Update(bus *v1alpha1.Bus) (result *v1alpha1.Bus, err error) { - result = &v1alpha1.Bus{} - err = c.client.Put(). - Namespace(c.ns). - Resource("buses"). - Name(bus.Name). - Body(bus). - Do(). - Into(result) - return -} - -// Delete takes name of the bus and deletes it. Returns an error if one occurs. -func (c *buses) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("buses"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *buses) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("buses"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched bus. -func (c *buses) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Bus, err error) { - result = &v1alpha1.Bus{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("buses"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/pkg/client/clientset/versioned/typed/channels/v1alpha1/channel.go b/pkg/client/clientset/versioned/typed/channels/v1alpha1/channel.go deleted file mode 100644 index f9a51328615..00000000000 --- a/pkg/client/clientset/versioned/typed/channels/v1alpha1/channel.go +++ /dev/null @@ -1,157 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - scheme "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// ChannelsGetter has a method to return a ChannelInterface. -// A group's client should implement this interface. -type ChannelsGetter interface { - Channels(namespace string) ChannelInterface -} - -// ChannelInterface has methods to work with Channel resources. -type ChannelInterface interface { - Create(*v1alpha1.Channel) (*v1alpha1.Channel, error) - Update(*v1alpha1.Channel) (*v1alpha1.Channel, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.Channel, error) - List(opts v1.ListOptions) (*v1alpha1.ChannelList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Channel, err error) - ChannelExpansion -} - -// channels implements ChannelInterface -type channels struct { - client rest.Interface - ns string -} - -// newChannels returns a Channels -func newChannels(c *ChannelsV1alpha1Client, namespace string) *channels { - return &channels{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the channel, and returns the corresponding channel object, and an error if there is any. -func (c *channels) Get(name string, options v1.GetOptions) (result *v1alpha1.Channel, err error) { - result = &v1alpha1.Channel{} - err = c.client.Get(). - Namespace(c.ns). - Resource("channels"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of Channels that match those selectors. -func (c *channels) List(opts v1.ListOptions) (result *v1alpha1.ChannelList, err error) { - result = &v1alpha1.ChannelList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("channels"). - VersionedParams(&opts, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested channels. -func (c *channels) Watch(opts v1.ListOptions) (watch.Interface, error) { - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("channels"). - VersionedParams(&opts, scheme.ParameterCodec). - Watch() -} - -// Create takes the representation of a channel and creates it. Returns the server's representation of the channel, and an error, if there is any. -func (c *channels) Create(channel *v1alpha1.Channel) (result *v1alpha1.Channel, err error) { - result = &v1alpha1.Channel{} - err = c.client.Post(). - Namespace(c.ns). - Resource("channels"). - Body(channel). - Do(). - Into(result) - return -} - -// Update takes the representation of a channel and updates it. Returns the server's representation of the channel, and an error, if there is any. -func (c *channels) Update(channel *v1alpha1.Channel) (result *v1alpha1.Channel, err error) { - result = &v1alpha1.Channel{} - err = c.client.Put(). - Namespace(c.ns). - Resource("channels"). - Name(channel.Name). - Body(channel). - Do(). - Into(result) - return -} - -// Delete takes name of the channel and deletes it. Returns an error if one occurs. -func (c *channels) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("channels"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *channels) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("channels"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched channel. -func (c *channels) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Channel, err error) { - result = &v1alpha1.Channel{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("channels"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/pkg/client/clientset/versioned/typed/channels/v1alpha1/clusterbus.go b/pkg/client/clientset/versioned/typed/channels/v1alpha1/clusterbus.go deleted file mode 100644 index 707d2e04e4e..00000000000 --- a/pkg/client/clientset/versioned/typed/channels/v1alpha1/clusterbus.go +++ /dev/null @@ -1,147 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - scheme "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// ClusterBusesGetter has a method to return a ClusterBusInterface. -// A group's client should implement this interface. -type ClusterBusesGetter interface { - ClusterBuses() ClusterBusInterface -} - -// ClusterBusInterface has methods to work with ClusterBus resources. -type ClusterBusInterface interface { - Create(*v1alpha1.ClusterBus) (*v1alpha1.ClusterBus, error) - Update(*v1alpha1.ClusterBus) (*v1alpha1.ClusterBus, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.ClusterBus, error) - List(opts v1.ListOptions) (*v1alpha1.ClusterBusList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterBus, err error) - ClusterBusExpansion -} - -// clusterBuses implements ClusterBusInterface -type clusterBuses struct { - client rest.Interface -} - -// newClusterBuses returns a ClusterBuses -func newClusterBuses(c *ChannelsV1alpha1Client) *clusterBuses { - return &clusterBuses{ - client: c.RESTClient(), - } -} - -// Get takes name of the clusterBus, and returns the corresponding clusterBus object, and an error if there is any. -func (c *clusterBuses) Get(name string, options v1.GetOptions) (result *v1alpha1.ClusterBus, err error) { - result = &v1alpha1.ClusterBus{} - err = c.client.Get(). - Resource("clusterbuses"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of ClusterBuses that match those selectors. -func (c *clusterBuses) List(opts v1.ListOptions) (result *v1alpha1.ClusterBusList, err error) { - result = &v1alpha1.ClusterBusList{} - err = c.client.Get(). - Resource("clusterbuses"). - VersionedParams(&opts, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested clusterBuses. -func (c *clusterBuses) Watch(opts v1.ListOptions) (watch.Interface, error) { - opts.Watch = true - return c.client.Get(). - Resource("clusterbuses"). - VersionedParams(&opts, scheme.ParameterCodec). - Watch() -} - -// Create takes the representation of a clusterBus and creates it. Returns the server's representation of the clusterBus, and an error, if there is any. -func (c *clusterBuses) Create(clusterBus *v1alpha1.ClusterBus) (result *v1alpha1.ClusterBus, err error) { - result = &v1alpha1.ClusterBus{} - err = c.client.Post(). - Resource("clusterbuses"). - Body(clusterBus). - Do(). - Into(result) - return -} - -// Update takes the representation of a clusterBus and updates it. Returns the server's representation of the clusterBus, and an error, if there is any. -func (c *clusterBuses) Update(clusterBus *v1alpha1.ClusterBus) (result *v1alpha1.ClusterBus, err error) { - result = &v1alpha1.ClusterBus{} - err = c.client.Put(). - Resource("clusterbuses"). - Name(clusterBus.Name). - Body(clusterBus). - Do(). - Into(result) - return -} - -// Delete takes name of the clusterBus and deletes it. Returns an error if one occurs. -func (c *clusterBuses) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Resource("clusterbuses"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *clusterBuses) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - return c.client.Delete(). - Resource("clusterbuses"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched clusterBus. -func (c *clusterBuses) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterBus, err error) { - result = &v1alpha1.ClusterBus{} - err = c.client.Patch(pt). - Resource("clusterbuses"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/pkg/client/clientset/versioned/typed/channels/v1alpha1/fake/fake_bus.go b/pkg/client/clientset/versioned/typed/channels/v1alpha1/fake/fake_bus.go deleted file mode 100644 index 3c68d02db36..00000000000 --- a/pkg/client/clientset/versioned/typed/channels/v1alpha1/fake/fake_bus.go +++ /dev/null @@ -1,128 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeBuses implements BusInterface -type FakeBuses struct { - Fake *FakeChannelsV1alpha1 - ns string -} - -var busesResource = schema.GroupVersionResource{Group: "channels.knative.dev", Version: "v1alpha1", Resource: "buses"} - -var busesKind = schema.GroupVersionKind{Group: "channels.knative.dev", Version: "v1alpha1", Kind: "Bus"} - -// Get takes name of the bus, and returns the corresponding bus object, and an error if there is any. -func (c *FakeBuses) Get(name string, options v1.GetOptions) (result *v1alpha1.Bus, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(busesResource, c.ns, name), &v1alpha1.Bus{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Bus), err -} - -// List takes label and field selectors, and returns the list of Buses that match those selectors. -func (c *FakeBuses) List(opts v1.ListOptions) (result *v1alpha1.BusList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(busesResource, busesKind, c.ns, opts), &v1alpha1.BusList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.BusList{ListMeta: obj.(*v1alpha1.BusList).ListMeta} - for _, item := range obj.(*v1alpha1.BusList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested buses. -func (c *FakeBuses) Watch(opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(busesResource, c.ns, opts)) - -} - -// Create takes the representation of a bus and creates it. Returns the server's representation of the bus, and an error, if there is any. -func (c *FakeBuses) Create(bus *v1alpha1.Bus) (result *v1alpha1.Bus, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(busesResource, c.ns, bus), &v1alpha1.Bus{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Bus), err -} - -// Update takes the representation of a bus and updates it. Returns the server's representation of the bus, and an error, if there is any. -func (c *FakeBuses) Update(bus *v1alpha1.Bus) (result *v1alpha1.Bus, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(busesResource, c.ns, bus), &v1alpha1.Bus{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Bus), err -} - -// Delete takes name of the bus and deletes it. Returns an error if one occurs. -func (c *FakeBuses) Delete(name string, options *v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteAction(busesResource, c.ns, name), &v1alpha1.Bus{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeBuses) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(busesResource, c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &v1alpha1.BusList{}) - return err -} - -// Patch applies the patch and returns the patched bus. -func (c *FakeBuses) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Bus, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(busesResource, c.ns, name, data, subresources...), &v1alpha1.Bus{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Bus), err -} diff --git a/pkg/client/clientset/versioned/typed/channels/v1alpha1/fake/fake_channel.go b/pkg/client/clientset/versioned/typed/channels/v1alpha1/fake/fake_channel.go deleted file mode 100644 index cf32da5a015..00000000000 --- a/pkg/client/clientset/versioned/typed/channels/v1alpha1/fake/fake_channel.go +++ /dev/null @@ -1,128 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeChannels implements ChannelInterface -type FakeChannels struct { - Fake *FakeChannelsV1alpha1 - ns string -} - -var channelsResource = schema.GroupVersionResource{Group: "channels.knative.dev", Version: "v1alpha1", Resource: "channels"} - -var channelsKind = schema.GroupVersionKind{Group: "channels.knative.dev", Version: "v1alpha1", Kind: "Channel"} - -// Get takes name of the channel, and returns the corresponding channel object, and an error if there is any. -func (c *FakeChannels) Get(name string, options v1.GetOptions) (result *v1alpha1.Channel, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(channelsResource, c.ns, name), &v1alpha1.Channel{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Channel), err -} - -// List takes label and field selectors, and returns the list of Channels that match those selectors. -func (c *FakeChannels) List(opts v1.ListOptions) (result *v1alpha1.ChannelList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(channelsResource, channelsKind, c.ns, opts), &v1alpha1.ChannelList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.ChannelList{ListMeta: obj.(*v1alpha1.ChannelList).ListMeta} - for _, item := range obj.(*v1alpha1.ChannelList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested channels. -func (c *FakeChannels) Watch(opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(channelsResource, c.ns, opts)) - -} - -// Create takes the representation of a channel and creates it. Returns the server's representation of the channel, and an error, if there is any. -func (c *FakeChannels) Create(channel *v1alpha1.Channel) (result *v1alpha1.Channel, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(channelsResource, c.ns, channel), &v1alpha1.Channel{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Channel), err -} - -// Update takes the representation of a channel and updates it. Returns the server's representation of the channel, and an error, if there is any. -func (c *FakeChannels) Update(channel *v1alpha1.Channel) (result *v1alpha1.Channel, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(channelsResource, c.ns, channel), &v1alpha1.Channel{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Channel), err -} - -// Delete takes name of the channel and deletes it. Returns an error if one occurs. -func (c *FakeChannels) Delete(name string, options *v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteAction(channelsResource, c.ns, name), &v1alpha1.Channel{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeChannels) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(channelsResource, c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &v1alpha1.ChannelList{}) - return err -} - -// Patch applies the patch and returns the patched channel. -func (c *FakeChannels) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Channel, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(channelsResource, c.ns, name, data, subresources...), &v1alpha1.Channel{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Channel), err -} diff --git a/pkg/client/clientset/versioned/typed/channels/v1alpha1/fake/fake_channels_client.go b/pkg/client/clientset/versioned/typed/channels/v1alpha1/fake/fake_channels_client.go deleted file mode 100644 index 3c498bd6dcb..00000000000 --- a/pkg/client/clientset/versioned/typed/channels/v1alpha1/fake/fake_channels_client.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/knative/eventing/pkg/client/clientset/versioned/typed/channels/v1alpha1" - rest "k8s.io/client-go/rest" - testing "k8s.io/client-go/testing" -) - -type FakeChannelsV1alpha1 struct { - *testing.Fake -} - -func (c *FakeChannelsV1alpha1) Buses(namespace string) v1alpha1.BusInterface { - return &FakeBuses{c, namespace} -} - -func (c *FakeChannelsV1alpha1) Channels(namespace string) v1alpha1.ChannelInterface { - return &FakeChannels{c, namespace} -} - -func (c *FakeChannelsV1alpha1) ClusterBuses() v1alpha1.ClusterBusInterface { - return &FakeClusterBuses{c} -} - -func (c *FakeChannelsV1alpha1) Subscriptions(namespace string) v1alpha1.SubscriptionInterface { - return &FakeSubscriptions{c, namespace} -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *FakeChannelsV1alpha1) RESTClient() rest.Interface { - var ret *rest.RESTClient - return ret -} diff --git a/pkg/client/clientset/versioned/typed/channels/v1alpha1/fake/fake_clusterbus.go b/pkg/client/clientset/versioned/typed/channels/v1alpha1/fake/fake_clusterbus.go deleted file mode 100644 index 82f4f9dc6d4..00000000000 --- a/pkg/client/clientset/versioned/typed/channels/v1alpha1/fake/fake_clusterbus.go +++ /dev/null @@ -1,120 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeClusterBuses implements ClusterBusInterface -type FakeClusterBuses struct { - Fake *FakeChannelsV1alpha1 -} - -var clusterbusesResource = schema.GroupVersionResource{Group: "channels.knative.dev", Version: "v1alpha1", Resource: "clusterbuses"} - -var clusterbusesKind = schema.GroupVersionKind{Group: "channels.knative.dev", Version: "v1alpha1", Kind: "ClusterBus"} - -// Get takes name of the clusterBus, and returns the corresponding clusterBus object, and an error if there is any. -func (c *FakeClusterBuses) Get(name string, options v1.GetOptions) (result *v1alpha1.ClusterBus, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootGetAction(clusterbusesResource, name), &v1alpha1.ClusterBus{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterBus), err -} - -// List takes label and field selectors, and returns the list of ClusterBuses that match those selectors. -func (c *FakeClusterBuses) List(opts v1.ListOptions) (result *v1alpha1.ClusterBusList, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootListAction(clusterbusesResource, clusterbusesKind, opts), &v1alpha1.ClusterBusList{}) - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.ClusterBusList{ListMeta: obj.(*v1alpha1.ClusterBusList).ListMeta} - for _, item := range obj.(*v1alpha1.ClusterBusList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested clusterBuses. -func (c *FakeClusterBuses) Watch(opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewRootWatchAction(clusterbusesResource, opts)) -} - -// Create takes the representation of a clusterBus and creates it. Returns the server's representation of the clusterBus, and an error, if there is any. -func (c *FakeClusterBuses) Create(clusterBus *v1alpha1.ClusterBus) (result *v1alpha1.ClusterBus, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootCreateAction(clusterbusesResource, clusterBus), &v1alpha1.ClusterBus{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterBus), err -} - -// Update takes the representation of a clusterBus and updates it. Returns the server's representation of the clusterBus, and an error, if there is any. -func (c *FakeClusterBuses) Update(clusterBus *v1alpha1.ClusterBus) (result *v1alpha1.ClusterBus, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootUpdateAction(clusterbusesResource, clusterBus), &v1alpha1.ClusterBus{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterBus), err -} - -// Delete takes name of the clusterBus and deletes it. Returns an error if one occurs. -func (c *FakeClusterBuses) Delete(name string, options *v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewRootDeleteAction(clusterbusesResource, name), &v1alpha1.ClusterBus{}) - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeClusterBuses) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - action := testing.NewRootDeleteCollectionAction(clusterbusesResource, listOptions) - - _, err := c.Fake.Invokes(action, &v1alpha1.ClusterBusList{}) - return err -} - -// Patch applies the patch and returns the patched clusterBus. -func (c *FakeClusterBuses) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterBus, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootPatchSubresourceAction(clusterbusesResource, name, data, subresources...), &v1alpha1.ClusterBus{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterBus), err -} diff --git a/pkg/client/clientset/versioned/typed/channels/v1alpha1/fake/fake_subscription.go b/pkg/client/clientset/versioned/typed/channels/v1alpha1/fake/fake_subscription.go deleted file mode 100644 index b3fdebf5308..00000000000 --- a/pkg/client/clientset/versioned/typed/channels/v1alpha1/fake/fake_subscription.go +++ /dev/null @@ -1,128 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeSubscriptions implements SubscriptionInterface -type FakeSubscriptions struct { - Fake *FakeChannelsV1alpha1 - ns string -} - -var subscriptionsResource = schema.GroupVersionResource{Group: "channels.knative.dev", Version: "v1alpha1", Resource: "subscriptions"} - -var subscriptionsKind = schema.GroupVersionKind{Group: "channels.knative.dev", Version: "v1alpha1", Kind: "Subscription"} - -// Get takes name of the subscription, and returns the corresponding subscription object, and an error if there is any. -func (c *FakeSubscriptions) Get(name string, options v1.GetOptions) (result *v1alpha1.Subscription, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(subscriptionsResource, c.ns, name), &v1alpha1.Subscription{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Subscription), err -} - -// List takes label and field selectors, and returns the list of Subscriptions that match those selectors. -func (c *FakeSubscriptions) List(opts v1.ListOptions) (result *v1alpha1.SubscriptionList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(subscriptionsResource, subscriptionsKind, c.ns, opts), &v1alpha1.SubscriptionList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.SubscriptionList{ListMeta: obj.(*v1alpha1.SubscriptionList).ListMeta} - for _, item := range obj.(*v1alpha1.SubscriptionList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested subscriptions. -func (c *FakeSubscriptions) Watch(opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(subscriptionsResource, c.ns, opts)) - -} - -// Create takes the representation of a subscription and creates it. Returns the server's representation of the subscription, and an error, if there is any. -func (c *FakeSubscriptions) Create(subscription *v1alpha1.Subscription) (result *v1alpha1.Subscription, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(subscriptionsResource, c.ns, subscription), &v1alpha1.Subscription{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Subscription), err -} - -// Update takes the representation of a subscription and updates it. Returns the server's representation of the subscription, and an error, if there is any. -func (c *FakeSubscriptions) Update(subscription *v1alpha1.Subscription) (result *v1alpha1.Subscription, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(subscriptionsResource, c.ns, subscription), &v1alpha1.Subscription{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Subscription), err -} - -// Delete takes name of the subscription and deletes it. Returns an error if one occurs. -func (c *FakeSubscriptions) Delete(name string, options *v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteAction(subscriptionsResource, c.ns, name), &v1alpha1.Subscription{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeSubscriptions) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(subscriptionsResource, c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &v1alpha1.SubscriptionList{}) - return err -} - -// Patch applies the patch and returns the patched subscription. -func (c *FakeSubscriptions) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Subscription, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(subscriptionsResource, c.ns, name, data, subresources...), &v1alpha1.Subscription{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Subscription), err -} diff --git a/pkg/client/clientset/versioned/typed/channels/v1alpha1/generated_expansion.go b/pkg/client/clientset/versioned/typed/channels/v1alpha1/generated_expansion.go deleted file mode 100644 index 8979577193d..00000000000 --- a/pkg/client/clientset/versioned/typed/channels/v1alpha1/generated_expansion.go +++ /dev/null @@ -1,27 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -type BusExpansion interface{} - -type ChannelExpansion interface{} - -type ClusterBusExpansion interface{} - -type SubscriptionExpansion interface{} diff --git a/pkg/client/clientset/versioned/typed/channels/v1alpha1/subscription.go b/pkg/client/clientset/versioned/typed/channels/v1alpha1/subscription.go deleted file mode 100644 index c91104a08ea..00000000000 --- a/pkg/client/clientset/versioned/typed/channels/v1alpha1/subscription.go +++ /dev/null @@ -1,157 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - scheme "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// SubscriptionsGetter has a method to return a SubscriptionInterface. -// A group's client should implement this interface. -type SubscriptionsGetter interface { - Subscriptions(namespace string) SubscriptionInterface -} - -// SubscriptionInterface has methods to work with Subscription resources. -type SubscriptionInterface interface { - Create(*v1alpha1.Subscription) (*v1alpha1.Subscription, error) - Update(*v1alpha1.Subscription) (*v1alpha1.Subscription, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.Subscription, error) - List(opts v1.ListOptions) (*v1alpha1.SubscriptionList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Subscription, err error) - SubscriptionExpansion -} - -// subscriptions implements SubscriptionInterface -type subscriptions struct { - client rest.Interface - ns string -} - -// newSubscriptions returns a Subscriptions -func newSubscriptions(c *ChannelsV1alpha1Client, namespace string) *subscriptions { - return &subscriptions{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the subscription, and returns the corresponding subscription object, and an error if there is any. -func (c *subscriptions) Get(name string, options v1.GetOptions) (result *v1alpha1.Subscription, err error) { - result = &v1alpha1.Subscription{} - err = c.client.Get(). - Namespace(c.ns). - Resource("subscriptions"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of Subscriptions that match those selectors. -func (c *subscriptions) List(opts v1.ListOptions) (result *v1alpha1.SubscriptionList, err error) { - result = &v1alpha1.SubscriptionList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("subscriptions"). - VersionedParams(&opts, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested subscriptions. -func (c *subscriptions) Watch(opts v1.ListOptions) (watch.Interface, error) { - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("subscriptions"). - VersionedParams(&opts, scheme.ParameterCodec). - Watch() -} - -// Create takes the representation of a subscription and creates it. Returns the server's representation of the subscription, and an error, if there is any. -func (c *subscriptions) Create(subscription *v1alpha1.Subscription) (result *v1alpha1.Subscription, err error) { - result = &v1alpha1.Subscription{} - err = c.client.Post(). - Namespace(c.ns). - Resource("subscriptions"). - Body(subscription). - Do(). - Into(result) - return -} - -// Update takes the representation of a subscription and updates it. Returns the server's representation of the subscription, and an error, if there is any. -func (c *subscriptions) Update(subscription *v1alpha1.Subscription) (result *v1alpha1.Subscription, err error) { - result = &v1alpha1.Subscription{} - err = c.client.Put(). - Namespace(c.ns). - Resource("subscriptions"). - Name(subscription.Name). - Body(subscription). - Do(). - Into(result) - return -} - -// Delete takes name of the subscription and deletes it. Returns an error if one occurs. -func (c *subscriptions) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("subscriptions"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *subscriptions) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("subscriptions"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched subscription. -func (c *subscriptions) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Subscription, err error) { - result = &v1alpha1.Subscription{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("subscriptions"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/pkg/client/clientset/versioned/typed/eventing/v1alpha1/clusterchannelprovisioner.go b/pkg/client/clientset/versioned/typed/eventing/v1alpha1/clusterchannelprovisioner.go new file mode 100644 index 00000000000..951b0f919eb --- /dev/null +++ b/pkg/client/clientset/versioned/typed/eventing/v1alpha1/clusterchannelprovisioner.go @@ -0,0 +1,147 @@ +/* +Copyright 2018 The Knative 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. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + v1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + scheme "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" +) + +// ClusterChannelProvisionersGetter has a method to return a ClusterChannelProvisionerInterface. +// A group's client should implement this interface. +type ClusterChannelProvisionersGetter interface { + ClusterChannelProvisioners() ClusterChannelProvisionerInterface +} + +// ClusterChannelProvisionerInterface has methods to work with ClusterChannelProvisioner resources. +type ClusterChannelProvisionerInterface interface { + Create(*v1alpha1.ClusterChannelProvisioner) (*v1alpha1.ClusterChannelProvisioner, error) + Update(*v1alpha1.ClusterChannelProvisioner) (*v1alpha1.ClusterChannelProvisioner, error) + Delete(name string, options *v1.DeleteOptions) error + DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error + Get(name string, options v1.GetOptions) (*v1alpha1.ClusterChannelProvisioner, error) + List(opts v1.ListOptions) (*v1alpha1.ClusterChannelProvisionerList, error) + Watch(opts v1.ListOptions) (watch.Interface, error) + Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterChannelProvisioner, err error) + ClusterChannelProvisionerExpansion +} + +// clusterChannelProvisioners implements ClusterChannelProvisionerInterface +type clusterChannelProvisioners struct { + client rest.Interface +} + +// newClusterChannelProvisioners returns a ClusterChannelProvisioners +func newClusterChannelProvisioners(c *EventingV1alpha1Client) *clusterChannelProvisioners { + return &clusterChannelProvisioners{ + client: c.RESTClient(), + } +} + +// Get takes name of the clusterChannelProvisioner, and returns the corresponding clusterChannelProvisioner object, and an error if there is any. +func (c *clusterChannelProvisioners) Get(name string, options v1.GetOptions) (result *v1alpha1.ClusterChannelProvisioner, err error) { + result = &v1alpha1.ClusterChannelProvisioner{} + err = c.client.Get(). + Resource("clusterchannelprovisioners"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of ClusterChannelProvisioners that match those selectors. +func (c *clusterChannelProvisioners) List(opts v1.ListOptions) (result *v1alpha1.ClusterChannelProvisionerList, err error) { + result = &v1alpha1.ClusterChannelProvisionerList{} + err = c.client.Get(). + Resource("clusterchannelprovisioners"). + VersionedParams(&opts, scheme.ParameterCodec). + Do(). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested clusterChannelProvisioners. +func (c *clusterChannelProvisioners) Watch(opts v1.ListOptions) (watch.Interface, error) { + opts.Watch = true + return c.client.Get(). + Resource("clusterchannelprovisioners"). + VersionedParams(&opts, scheme.ParameterCodec). + Watch() +} + +// Create takes the representation of a clusterChannelProvisioner and creates it. Returns the server's representation of the clusterChannelProvisioner, and an error, if there is any. +func (c *clusterChannelProvisioners) Create(clusterChannelProvisioner *v1alpha1.ClusterChannelProvisioner) (result *v1alpha1.ClusterChannelProvisioner, err error) { + result = &v1alpha1.ClusterChannelProvisioner{} + err = c.client.Post(). + Resource("clusterchannelprovisioners"). + Body(clusterChannelProvisioner). + Do(). + Into(result) + return +} + +// Update takes the representation of a clusterChannelProvisioner and updates it. Returns the server's representation of the clusterChannelProvisioner, and an error, if there is any. +func (c *clusterChannelProvisioners) Update(clusterChannelProvisioner *v1alpha1.ClusterChannelProvisioner) (result *v1alpha1.ClusterChannelProvisioner, err error) { + result = &v1alpha1.ClusterChannelProvisioner{} + err = c.client.Put(). + Resource("clusterchannelprovisioners"). + Name(clusterChannelProvisioner.Name). + Body(clusterChannelProvisioner). + Do(). + Into(result) + return +} + +// Delete takes name of the clusterChannelProvisioner and deletes it. Returns an error if one occurs. +func (c *clusterChannelProvisioners) Delete(name string, options *v1.DeleteOptions) error { + return c.client.Delete(). + Resource("clusterchannelprovisioners"). + Name(name). + Body(options). + Do(). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *clusterChannelProvisioners) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + return c.client.Delete(). + Resource("clusterchannelprovisioners"). + VersionedParams(&listOptions, scheme.ParameterCodec). + Body(options). + Do(). + Error() +} + +// Patch applies the patch and returns the patched clusterChannelProvisioner. +func (c *clusterChannelProvisioners) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterChannelProvisioner, err error) { + result = &v1alpha1.ClusterChannelProvisioner{} + err = c.client.Patch(pt). + Resource("clusterchannelprovisioners"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/pkg/client/clientset/versioned/typed/eventing/v1alpha1/clusterprovisioner.go b/pkg/client/clientset/versioned/typed/eventing/v1alpha1/clusterprovisioner.go deleted file mode 100644 index 9b61e6c9073..00000000000 --- a/pkg/client/clientset/versioned/typed/eventing/v1alpha1/clusterprovisioner.go +++ /dev/null @@ -1,147 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" - scheme "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// ClusterProvisionersGetter has a method to return a ClusterProvisionerInterface. -// A group's client should implement this interface. -type ClusterProvisionersGetter interface { - ClusterProvisioners() ClusterProvisionerInterface -} - -// ClusterProvisionerInterface has methods to work with ClusterProvisioner resources. -type ClusterProvisionerInterface interface { - Create(*v1alpha1.ClusterProvisioner) (*v1alpha1.ClusterProvisioner, error) - Update(*v1alpha1.ClusterProvisioner) (*v1alpha1.ClusterProvisioner, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.ClusterProvisioner, error) - List(opts v1.ListOptions) (*v1alpha1.ClusterProvisionerList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterProvisioner, err error) - ClusterProvisionerExpansion -} - -// clusterProvisioners implements ClusterProvisionerInterface -type clusterProvisioners struct { - client rest.Interface -} - -// newClusterProvisioners returns a ClusterProvisioners -func newClusterProvisioners(c *EventingV1alpha1Client) *clusterProvisioners { - return &clusterProvisioners{ - client: c.RESTClient(), - } -} - -// Get takes name of the clusterProvisioner, and returns the corresponding clusterProvisioner object, and an error if there is any. -func (c *clusterProvisioners) Get(name string, options v1.GetOptions) (result *v1alpha1.ClusterProvisioner, err error) { - result = &v1alpha1.ClusterProvisioner{} - err = c.client.Get(). - Resource("clusterprovisioners"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of ClusterProvisioners that match those selectors. -func (c *clusterProvisioners) List(opts v1.ListOptions) (result *v1alpha1.ClusterProvisionerList, err error) { - result = &v1alpha1.ClusterProvisionerList{} - err = c.client.Get(). - Resource("clusterprovisioners"). - VersionedParams(&opts, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested clusterProvisioners. -func (c *clusterProvisioners) Watch(opts v1.ListOptions) (watch.Interface, error) { - opts.Watch = true - return c.client.Get(). - Resource("clusterprovisioners"). - VersionedParams(&opts, scheme.ParameterCodec). - Watch() -} - -// Create takes the representation of a clusterProvisioner and creates it. Returns the server's representation of the clusterProvisioner, and an error, if there is any. -func (c *clusterProvisioners) Create(clusterProvisioner *v1alpha1.ClusterProvisioner) (result *v1alpha1.ClusterProvisioner, err error) { - result = &v1alpha1.ClusterProvisioner{} - err = c.client.Post(). - Resource("clusterprovisioners"). - Body(clusterProvisioner). - Do(). - Into(result) - return -} - -// Update takes the representation of a clusterProvisioner and updates it. Returns the server's representation of the clusterProvisioner, and an error, if there is any. -func (c *clusterProvisioners) Update(clusterProvisioner *v1alpha1.ClusterProvisioner) (result *v1alpha1.ClusterProvisioner, err error) { - result = &v1alpha1.ClusterProvisioner{} - err = c.client.Put(). - Resource("clusterprovisioners"). - Name(clusterProvisioner.Name). - Body(clusterProvisioner). - Do(). - Into(result) - return -} - -// Delete takes name of the clusterProvisioner and deletes it. Returns an error if one occurs. -func (c *clusterProvisioners) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Resource("clusterprovisioners"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *clusterProvisioners) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - return c.client.Delete(). - Resource("clusterprovisioners"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched clusterProvisioner. -func (c *clusterProvisioners) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterProvisioner, err error) { - result = &v1alpha1.ClusterProvisioner{} - err = c.client.Patch(pt). - Resource("clusterprovisioners"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/pkg/client/clientset/versioned/typed/eventing/v1alpha1/eventing_client.go b/pkg/client/clientset/versioned/typed/eventing/v1alpha1/eventing_client.go index c9474ed0042..ef337f70bf0 100644 --- a/pkg/client/clientset/versioned/typed/eventing/v1alpha1/eventing_client.go +++ b/pkg/client/clientset/versioned/typed/eventing/v1alpha1/eventing_client.go @@ -28,8 +28,7 @@ import ( type EventingV1alpha1Interface interface { RESTClient() rest.Interface ChannelsGetter - ClusterProvisionersGetter - SourcesGetter + ClusterChannelProvisionersGetter SubscriptionsGetter } @@ -42,12 +41,8 @@ func (c *EventingV1alpha1Client) Channels(namespace string) ChannelInterface { return newChannels(c, namespace) } -func (c *EventingV1alpha1Client) ClusterProvisioners() ClusterProvisionerInterface { - return newClusterProvisioners(c) -} - -func (c *EventingV1alpha1Client) Sources(namespace string) SourceInterface { - return newSources(c, namespace) +func (c *EventingV1alpha1Client) ClusterChannelProvisioners() ClusterChannelProvisionerInterface { + return newClusterChannelProvisioners(c) } func (c *EventingV1alpha1Client) Subscriptions(namespace string) SubscriptionInterface { diff --git a/pkg/client/clientset/versioned/typed/eventing/v1alpha1/fake/fake_clusterchannelprovisioner.go b/pkg/client/clientset/versioned/typed/eventing/v1alpha1/fake/fake_clusterchannelprovisioner.go new file mode 100644 index 00000000000..785d0af0b42 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/eventing/v1alpha1/fake/fake_clusterchannelprovisioner.go @@ -0,0 +1,120 @@ +/* +Copyright 2018 The Knative 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. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + v1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + schema "k8s.io/apimachinery/pkg/runtime/schema" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + testing "k8s.io/client-go/testing" +) + +// FakeClusterChannelProvisioners implements ClusterChannelProvisionerInterface +type FakeClusterChannelProvisioners struct { + Fake *FakeEventingV1alpha1 +} + +var clusterchannelprovisionersResource = schema.GroupVersionResource{Group: "eventing.knative.dev", Version: "v1alpha1", Resource: "clusterchannelprovisioners"} + +var clusterchannelprovisionersKind = schema.GroupVersionKind{Group: "eventing.knative.dev", Version: "v1alpha1", Kind: "ClusterChannelProvisioner"} + +// Get takes name of the clusterChannelProvisioner, and returns the corresponding clusterChannelProvisioner object, and an error if there is any. +func (c *FakeClusterChannelProvisioners) Get(name string, options v1.GetOptions) (result *v1alpha1.ClusterChannelProvisioner, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootGetAction(clusterchannelprovisionersResource, name), &v1alpha1.ClusterChannelProvisioner{}) + if obj == nil { + return nil, err + } + return obj.(*v1alpha1.ClusterChannelProvisioner), err +} + +// List takes label and field selectors, and returns the list of ClusterChannelProvisioners that match those selectors. +func (c *FakeClusterChannelProvisioners) List(opts v1.ListOptions) (result *v1alpha1.ClusterChannelProvisionerList, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootListAction(clusterchannelprovisionersResource, clusterchannelprovisionersKind, opts), &v1alpha1.ClusterChannelProvisionerList{}) + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &v1alpha1.ClusterChannelProvisionerList{ListMeta: obj.(*v1alpha1.ClusterChannelProvisionerList).ListMeta} + for _, item := range obj.(*v1alpha1.ClusterChannelProvisionerList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested clusterChannelProvisioners. +func (c *FakeClusterChannelProvisioners) Watch(opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewRootWatchAction(clusterchannelprovisionersResource, opts)) +} + +// Create takes the representation of a clusterChannelProvisioner and creates it. Returns the server's representation of the clusterChannelProvisioner, and an error, if there is any. +func (c *FakeClusterChannelProvisioners) Create(clusterChannelProvisioner *v1alpha1.ClusterChannelProvisioner) (result *v1alpha1.ClusterChannelProvisioner, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootCreateAction(clusterchannelprovisionersResource, clusterChannelProvisioner), &v1alpha1.ClusterChannelProvisioner{}) + if obj == nil { + return nil, err + } + return obj.(*v1alpha1.ClusterChannelProvisioner), err +} + +// Update takes the representation of a clusterChannelProvisioner and updates it. Returns the server's representation of the clusterChannelProvisioner, and an error, if there is any. +func (c *FakeClusterChannelProvisioners) Update(clusterChannelProvisioner *v1alpha1.ClusterChannelProvisioner) (result *v1alpha1.ClusterChannelProvisioner, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootUpdateAction(clusterchannelprovisionersResource, clusterChannelProvisioner), &v1alpha1.ClusterChannelProvisioner{}) + if obj == nil { + return nil, err + } + return obj.(*v1alpha1.ClusterChannelProvisioner), err +} + +// Delete takes name of the clusterChannelProvisioner and deletes it. Returns an error if one occurs. +func (c *FakeClusterChannelProvisioners) Delete(name string, options *v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewRootDeleteAction(clusterchannelprovisionersResource, name), &v1alpha1.ClusterChannelProvisioner{}) + return err +} + +// DeleteCollection deletes a collection of objects. +func (c *FakeClusterChannelProvisioners) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + action := testing.NewRootDeleteCollectionAction(clusterchannelprovisionersResource, listOptions) + + _, err := c.Fake.Invokes(action, &v1alpha1.ClusterChannelProvisionerList{}) + return err +} + +// Patch applies the patch and returns the patched clusterChannelProvisioner. +func (c *FakeClusterChannelProvisioners) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterChannelProvisioner, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootPatchSubresourceAction(clusterchannelprovisionersResource, name, data, subresources...), &v1alpha1.ClusterChannelProvisioner{}) + if obj == nil { + return nil, err + } + return obj.(*v1alpha1.ClusterChannelProvisioner), err +} diff --git a/pkg/client/clientset/versioned/typed/eventing/v1alpha1/fake/fake_clusterprovisioner.go b/pkg/client/clientset/versioned/typed/eventing/v1alpha1/fake/fake_clusterprovisioner.go deleted file mode 100644 index ce5b93f76ce..00000000000 --- a/pkg/client/clientset/versioned/typed/eventing/v1alpha1/fake/fake_clusterprovisioner.go +++ /dev/null @@ -1,120 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeClusterProvisioners implements ClusterProvisionerInterface -type FakeClusterProvisioners struct { - Fake *FakeEventingV1alpha1 -} - -var clusterprovisionersResource = schema.GroupVersionResource{Group: "eventing.knative.dev", Version: "v1alpha1", Resource: "clusterprovisioners"} - -var clusterprovisionersKind = schema.GroupVersionKind{Group: "eventing.knative.dev", Version: "v1alpha1", Kind: "ClusterProvisioner"} - -// Get takes name of the clusterProvisioner, and returns the corresponding clusterProvisioner object, and an error if there is any. -func (c *FakeClusterProvisioners) Get(name string, options v1.GetOptions) (result *v1alpha1.ClusterProvisioner, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootGetAction(clusterprovisionersResource, name), &v1alpha1.ClusterProvisioner{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterProvisioner), err -} - -// List takes label and field selectors, and returns the list of ClusterProvisioners that match those selectors. -func (c *FakeClusterProvisioners) List(opts v1.ListOptions) (result *v1alpha1.ClusterProvisionerList, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootListAction(clusterprovisionersResource, clusterprovisionersKind, opts), &v1alpha1.ClusterProvisionerList{}) - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.ClusterProvisionerList{ListMeta: obj.(*v1alpha1.ClusterProvisionerList).ListMeta} - for _, item := range obj.(*v1alpha1.ClusterProvisionerList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested clusterProvisioners. -func (c *FakeClusterProvisioners) Watch(opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewRootWatchAction(clusterprovisionersResource, opts)) -} - -// Create takes the representation of a clusterProvisioner and creates it. Returns the server's representation of the clusterProvisioner, and an error, if there is any. -func (c *FakeClusterProvisioners) Create(clusterProvisioner *v1alpha1.ClusterProvisioner) (result *v1alpha1.ClusterProvisioner, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootCreateAction(clusterprovisionersResource, clusterProvisioner), &v1alpha1.ClusterProvisioner{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterProvisioner), err -} - -// Update takes the representation of a clusterProvisioner and updates it. Returns the server's representation of the clusterProvisioner, and an error, if there is any. -func (c *FakeClusterProvisioners) Update(clusterProvisioner *v1alpha1.ClusterProvisioner) (result *v1alpha1.ClusterProvisioner, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootUpdateAction(clusterprovisionersResource, clusterProvisioner), &v1alpha1.ClusterProvisioner{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterProvisioner), err -} - -// Delete takes name of the clusterProvisioner and deletes it. Returns an error if one occurs. -func (c *FakeClusterProvisioners) Delete(name string, options *v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewRootDeleteAction(clusterprovisionersResource, name), &v1alpha1.ClusterProvisioner{}) - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeClusterProvisioners) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - action := testing.NewRootDeleteCollectionAction(clusterprovisionersResource, listOptions) - - _, err := c.Fake.Invokes(action, &v1alpha1.ClusterProvisionerList{}) - return err -} - -// Patch applies the patch and returns the patched clusterProvisioner. -func (c *FakeClusterProvisioners) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterProvisioner, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootPatchSubresourceAction(clusterprovisionersResource, name, data, subresources...), &v1alpha1.ClusterProvisioner{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterProvisioner), err -} diff --git a/pkg/client/clientset/versioned/typed/eventing/v1alpha1/fake/fake_eventing_client.go b/pkg/client/clientset/versioned/typed/eventing/v1alpha1/fake/fake_eventing_client.go index dfd67eea8b1..0080c07b8d4 100644 --- a/pkg/client/clientset/versioned/typed/eventing/v1alpha1/fake/fake_eventing_client.go +++ b/pkg/client/clientset/versioned/typed/eventing/v1alpha1/fake/fake_eventing_client.go @@ -32,12 +32,8 @@ func (c *FakeEventingV1alpha1) Channels(namespace string) v1alpha1.ChannelInterf return &FakeChannels{c, namespace} } -func (c *FakeEventingV1alpha1) ClusterProvisioners() v1alpha1.ClusterProvisionerInterface { - return &FakeClusterProvisioners{c} -} - -func (c *FakeEventingV1alpha1) Sources(namespace string) v1alpha1.SourceInterface { - return &FakeSources{c, namespace} +func (c *FakeEventingV1alpha1) ClusterChannelProvisioners() v1alpha1.ClusterChannelProvisionerInterface { + return &FakeClusterChannelProvisioners{c} } func (c *FakeEventingV1alpha1) Subscriptions(namespace string) v1alpha1.SubscriptionInterface { diff --git a/pkg/client/clientset/versioned/typed/eventing/v1alpha1/fake/fake_source.go b/pkg/client/clientset/versioned/typed/eventing/v1alpha1/fake/fake_source.go deleted file mode 100644 index 7fa9395eaa4..00000000000 --- a/pkg/client/clientset/versioned/typed/eventing/v1alpha1/fake/fake_source.go +++ /dev/null @@ -1,128 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeSources implements SourceInterface -type FakeSources struct { - Fake *FakeEventingV1alpha1 - ns string -} - -var sourcesResource = schema.GroupVersionResource{Group: "eventing.knative.dev", Version: "v1alpha1", Resource: "sources"} - -var sourcesKind = schema.GroupVersionKind{Group: "eventing.knative.dev", Version: "v1alpha1", Kind: "Source"} - -// Get takes name of the source, and returns the corresponding source object, and an error if there is any. -func (c *FakeSources) Get(name string, options v1.GetOptions) (result *v1alpha1.Source, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(sourcesResource, c.ns, name), &v1alpha1.Source{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Source), err -} - -// List takes label and field selectors, and returns the list of Sources that match those selectors. -func (c *FakeSources) List(opts v1.ListOptions) (result *v1alpha1.SourceList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(sourcesResource, sourcesKind, c.ns, opts), &v1alpha1.SourceList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.SourceList{ListMeta: obj.(*v1alpha1.SourceList).ListMeta} - for _, item := range obj.(*v1alpha1.SourceList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested sources. -func (c *FakeSources) Watch(opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(sourcesResource, c.ns, opts)) - -} - -// Create takes the representation of a source and creates it. Returns the server's representation of the source, and an error, if there is any. -func (c *FakeSources) Create(source *v1alpha1.Source) (result *v1alpha1.Source, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(sourcesResource, c.ns, source), &v1alpha1.Source{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Source), err -} - -// Update takes the representation of a source and updates it. Returns the server's representation of the source, and an error, if there is any. -func (c *FakeSources) Update(source *v1alpha1.Source) (result *v1alpha1.Source, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(sourcesResource, c.ns, source), &v1alpha1.Source{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Source), err -} - -// Delete takes name of the source and deletes it. Returns an error if one occurs. -func (c *FakeSources) Delete(name string, options *v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteAction(sourcesResource, c.ns, name), &v1alpha1.Source{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeSources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(sourcesResource, c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &v1alpha1.SourceList{}) - return err -} - -// Patch applies the patch and returns the patched source. -func (c *FakeSources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Source, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(sourcesResource, c.ns, name, data, subresources...), &v1alpha1.Source{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Source), err -} diff --git a/pkg/client/clientset/versioned/typed/eventing/v1alpha1/generated_expansion.go b/pkg/client/clientset/versioned/typed/eventing/v1alpha1/generated_expansion.go index 121200ef9f9..fcef70e765c 100644 --- a/pkg/client/clientset/versioned/typed/eventing/v1alpha1/generated_expansion.go +++ b/pkg/client/clientset/versioned/typed/eventing/v1alpha1/generated_expansion.go @@ -20,8 +20,6 @@ package v1alpha1 type ChannelExpansion interface{} -type ClusterProvisionerExpansion interface{} - -type SourceExpansion interface{} +type ClusterChannelProvisionerExpansion interface{} type SubscriptionExpansion interface{} diff --git a/pkg/client/clientset/versioned/typed/eventing/v1alpha1/source.go b/pkg/client/clientset/versioned/typed/eventing/v1alpha1/source.go deleted file mode 100644 index f0a4a8a74f7..00000000000 --- a/pkg/client/clientset/versioned/typed/eventing/v1alpha1/source.go +++ /dev/null @@ -1,157 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" - scheme "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// SourcesGetter has a method to return a SourceInterface. -// A group's client should implement this interface. -type SourcesGetter interface { - Sources(namespace string) SourceInterface -} - -// SourceInterface has methods to work with Source resources. -type SourceInterface interface { - Create(*v1alpha1.Source) (*v1alpha1.Source, error) - Update(*v1alpha1.Source) (*v1alpha1.Source, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.Source, error) - List(opts v1.ListOptions) (*v1alpha1.SourceList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Source, err error) - SourceExpansion -} - -// sources implements SourceInterface -type sources struct { - client rest.Interface - ns string -} - -// newSources returns a Sources -func newSources(c *EventingV1alpha1Client, namespace string) *sources { - return &sources{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the source, and returns the corresponding source object, and an error if there is any. -func (c *sources) Get(name string, options v1.GetOptions) (result *v1alpha1.Source, err error) { - result = &v1alpha1.Source{} - err = c.client.Get(). - Namespace(c.ns). - Resource("sources"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of Sources that match those selectors. -func (c *sources) List(opts v1.ListOptions) (result *v1alpha1.SourceList, err error) { - result = &v1alpha1.SourceList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("sources"). - VersionedParams(&opts, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested sources. -func (c *sources) Watch(opts v1.ListOptions) (watch.Interface, error) { - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("sources"). - VersionedParams(&opts, scheme.ParameterCodec). - Watch() -} - -// Create takes the representation of a source and creates it. Returns the server's representation of the source, and an error, if there is any. -func (c *sources) Create(source *v1alpha1.Source) (result *v1alpha1.Source, err error) { - result = &v1alpha1.Source{} - err = c.client.Post(). - Namespace(c.ns). - Resource("sources"). - Body(source). - Do(). - Into(result) - return -} - -// Update takes the representation of a source and updates it. Returns the server's representation of the source, and an error, if there is any. -func (c *sources) Update(source *v1alpha1.Source) (result *v1alpha1.Source, err error) { - result = &v1alpha1.Source{} - err = c.client.Put(). - Namespace(c.ns). - Resource("sources"). - Name(source.Name). - Body(source). - Do(). - Into(result) - return -} - -// Delete takes name of the source and deletes it. Returns an error if one occurs. -func (c *sources) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("sources"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *sources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("sources"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched source. -func (c *sources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Source, err error) { - result = &v1alpha1.Source{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("sources"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/clustereventsource.go b/pkg/client/clientset/versioned/typed/feeds/v1alpha1/clustereventsource.go deleted file mode 100644 index 45328f1dd72..00000000000 --- a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/clustereventsource.go +++ /dev/null @@ -1,163 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - scheme "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// ClusterEventSourcesGetter has a method to return a ClusterEventSourceInterface. -// A group's client should implement this interface. -type ClusterEventSourcesGetter interface { - ClusterEventSources() ClusterEventSourceInterface -} - -// ClusterEventSourceInterface has methods to work with ClusterEventSource resources. -type ClusterEventSourceInterface interface { - Create(*v1alpha1.ClusterEventSource) (*v1alpha1.ClusterEventSource, error) - Update(*v1alpha1.ClusterEventSource) (*v1alpha1.ClusterEventSource, error) - UpdateStatus(*v1alpha1.ClusterEventSource) (*v1alpha1.ClusterEventSource, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.ClusterEventSource, error) - List(opts v1.ListOptions) (*v1alpha1.ClusterEventSourceList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterEventSource, err error) - ClusterEventSourceExpansion -} - -// clusterEventSources implements ClusterEventSourceInterface -type clusterEventSources struct { - client rest.Interface -} - -// newClusterEventSources returns a ClusterEventSources -func newClusterEventSources(c *FeedsV1alpha1Client) *clusterEventSources { - return &clusterEventSources{ - client: c.RESTClient(), - } -} - -// Get takes name of the clusterEventSource, and returns the corresponding clusterEventSource object, and an error if there is any. -func (c *clusterEventSources) Get(name string, options v1.GetOptions) (result *v1alpha1.ClusterEventSource, err error) { - result = &v1alpha1.ClusterEventSource{} - err = c.client.Get(). - Resource("clustereventsources"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of ClusterEventSources that match those selectors. -func (c *clusterEventSources) List(opts v1.ListOptions) (result *v1alpha1.ClusterEventSourceList, err error) { - result = &v1alpha1.ClusterEventSourceList{} - err = c.client.Get(). - Resource("clustereventsources"). - VersionedParams(&opts, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested clusterEventSources. -func (c *clusterEventSources) Watch(opts v1.ListOptions) (watch.Interface, error) { - opts.Watch = true - return c.client.Get(). - Resource("clustereventsources"). - VersionedParams(&opts, scheme.ParameterCodec). - Watch() -} - -// Create takes the representation of a clusterEventSource and creates it. Returns the server's representation of the clusterEventSource, and an error, if there is any. -func (c *clusterEventSources) Create(clusterEventSource *v1alpha1.ClusterEventSource) (result *v1alpha1.ClusterEventSource, err error) { - result = &v1alpha1.ClusterEventSource{} - err = c.client.Post(). - Resource("clustereventsources"). - Body(clusterEventSource). - Do(). - Into(result) - return -} - -// Update takes the representation of a clusterEventSource and updates it. Returns the server's representation of the clusterEventSource, and an error, if there is any. -func (c *clusterEventSources) Update(clusterEventSource *v1alpha1.ClusterEventSource) (result *v1alpha1.ClusterEventSource, err error) { - result = &v1alpha1.ClusterEventSource{} - err = c.client.Put(). - Resource("clustereventsources"). - Name(clusterEventSource.Name). - Body(clusterEventSource). - Do(). - Into(result) - return -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - -func (c *clusterEventSources) UpdateStatus(clusterEventSource *v1alpha1.ClusterEventSource) (result *v1alpha1.ClusterEventSource, err error) { - result = &v1alpha1.ClusterEventSource{} - err = c.client.Put(). - Resource("clustereventsources"). - Name(clusterEventSource.Name). - SubResource("status"). - Body(clusterEventSource). - Do(). - Into(result) - return -} - -// Delete takes name of the clusterEventSource and deletes it. Returns an error if one occurs. -func (c *clusterEventSources) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Resource("clustereventsources"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *clusterEventSources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - return c.client.Delete(). - Resource("clustereventsources"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched clusterEventSource. -func (c *clusterEventSources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterEventSource, err error) { - result = &v1alpha1.ClusterEventSource{} - err = c.client.Patch(pt). - Resource("clustereventsources"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/clustereventtype.go b/pkg/client/clientset/versioned/typed/feeds/v1alpha1/clustereventtype.go deleted file mode 100644 index 6b2d24d295d..00000000000 --- a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/clustereventtype.go +++ /dev/null @@ -1,163 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - scheme "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// ClusterEventTypesGetter has a method to return a ClusterEventTypeInterface. -// A group's client should implement this interface. -type ClusterEventTypesGetter interface { - ClusterEventTypes() ClusterEventTypeInterface -} - -// ClusterEventTypeInterface has methods to work with ClusterEventType resources. -type ClusterEventTypeInterface interface { - Create(*v1alpha1.ClusterEventType) (*v1alpha1.ClusterEventType, error) - Update(*v1alpha1.ClusterEventType) (*v1alpha1.ClusterEventType, error) - UpdateStatus(*v1alpha1.ClusterEventType) (*v1alpha1.ClusterEventType, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.ClusterEventType, error) - List(opts v1.ListOptions) (*v1alpha1.ClusterEventTypeList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterEventType, err error) - ClusterEventTypeExpansion -} - -// clusterEventTypes implements ClusterEventTypeInterface -type clusterEventTypes struct { - client rest.Interface -} - -// newClusterEventTypes returns a ClusterEventTypes -func newClusterEventTypes(c *FeedsV1alpha1Client) *clusterEventTypes { - return &clusterEventTypes{ - client: c.RESTClient(), - } -} - -// Get takes name of the clusterEventType, and returns the corresponding clusterEventType object, and an error if there is any. -func (c *clusterEventTypes) Get(name string, options v1.GetOptions) (result *v1alpha1.ClusterEventType, err error) { - result = &v1alpha1.ClusterEventType{} - err = c.client.Get(). - Resource("clustereventtypes"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of ClusterEventTypes that match those selectors. -func (c *clusterEventTypes) List(opts v1.ListOptions) (result *v1alpha1.ClusterEventTypeList, err error) { - result = &v1alpha1.ClusterEventTypeList{} - err = c.client.Get(). - Resource("clustereventtypes"). - VersionedParams(&opts, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested clusterEventTypes. -func (c *clusterEventTypes) Watch(opts v1.ListOptions) (watch.Interface, error) { - opts.Watch = true - return c.client.Get(). - Resource("clustereventtypes"). - VersionedParams(&opts, scheme.ParameterCodec). - Watch() -} - -// Create takes the representation of a clusterEventType and creates it. Returns the server's representation of the clusterEventType, and an error, if there is any. -func (c *clusterEventTypes) Create(clusterEventType *v1alpha1.ClusterEventType) (result *v1alpha1.ClusterEventType, err error) { - result = &v1alpha1.ClusterEventType{} - err = c.client.Post(). - Resource("clustereventtypes"). - Body(clusterEventType). - Do(). - Into(result) - return -} - -// Update takes the representation of a clusterEventType and updates it. Returns the server's representation of the clusterEventType, and an error, if there is any. -func (c *clusterEventTypes) Update(clusterEventType *v1alpha1.ClusterEventType) (result *v1alpha1.ClusterEventType, err error) { - result = &v1alpha1.ClusterEventType{} - err = c.client.Put(). - Resource("clustereventtypes"). - Name(clusterEventType.Name). - Body(clusterEventType). - Do(). - Into(result) - return -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - -func (c *clusterEventTypes) UpdateStatus(clusterEventType *v1alpha1.ClusterEventType) (result *v1alpha1.ClusterEventType, err error) { - result = &v1alpha1.ClusterEventType{} - err = c.client.Put(). - Resource("clustereventtypes"). - Name(clusterEventType.Name). - SubResource("status"). - Body(clusterEventType). - Do(). - Into(result) - return -} - -// Delete takes name of the clusterEventType and deletes it. Returns an error if one occurs. -func (c *clusterEventTypes) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Resource("clustereventtypes"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *clusterEventTypes) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - return c.client.Delete(). - Resource("clustereventtypes"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched clusterEventType. -func (c *clusterEventTypes) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterEventType, err error) { - result = &v1alpha1.ClusterEventType{} - err = c.client.Patch(pt). - Resource("clustereventtypes"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/eventsource.go b/pkg/client/clientset/versioned/typed/feeds/v1alpha1/eventsource.go deleted file mode 100644 index 6d28a8ae4e8..00000000000 --- a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/eventsource.go +++ /dev/null @@ -1,174 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - scheme "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// EventSourcesGetter has a method to return a EventSourceInterface. -// A group's client should implement this interface. -type EventSourcesGetter interface { - EventSources(namespace string) EventSourceInterface -} - -// EventSourceInterface has methods to work with EventSource resources. -type EventSourceInterface interface { - Create(*v1alpha1.EventSource) (*v1alpha1.EventSource, error) - Update(*v1alpha1.EventSource) (*v1alpha1.EventSource, error) - UpdateStatus(*v1alpha1.EventSource) (*v1alpha1.EventSource, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.EventSource, error) - List(opts v1.ListOptions) (*v1alpha1.EventSourceList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.EventSource, err error) - EventSourceExpansion -} - -// eventSources implements EventSourceInterface -type eventSources struct { - client rest.Interface - ns string -} - -// newEventSources returns a EventSources -func newEventSources(c *FeedsV1alpha1Client, namespace string) *eventSources { - return &eventSources{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the eventSource, and returns the corresponding eventSource object, and an error if there is any. -func (c *eventSources) Get(name string, options v1.GetOptions) (result *v1alpha1.EventSource, err error) { - result = &v1alpha1.EventSource{} - err = c.client.Get(). - Namespace(c.ns). - Resource("eventsources"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of EventSources that match those selectors. -func (c *eventSources) List(opts v1.ListOptions) (result *v1alpha1.EventSourceList, err error) { - result = &v1alpha1.EventSourceList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("eventsources"). - VersionedParams(&opts, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested eventSources. -func (c *eventSources) Watch(opts v1.ListOptions) (watch.Interface, error) { - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("eventsources"). - VersionedParams(&opts, scheme.ParameterCodec). - Watch() -} - -// Create takes the representation of a eventSource and creates it. Returns the server's representation of the eventSource, and an error, if there is any. -func (c *eventSources) Create(eventSource *v1alpha1.EventSource) (result *v1alpha1.EventSource, err error) { - result = &v1alpha1.EventSource{} - err = c.client.Post(). - Namespace(c.ns). - Resource("eventsources"). - Body(eventSource). - Do(). - Into(result) - return -} - -// Update takes the representation of a eventSource and updates it. Returns the server's representation of the eventSource, and an error, if there is any. -func (c *eventSources) Update(eventSource *v1alpha1.EventSource) (result *v1alpha1.EventSource, err error) { - result = &v1alpha1.EventSource{} - err = c.client.Put(). - Namespace(c.ns). - Resource("eventsources"). - Name(eventSource.Name). - Body(eventSource). - Do(). - Into(result) - return -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - -func (c *eventSources) UpdateStatus(eventSource *v1alpha1.EventSource) (result *v1alpha1.EventSource, err error) { - result = &v1alpha1.EventSource{} - err = c.client.Put(). - Namespace(c.ns). - Resource("eventsources"). - Name(eventSource.Name). - SubResource("status"). - Body(eventSource). - Do(). - Into(result) - return -} - -// Delete takes name of the eventSource and deletes it. Returns an error if one occurs. -func (c *eventSources) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("eventsources"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *eventSources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("eventsources"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched eventSource. -func (c *eventSources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.EventSource, err error) { - result = &v1alpha1.EventSource{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("eventsources"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/eventtype.go b/pkg/client/clientset/versioned/typed/feeds/v1alpha1/eventtype.go deleted file mode 100644 index 2f0b0a9998d..00000000000 --- a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/eventtype.go +++ /dev/null @@ -1,174 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - scheme "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// EventTypesGetter has a method to return a EventTypeInterface. -// A group's client should implement this interface. -type EventTypesGetter interface { - EventTypes(namespace string) EventTypeInterface -} - -// EventTypeInterface has methods to work with EventType resources. -type EventTypeInterface interface { - Create(*v1alpha1.EventType) (*v1alpha1.EventType, error) - Update(*v1alpha1.EventType) (*v1alpha1.EventType, error) - UpdateStatus(*v1alpha1.EventType) (*v1alpha1.EventType, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.EventType, error) - List(opts v1.ListOptions) (*v1alpha1.EventTypeList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.EventType, err error) - EventTypeExpansion -} - -// eventTypes implements EventTypeInterface -type eventTypes struct { - client rest.Interface - ns string -} - -// newEventTypes returns a EventTypes -func newEventTypes(c *FeedsV1alpha1Client, namespace string) *eventTypes { - return &eventTypes{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the eventType, and returns the corresponding eventType object, and an error if there is any. -func (c *eventTypes) Get(name string, options v1.GetOptions) (result *v1alpha1.EventType, err error) { - result = &v1alpha1.EventType{} - err = c.client.Get(). - Namespace(c.ns). - Resource("eventtypes"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of EventTypes that match those selectors. -func (c *eventTypes) List(opts v1.ListOptions) (result *v1alpha1.EventTypeList, err error) { - result = &v1alpha1.EventTypeList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("eventtypes"). - VersionedParams(&opts, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested eventTypes. -func (c *eventTypes) Watch(opts v1.ListOptions) (watch.Interface, error) { - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("eventtypes"). - VersionedParams(&opts, scheme.ParameterCodec). - Watch() -} - -// Create takes the representation of a eventType and creates it. Returns the server's representation of the eventType, and an error, if there is any. -func (c *eventTypes) Create(eventType *v1alpha1.EventType) (result *v1alpha1.EventType, err error) { - result = &v1alpha1.EventType{} - err = c.client.Post(). - Namespace(c.ns). - Resource("eventtypes"). - Body(eventType). - Do(). - Into(result) - return -} - -// Update takes the representation of a eventType and updates it. Returns the server's representation of the eventType, and an error, if there is any. -func (c *eventTypes) Update(eventType *v1alpha1.EventType) (result *v1alpha1.EventType, err error) { - result = &v1alpha1.EventType{} - err = c.client.Put(). - Namespace(c.ns). - Resource("eventtypes"). - Name(eventType.Name). - Body(eventType). - Do(). - Into(result) - return -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - -func (c *eventTypes) UpdateStatus(eventType *v1alpha1.EventType) (result *v1alpha1.EventType, err error) { - result = &v1alpha1.EventType{} - err = c.client.Put(). - Namespace(c.ns). - Resource("eventtypes"). - Name(eventType.Name). - SubResource("status"). - Body(eventType). - Do(). - Into(result) - return -} - -// Delete takes name of the eventType and deletes it. Returns an error if one occurs. -func (c *eventTypes) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("eventtypes"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *eventTypes) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("eventtypes"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched eventType. -func (c *eventTypes) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.EventType, err error) { - result = &v1alpha1.EventType{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("eventtypes"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/fake_clustereventsource.go b/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/fake_clustereventsource.go deleted file mode 100644 index 52f724b39ab..00000000000 --- a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/fake_clustereventsource.go +++ /dev/null @@ -1,131 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeClusterEventSources implements ClusterEventSourceInterface -type FakeClusterEventSources struct { - Fake *FakeFeedsV1alpha1 -} - -var clustereventsourcesResource = schema.GroupVersionResource{Group: "feeds.knative.dev", Version: "v1alpha1", Resource: "clustereventsources"} - -var clustereventsourcesKind = schema.GroupVersionKind{Group: "feeds.knative.dev", Version: "v1alpha1", Kind: "ClusterEventSource"} - -// Get takes name of the clusterEventSource, and returns the corresponding clusterEventSource object, and an error if there is any. -func (c *FakeClusterEventSources) Get(name string, options v1.GetOptions) (result *v1alpha1.ClusterEventSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootGetAction(clustereventsourcesResource, name), &v1alpha1.ClusterEventSource{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterEventSource), err -} - -// List takes label and field selectors, and returns the list of ClusterEventSources that match those selectors. -func (c *FakeClusterEventSources) List(opts v1.ListOptions) (result *v1alpha1.ClusterEventSourceList, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootListAction(clustereventsourcesResource, clustereventsourcesKind, opts), &v1alpha1.ClusterEventSourceList{}) - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.ClusterEventSourceList{ListMeta: obj.(*v1alpha1.ClusterEventSourceList).ListMeta} - for _, item := range obj.(*v1alpha1.ClusterEventSourceList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested clusterEventSources. -func (c *FakeClusterEventSources) Watch(opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewRootWatchAction(clustereventsourcesResource, opts)) -} - -// Create takes the representation of a clusterEventSource and creates it. Returns the server's representation of the clusterEventSource, and an error, if there is any. -func (c *FakeClusterEventSources) Create(clusterEventSource *v1alpha1.ClusterEventSource) (result *v1alpha1.ClusterEventSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootCreateAction(clustereventsourcesResource, clusterEventSource), &v1alpha1.ClusterEventSource{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterEventSource), err -} - -// Update takes the representation of a clusterEventSource and updates it. Returns the server's representation of the clusterEventSource, and an error, if there is any. -func (c *FakeClusterEventSources) Update(clusterEventSource *v1alpha1.ClusterEventSource) (result *v1alpha1.ClusterEventSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootUpdateAction(clustereventsourcesResource, clusterEventSource), &v1alpha1.ClusterEventSource{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterEventSource), err -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *FakeClusterEventSources) UpdateStatus(clusterEventSource *v1alpha1.ClusterEventSource) (*v1alpha1.ClusterEventSource, error) { - obj, err := c.Fake. - Invokes(testing.NewRootUpdateSubresourceAction(clustereventsourcesResource, "status", clusterEventSource), &v1alpha1.ClusterEventSource{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterEventSource), err -} - -// Delete takes name of the clusterEventSource and deletes it. Returns an error if one occurs. -func (c *FakeClusterEventSources) Delete(name string, options *v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewRootDeleteAction(clustereventsourcesResource, name), &v1alpha1.ClusterEventSource{}) - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeClusterEventSources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - action := testing.NewRootDeleteCollectionAction(clustereventsourcesResource, listOptions) - - _, err := c.Fake.Invokes(action, &v1alpha1.ClusterEventSourceList{}) - return err -} - -// Patch applies the patch and returns the patched clusterEventSource. -func (c *FakeClusterEventSources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterEventSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootPatchSubresourceAction(clustereventsourcesResource, name, data, subresources...), &v1alpha1.ClusterEventSource{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterEventSource), err -} diff --git a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/fake_clustereventtype.go b/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/fake_clustereventtype.go deleted file mode 100644 index 87ba368afbf..00000000000 --- a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/fake_clustereventtype.go +++ /dev/null @@ -1,131 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeClusterEventTypes implements ClusterEventTypeInterface -type FakeClusterEventTypes struct { - Fake *FakeFeedsV1alpha1 -} - -var clustereventtypesResource = schema.GroupVersionResource{Group: "feeds.knative.dev", Version: "v1alpha1", Resource: "clustereventtypes"} - -var clustereventtypesKind = schema.GroupVersionKind{Group: "feeds.knative.dev", Version: "v1alpha1", Kind: "ClusterEventType"} - -// Get takes name of the clusterEventType, and returns the corresponding clusterEventType object, and an error if there is any. -func (c *FakeClusterEventTypes) Get(name string, options v1.GetOptions) (result *v1alpha1.ClusterEventType, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootGetAction(clustereventtypesResource, name), &v1alpha1.ClusterEventType{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterEventType), err -} - -// List takes label and field selectors, and returns the list of ClusterEventTypes that match those selectors. -func (c *FakeClusterEventTypes) List(opts v1.ListOptions) (result *v1alpha1.ClusterEventTypeList, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootListAction(clustereventtypesResource, clustereventtypesKind, opts), &v1alpha1.ClusterEventTypeList{}) - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.ClusterEventTypeList{ListMeta: obj.(*v1alpha1.ClusterEventTypeList).ListMeta} - for _, item := range obj.(*v1alpha1.ClusterEventTypeList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested clusterEventTypes. -func (c *FakeClusterEventTypes) Watch(opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewRootWatchAction(clustereventtypesResource, opts)) -} - -// Create takes the representation of a clusterEventType and creates it. Returns the server's representation of the clusterEventType, and an error, if there is any. -func (c *FakeClusterEventTypes) Create(clusterEventType *v1alpha1.ClusterEventType) (result *v1alpha1.ClusterEventType, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootCreateAction(clustereventtypesResource, clusterEventType), &v1alpha1.ClusterEventType{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterEventType), err -} - -// Update takes the representation of a clusterEventType and updates it. Returns the server's representation of the clusterEventType, and an error, if there is any. -func (c *FakeClusterEventTypes) Update(clusterEventType *v1alpha1.ClusterEventType) (result *v1alpha1.ClusterEventType, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootUpdateAction(clustereventtypesResource, clusterEventType), &v1alpha1.ClusterEventType{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterEventType), err -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *FakeClusterEventTypes) UpdateStatus(clusterEventType *v1alpha1.ClusterEventType) (*v1alpha1.ClusterEventType, error) { - obj, err := c.Fake. - Invokes(testing.NewRootUpdateSubresourceAction(clustereventtypesResource, "status", clusterEventType), &v1alpha1.ClusterEventType{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterEventType), err -} - -// Delete takes name of the clusterEventType and deletes it. Returns an error if one occurs. -func (c *FakeClusterEventTypes) Delete(name string, options *v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewRootDeleteAction(clustereventtypesResource, name), &v1alpha1.ClusterEventType{}) - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeClusterEventTypes) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - action := testing.NewRootDeleteCollectionAction(clustereventtypesResource, listOptions) - - _, err := c.Fake.Invokes(action, &v1alpha1.ClusterEventTypeList{}) - return err -} - -// Patch applies the patch and returns the patched clusterEventType. -func (c *FakeClusterEventTypes) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterEventType, err error) { - obj, err := c.Fake. - Invokes(testing.NewRootPatchSubresourceAction(clustereventtypesResource, name, data, subresources...), &v1alpha1.ClusterEventType{}) - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ClusterEventType), err -} diff --git a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/fake_eventsource.go b/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/fake_eventsource.go deleted file mode 100644 index fbd3b10ed0a..00000000000 --- a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/fake_eventsource.go +++ /dev/null @@ -1,140 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeEventSources implements EventSourceInterface -type FakeEventSources struct { - Fake *FakeFeedsV1alpha1 - ns string -} - -var eventsourcesResource = schema.GroupVersionResource{Group: "feeds.knative.dev", Version: "v1alpha1", Resource: "eventsources"} - -var eventsourcesKind = schema.GroupVersionKind{Group: "feeds.knative.dev", Version: "v1alpha1", Kind: "EventSource"} - -// Get takes name of the eventSource, and returns the corresponding eventSource object, and an error if there is any. -func (c *FakeEventSources) Get(name string, options v1.GetOptions) (result *v1alpha1.EventSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(eventsourcesResource, c.ns, name), &v1alpha1.EventSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.EventSource), err -} - -// List takes label and field selectors, and returns the list of EventSources that match those selectors. -func (c *FakeEventSources) List(opts v1.ListOptions) (result *v1alpha1.EventSourceList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(eventsourcesResource, eventsourcesKind, c.ns, opts), &v1alpha1.EventSourceList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.EventSourceList{ListMeta: obj.(*v1alpha1.EventSourceList).ListMeta} - for _, item := range obj.(*v1alpha1.EventSourceList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested eventSources. -func (c *FakeEventSources) Watch(opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(eventsourcesResource, c.ns, opts)) - -} - -// Create takes the representation of a eventSource and creates it. Returns the server's representation of the eventSource, and an error, if there is any. -func (c *FakeEventSources) Create(eventSource *v1alpha1.EventSource) (result *v1alpha1.EventSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(eventsourcesResource, c.ns, eventSource), &v1alpha1.EventSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.EventSource), err -} - -// Update takes the representation of a eventSource and updates it. Returns the server's representation of the eventSource, and an error, if there is any. -func (c *FakeEventSources) Update(eventSource *v1alpha1.EventSource) (result *v1alpha1.EventSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(eventsourcesResource, c.ns, eventSource), &v1alpha1.EventSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.EventSource), err -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *FakeEventSources) UpdateStatus(eventSource *v1alpha1.EventSource) (*v1alpha1.EventSource, error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateSubresourceAction(eventsourcesResource, "status", c.ns, eventSource), &v1alpha1.EventSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.EventSource), err -} - -// Delete takes name of the eventSource and deletes it. Returns an error if one occurs. -func (c *FakeEventSources) Delete(name string, options *v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteAction(eventsourcesResource, c.ns, name), &v1alpha1.EventSource{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeEventSources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(eventsourcesResource, c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &v1alpha1.EventSourceList{}) - return err -} - -// Patch applies the patch and returns the patched eventSource. -func (c *FakeEventSources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.EventSource, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(eventsourcesResource, c.ns, name, data, subresources...), &v1alpha1.EventSource{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.EventSource), err -} diff --git a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/fake_eventtype.go b/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/fake_eventtype.go deleted file mode 100644 index bdef7163d5e..00000000000 --- a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/fake_eventtype.go +++ /dev/null @@ -1,140 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeEventTypes implements EventTypeInterface -type FakeEventTypes struct { - Fake *FakeFeedsV1alpha1 - ns string -} - -var eventtypesResource = schema.GroupVersionResource{Group: "feeds.knative.dev", Version: "v1alpha1", Resource: "eventtypes"} - -var eventtypesKind = schema.GroupVersionKind{Group: "feeds.knative.dev", Version: "v1alpha1", Kind: "EventType"} - -// Get takes name of the eventType, and returns the corresponding eventType object, and an error if there is any. -func (c *FakeEventTypes) Get(name string, options v1.GetOptions) (result *v1alpha1.EventType, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(eventtypesResource, c.ns, name), &v1alpha1.EventType{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.EventType), err -} - -// List takes label and field selectors, and returns the list of EventTypes that match those selectors. -func (c *FakeEventTypes) List(opts v1.ListOptions) (result *v1alpha1.EventTypeList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(eventtypesResource, eventtypesKind, c.ns, opts), &v1alpha1.EventTypeList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.EventTypeList{ListMeta: obj.(*v1alpha1.EventTypeList).ListMeta} - for _, item := range obj.(*v1alpha1.EventTypeList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested eventTypes. -func (c *FakeEventTypes) Watch(opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(eventtypesResource, c.ns, opts)) - -} - -// Create takes the representation of a eventType and creates it. Returns the server's representation of the eventType, and an error, if there is any. -func (c *FakeEventTypes) Create(eventType *v1alpha1.EventType) (result *v1alpha1.EventType, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(eventtypesResource, c.ns, eventType), &v1alpha1.EventType{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.EventType), err -} - -// Update takes the representation of a eventType and updates it. Returns the server's representation of the eventType, and an error, if there is any. -func (c *FakeEventTypes) Update(eventType *v1alpha1.EventType) (result *v1alpha1.EventType, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(eventtypesResource, c.ns, eventType), &v1alpha1.EventType{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.EventType), err -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *FakeEventTypes) UpdateStatus(eventType *v1alpha1.EventType) (*v1alpha1.EventType, error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateSubresourceAction(eventtypesResource, "status", c.ns, eventType), &v1alpha1.EventType{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.EventType), err -} - -// Delete takes name of the eventType and deletes it. Returns an error if one occurs. -func (c *FakeEventTypes) Delete(name string, options *v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteAction(eventtypesResource, c.ns, name), &v1alpha1.EventType{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeEventTypes) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(eventtypesResource, c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &v1alpha1.EventTypeList{}) - return err -} - -// Patch applies the patch and returns the patched eventType. -func (c *FakeEventTypes) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.EventType, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(eventtypesResource, c.ns, name, data, subresources...), &v1alpha1.EventType{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.EventType), err -} diff --git a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/fake_feed.go b/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/fake_feed.go deleted file mode 100644 index 45f6beaa92c..00000000000 --- a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/fake_feed.go +++ /dev/null @@ -1,140 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeFeeds implements FeedInterface -type FakeFeeds struct { - Fake *FakeFeedsV1alpha1 - ns string -} - -var feedsResource = schema.GroupVersionResource{Group: "feeds.knative.dev", Version: "v1alpha1", Resource: "feeds"} - -var feedsKind = schema.GroupVersionKind{Group: "feeds.knative.dev", Version: "v1alpha1", Kind: "Feed"} - -// Get takes name of the feed, and returns the corresponding feed object, and an error if there is any. -func (c *FakeFeeds) Get(name string, options v1.GetOptions) (result *v1alpha1.Feed, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(feedsResource, c.ns, name), &v1alpha1.Feed{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Feed), err -} - -// List takes label and field selectors, and returns the list of Feeds that match those selectors. -func (c *FakeFeeds) List(opts v1.ListOptions) (result *v1alpha1.FeedList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(feedsResource, feedsKind, c.ns, opts), &v1alpha1.FeedList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.FeedList{ListMeta: obj.(*v1alpha1.FeedList).ListMeta} - for _, item := range obj.(*v1alpha1.FeedList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested feeds. -func (c *FakeFeeds) Watch(opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(feedsResource, c.ns, opts)) - -} - -// Create takes the representation of a feed and creates it. Returns the server's representation of the feed, and an error, if there is any. -func (c *FakeFeeds) Create(feed *v1alpha1.Feed) (result *v1alpha1.Feed, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(feedsResource, c.ns, feed), &v1alpha1.Feed{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Feed), err -} - -// Update takes the representation of a feed and updates it. Returns the server's representation of the feed, and an error, if there is any. -func (c *FakeFeeds) Update(feed *v1alpha1.Feed) (result *v1alpha1.Feed, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(feedsResource, c.ns, feed), &v1alpha1.Feed{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Feed), err -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *FakeFeeds) UpdateStatus(feed *v1alpha1.Feed) (*v1alpha1.Feed, error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateSubresourceAction(feedsResource, "status", c.ns, feed), &v1alpha1.Feed{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Feed), err -} - -// Delete takes name of the feed and deletes it. Returns an error if one occurs. -func (c *FakeFeeds) Delete(name string, options *v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteAction(feedsResource, c.ns, name), &v1alpha1.Feed{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeFeeds) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(feedsResource, c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &v1alpha1.FeedList{}) - return err -} - -// Patch applies the patch and returns the patched feed. -func (c *FakeFeeds) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Feed, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(feedsResource, c.ns, name, data, subresources...), &v1alpha1.Feed{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Feed), err -} diff --git a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/fake_feeds_client.go b/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/fake_feeds_client.go deleted file mode 100644 index a1a506c5aef..00000000000 --- a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/fake_feeds_client.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/knative/eventing/pkg/client/clientset/versioned/typed/feeds/v1alpha1" - rest "k8s.io/client-go/rest" - testing "k8s.io/client-go/testing" -) - -type FakeFeedsV1alpha1 struct { - *testing.Fake -} - -func (c *FakeFeedsV1alpha1) ClusterEventSources() v1alpha1.ClusterEventSourceInterface { - return &FakeClusterEventSources{c} -} - -func (c *FakeFeedsV1alpha1) ClusterEventTypes() v1alpha1.ClusterEventTypeInterface { - return &FakeClusterEventTypes{c} -} - -func (c *FakeFeedsV1alpha1) EventSources(namespace string) v1alpha1.EventSourceInterface { - return &FakeEventSources{c, namespace} -} - -func (c *FakeFeedsV1alpha1) EventTypes(namespace string) v1alpha1.EventTypeInterface { - return &FakeEventTypes{c, namespace} -} - -func (c *FakeFeedsV1alpha1) Feeds(namespace string) v1alpha1.FeedInterface { - return &FakeFeeds{c, namespace} -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *FakeFeedsV1alpha1) RESTClient() rest.Interface { - var ret *rest.RESTClient - return ret -} diff --git a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/feed.go b/pkg/client/clientset/versioned/typed/feeds/v1alpha1/feed.go deleted file mode 100644 index f521a734677..00000000000 --- a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/feed.go +++ /dev/null @@ -1,174 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - scheme "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// FeedsGetter has a method to return a FeedInterface. -// A group's client should implement this interface. -type FeedsGetter interface { - Feeds(namespace string) FeedInterface -} - -// FeedInterface has methods to work with Feed resources. -type FeedInterface interface { - Create(*v1alpha1.Feed) (*v1alpha1.Feed, error) - Update(*v1alpha1.Feed) (*v1alpha1.Feed, error) - UpdateStatus(*v1alpha1.Feed) (*v1alpha1.Feed, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.Feed, error) - List(opts v1.ListOptions) (*v1alpha1.FeedList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Feed, err error) - FeedExpansion -} - -// feeds implements FeedInterface -type feeds struct { - client rest.Interface - ns string -} - -// newFeeds returns a Feeds -func newFeeds(c *FeedsV1alpha1Client, namespace string) *feeds { - return &feeds{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the feed, and returns the corresponding feed object, and an error if there is any. -func (c *feeds) Get(name string, options v1.GetOptions) (result *v1alpha1.Feed, err error) { - result = &v1alpha1.Feed{} - err = c.client.Get(). - Namespace(c.ns). - Resource("feeds"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of Feeds that match those selectors. -func (c *feeds) List(opts v1.ListOptions) (result *v1alpha1.FeedList, err error) { - result = &v1alpha1.FeedList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("feeds"). - VersionedParams(&opts, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested feeds. -func (c *feeds) Watch(opts v1.ListOptions) (watch.Interface, error) { - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("feeds"). - VersionedParams(&opts, scheme.ParameterCodec). - Watch() -} - -// Create takes the representation of a feed and creates it. Returns the server's representation of the feed, and an error, if there is any. -func (c *feeds) Create(feed *v1alpha1.Feed) (result *v1alpha1.Feed, err error) { - result = &v1alpha1.Feed{} - err = c.client.Post(). - Namespace(c.ns). - Resource("feeds"). - Body(feed). - Do(). - Into(result) - return -} - -// Update takes the representation of a feed and updates it. Returns the server's representation of the feed, and an error, if there is any. -func (c *feeds) Update(feed *v1alpha1.Feed) (result *v1alpha1.Feed, err error) { - result = &v1alpha1.Feed{} - err = c.client.Put(). - Namespace(c.ns). - Resource("feeds"). - Name(feed.Name). - Body(feed). - Do(). - Into(result) - return -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - -func (c *feeds) UpdateStatus(feed *v1alpha1.Feed) (result *v1alpha1.Feed, err error) { - result = &v1alpha1.Feed{} - err = c.client.Put(). - Namespace(c.ns). - Resource("feeds"). - Name(feed.Name). - SubResource("status"). - Body(feed). - Do(). - Into(result) - return -} - -// Delete takes name of the feed and deletes it. Returns an error if one occurs. -func (c *feeds) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("feeds"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *feeds) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("feeds"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched feed. -func (c *feeds) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Feed, err error) { - result = &v1alpha1.Feed{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("feeds"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/feeds_client.go b/pkg/client/clientset/versioned/typed/feeds/v1alpha1/feeds_client.go deleted file mode 100644 index df66a2000b0..00000000000 --- a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/feeds_client.go +++ /dev/null @@ -1,110 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" - serializer "k8s.io/apimachinery/pkg/runtime/serializer" - rest "k8s.io/client-go/rest" -) - -type FeedsV1alpha1Interface interface { - RESTClient() rest.Interface - ClusterEventSourcesGetter - ClusterEventTypesGetter - EventSourcesGetter - EventTypesGetter - FeedsGetter -} - -// FeedsV1alpha1Client is used to interact with features provided by the feeds.knative.dev group. -type FeedsV1alpha1Client struct { - restClient rest.Interface -} - -func (c *FeedsV1alpha1Client) ClusterEventSources() ClusterEventSourceInterface { - return newClusterEventSources(c) -} - -func (c *FeedsV1alpha1Client) ClusterEventTypes() ClusterEventTypeInterface { - return newClusterEventTypes(c) -} - -func (c *FeedsV1alpha1Client) EventSources(namespace string) EventSourceInterface { - return newEventSources(c, namespace) -} - -func (c *FeedsV1alpha1Client) EventTypes(namespace string) EventTypeInterface { - return newEventTypes(c, namespace) -} - -func (c *FeedsV1alpha1Client) Feeds(namespace string) FeedInterface { - return newFeeds(c, namespace) -} - -// NewForConfig creates a new FeedsV1alpha1Client for the given config. -func NewForConfig(c *rest.Config) (*FeedsV1alpha1Client, error) { - config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } - client, err := rest.RESTClientFor(&config) - if err != nil { - return nil, err - } - return &FeedsV1alpha1Client{client}, nil -} - -// NewForConfigOrDie creates a new FeedsV1alpha1Client for the given config and -// panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *FeedsV1alpha1Client { - client, err := NewForConfig(c) - if err != nil { - panic(err) - } - return client -} - -// New creates a new FeedsV1alpha1Client for the given RESTClient. -func New(c rest.Interface) *FeedsV1alpha1Client { - return &FeedsV1alpha1Client{c} -} - -func setConfigDefaults(config *rest.Config) error { - gv := v1alpha1.SchemeGroupVersion - config.GroupVersion = &gv - config.APIPath = "/apis" - config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs} - - if config.UserAgent == "" { - config.UserAgent = rest.DefaultKubernetesUserAgent() - } - - return nil -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *FeedsV1alpha1Client) RESTClient() rest.Interface { - if c == nil { - return nil - } - return c.restClient -} diff --git a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/generated_expansion.go b/pkg/client/clientset/versioned/typed/feeds/v1alpha1/generated_expansion.go deleted file mode 100644 index bb9c1c83f55..00000000000 --- a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/generated_expansion.go +++ /dev/null @@ -1,29 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -type ClusterEventSourceExpansion interface{} - -type ClusterEventTypeExpansion interface{} - -type EventSourceExpansion interface{} - -type EventTypeExpansion interface{} - -type FeedExpansion interface{} diff --git a/pkg/client/clientset/versioned/typed/flows/v1alpha1/fake/doc.go b/pkg/client/clientset/versioned/typed/flows/v1alpha1/fake/doc.go deleted file mode 100644 index 128aa183a91..00000000000 --- a/pkg/client/clientset/versioned/typed/flows/v1alpha1/fake/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -// Package fake has the automatically generated clients. -package fake diff --git a/pkg/client/clientset/versioned/typed/flows/v1alpha1/fake/fake_flow.go b/pkg/client/clientset/versioned/typed/flows/v1alpha1/fake/fake_flow.go deleted file mode 100644 index 786dfd44e29..00000000000 --- a/pkg/client/clientset/versioned/typed/flows/v1alpha1/fake/fake_flow.go +++ /dev/null @@ -1,140 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/flows/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeFlows implements FlowInterface -type FakeFlows struct { - Fake *FakeFlowsV1alpha1 - ns string -} - -var flowsResource = schema.GroupVersionResource{Group: "flows.knative.dev", Version: "v1alpha1", Resource: "flows"} - -var flowsKind = schema.GroupVersionKind{Group: "flows.knative.dev", Version: "v1alpha1", Kind: "Flow"} - -// Get takes name of the flow, and returns the corresponding flow object, and an error if there is any. -func (c *FakeFlows) Get(name string, options v1.GetOptions) (result *v1alpha1.Flow, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(flowsResource, c.ns, name), &v1alpha1.Flow{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Flow), err -} - -// List takes label and field selectors, and returns the list of Flows that match those selectors. -func (c *FakeFlows) List(opts v1.ListOptions) (result *v1alpha1.FlowList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(flowsResource, flowsKind, c.ns, opts), &v1alpha1.FlowList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.FlowList{ListMeta: obj.(*v1alpha1.FlowList).ListMeta} - for _, item := range obj.(*v1alpha1.FlowList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested flows. -func (c *FakeFlows) Watch(opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(flowsResource, c.ns, opts)) - -} - -// Create takes the representation of a flow and creates it. Returns the server's representation of the flow, and an error, if there is any. -func (c *FakeFlows) Create(flow *v1alpha1.Flow) (result *v1alpha1.Flow, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(flowsResource, c.ns, flow), &v1alpha1.Flow{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Flow), err -} - -// Update takes the representation of a flow and updates it. Returns the server's representation of the flow, and an error, if there is any. -func (c *FakeFlows) Update(flow *v1alpha1.Flow) (result *v1alpha1.Flow, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(flowsResource, c.ns, flow), &v1alpha1.Flow{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Flow), err -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *FakeFlows) UpdateStatus(flow *v1alpha1.Flow) (*v1alpha1.Flow, error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateSubresourceAction(flowsResource, "status", c.ns, flow), &v1alpha1.Flow{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Flow), err -} - -// Delete takes name of the flow and deletes it. Returns an error if one occurs. -func (c *FakeFlows) Delete(name string, options *v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteAction(flowsResource, c.ns, name), &v1alpha1.Flow{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeFlows) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(flowsResource, c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &v1alpha1.FlowList{}) - return err -} - -// Patch applies the patch and returns the patched flow. -func (c *FakeFlows) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Flow, err error) { - obj, err := c.Fake. - Invokes(testing.NewPatchSubresourceAction(flowsResource, c.ns, name, data, subresources...), &v1alpha1.Flow{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.Flow), err -} diff --git a/pkg/client/clientset/versioned/typed/flows/v1alpha1/fake/fake_flows_client.go b/pkg/client/clientset/versioned/typed/flows/v1alpha1/fake/fake_flows_client.go deleted file mode 100644 index 266afaff88b..00000000000 --- a/pkg/client/clientset/versioned/typed/flows/v1alpha1/fake/fake_flows_client.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/knative/eventing/pkg/client/clientset/versioned/typed/flows/v1alpha1" - rest "k8s.io/client-go/rest" - testing "k8s.io/client-go/testing" -) - -type FakeFlowsV1alpha1 struct { - *testing.Fake -} - -func (c *FakeFlowsV1alpha1) Flows(namespace string) v1alpha1.FlowInterface { - return &FakeFlows{c, namespace} -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *FakeFlowsV1alpha1) RESTClient() rest.Interface { - var ret *rest.RESTClient - return ret -} diff --git a/pkg/client/clientset/versioned/typed/flows/v1alpha1/flow.go b/pkg/client/clientset/versioned/typed/flows/v1alpha1/flow.go deleted file mode 100644 index f687c0dd387..00000000000 --- a/pkg/client/clientset/versioned/typed/flows/v1alpha1/flow.go +++ /dev/null @@ -1,174 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/flows/v1alpha1" - scheme "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// FlowsGetter has a method to return a FlowInterface. -// A group's client should implement this interface. -type FlowsGetter interface { - Flows(namespace string) FlowInterface -} - -// FlowInterface has methods to work with Flow resources. -type FlowInterface interface { - Create(*v1alpha1.Flow) (*v1alpha1.Flow, error) - Update(*v1alpha1.Flow) (*v1alpha1.Flow, error) - UpdateStatus(*v1alpha1.Flow) (*v1alpha1.Flow, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.Flow, error) - List(opts v1.ListOptions) (*v1alpha1.FlowList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Flow, err error) - FlowExpansion -} - -// flows implements FlowInterface -type flows struct { - client rest.Interface - ns string -} - -// newFlows returns a Flows -func newFlows(c *FlowsV1alpha1Client, namespace string) *flows { - return &flows{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the flow, and returns the corresponding flow object, and an error if there is any. -func (c *flows) Get(name string, options v1.GetOptions) (result *v1alpha1.Flow, err error) { - result = &v1alpha1.Flow{} - err = c.client.Get(). - Namespace(c.ns). - Resource("flows"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of Flows that match those selectors. -func (c *flows) List(opts v1.ListOptions) (result *v1alpha1.FlowList, err error) { - result = &v1alpha1.FlowList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("flows"). - VersionedParams(&opts, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested flows. -func (c *flows) Watch(opts v1.ListOptions) (watch.Interface, error) { - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("flows"). - VersionedParams(&opts, scheme.ParameterCodec). - Watch() -} - -// Create takes the representation of a flow and creates it. Returns the server's representation of the flow, and an error, if there is any. -func (c *flows) Create(flow *v1alpha1.Flow) (result *v1alpha1.Flow, err error) { - result = &v1alpha1.Flow{} - err = c.client.Post(). - Namespace(c.ns). - Resource("flows"). - Body(flow). - Do(). - Into(result) - return -} - -// Update takes the representation of a flow and updates it. Returns the server's representation of the flow, and an error, if there is any. -func (c *flows) Update(flow *v1alpha1.Flow) (result *v1alpha1.Flow, err error) { - result = &v1alpha1.Flow{} - err = c.client.Put(). - Namespace(c.ns). - Resource("flows"). - Name(flow.Name). - Body(flow). - Do(). - Into(result) - return -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - -func (c *flows) UpdateStatus(flow *v1alpha1.Flow) (result *v1alpha1.Flow, err error) { - result = &v1alpha1.Flow{} - err = c.client.Put(). - Namespace(c.ns). - Resource("flows"). - Name(flow.Name). - SubResource("status"). - Body(flow). - Do(). - Into(result) - return -} - -// Delete takes name of the flow and deletes it. Returns an error if one occurs. -func (c *flows) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("flows"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *flows) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("flows"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched flow. -func (c *flows) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Flow, err error) { - result = &v1alpha1.Flow{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("flows"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/pkg/client/informers/externalversions/channels/interface.go b/pkg/client/informers/externalversions/channels/interface.go deleted file mode 100644 index ab211697acd..00000000000 --- a/pkg/client/informers/externalversions/channels/interface.go +++ /dev/null @@ -1,46 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package channels - -import ( - v1alpha1 "github.com/knative/eventing/pkg/client/informers/externalversions/channels/v1alpha1" - internalinterfaces "github.com/knative/eventing/pkg/client/informers/externalversions/internalinterfaces" -) - -// Interface provides access to each of this group's versions. -type Interface interface { - // V1alpha1 provides access to shared informers for resources in V1alpha1. - V1alpha1() v1alpha1.Interface -} - -type group struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// V1alpha1 returns a new v1alpha1.Interface. -func (g *group) V1alpha1() v1alpha1.Interface { - return v1alpha1.New(g.factory, g.namespace, g.tweakListOptions) -} diff --git a/pkg/client/informers/externalversions/channels/v1alpha1/bus.go b/pkg/client/informers/externalversions/channels/v1alpha1/bus.go deleted file mode 100644 index 43ee3cffb56..00000000000 --- a/pkg/client/informers/externalversions/channels/v1alpha1/bus.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - time "time" - - channels_v1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - versioned "github.com/knative/eventing/pkg/client/clientset/versioned" - internalinterfaces "github.com/knative/eventing/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/knative/eventing/pkg/client/listers/channels/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// BusInformer provides access to a shared informer and lister for -// Buses. -type BusInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.BusLister -} - -type busInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewBusInformer constructs a new informer for Bus type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewBusInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredBusInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredBusInformer constructs a new informer for Bus type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredBusInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.ChannelsV1alpha1().Buses(namespace).List(options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.ChannelsV1alpha1().Buses(namespace).Watch(options) - }, - }, - &channels_v1alpha1.Bus{}, - resyncPeriod, - indexers, - ) -} - -func (f *busInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredBusInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *busInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&channels_v1alpha1.Bus{}, f.defaultInformer) -} - -func (f *busInformer) Lister() v1alpha1.BusLister { - return v1alpha1.NewBusLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/informers/externalversions/channels/v1alpha1/channel.go b/pkg/client/informers/externalversions/channels/v1alpha1/channel.go deleted file mode 100644 index b00e1fe36c5..00000000000 --- a/pkg/client/informers/externalversions/channels/v1alpha1/channel.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - time "time" - - channels_v1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - versioned "github.com/knative/eventing/pkg/client/clientset/versioned" - internalinterfaces "github.com/knative/eventing/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/knative/eventing/pkg/client/listers/channels/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// ChannelInformer provides access to a shared informer and lister for -// Channels. -type ChannelInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.ChannelLister -} - -type channelInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewChannelInformer constructs a new informer for Channel type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewChannelInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredChannelInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredChannelInformer constructs a new informer for Channel type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredChannelInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.ChannelsV1alpha1().Channels(namespace).List(options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.ChannelsV1alpha1().Channels(namespace).Watch(options) - }, - }, - &channels_v1alpha1.Channel{}, - resyncPeriod, - indexers, - ) -} - -func (f *channelInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredChannelInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *channelInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&channels_v1alpha1.Channel{}, f.defaultInformer) -} - -func (f *channelInformer) Lister() v1alpha1.ChannelLister { - return v1alpha1.NewChannelLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/informers/externalversions/channels/v1alpha1/clusterbus.go b/pkg/client/informers/externalversions/channels/v1alpha1/clusterbus.go deleted file mode 100644 index 109af846e71..00000000000 --- a/pkg/client/informers/externalversions/channels/v1alpha1/clusterbus.go +++ /dev/null @@ -1,88 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - time "time" - - channels_v1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - versioned "github.com/knative/eventing/pkg/client/clientset/versioned" - internalinterfaces "github.com/knative/eventing/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/knative/eventing/pkg/client/listers/channels/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// ClusterBusInformer provides access to a shared informer and lister for -// ClusterBuses. -type ClusterBusInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.ClusterBusLister -} - -type clusterBusInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// NewClusterBusInformer constructs a new informer for ClusterBus type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewClusterBusInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredClusterBusInformer(client, resyncPeriod, indexers, nil) -} - -// NewFilteredClusterBusInformer constructs a new informer for ClusterBus type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredClusterBusInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.ChannelsV1alpha1().ClusterBuses().List(options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.ChannelsV1alpha1().ClusterBuses().Watch(options) - }, - }, - &channels_v1alpha1.ClusterBus{}, - resyncPeriod, - indexers, - ) -} - -func (f *clusterBusInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredClusterBusInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *clusterBusInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&channels_v1alpha1.ClusterBus{}, f.defaultInformer) -} - -func (f *clusterBusInformer) Lister() v1alpha1.ClusterBusLister { - return v1alpha1.NewClusterBusLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/informers/externalversions/channels/v1alpha1/interface.go b/pkg/client/informers/externalversions/channels/v1alpha1/interface.go deleted file mode 100644 index 0831ac85fba..00000000000 --- a/pkg/client/informers/externalversions/channels/v1alpha1/interface.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - internalinterfaces "github.com/knative/eventing/pkg/client/informers/externalversions/internalinterfaces" -) - -// Interface provides access to all the informers in this group version. -type Interface interface { - // Buses returns a BusInformer. - Buses() BusInformer - // Channels returns a ChannelInformer. - Channels() ChannelInformer - // ClusterBuses returns a ClusterBusInformer. - ClusterBuses() ClusterBusInformer - // Subscriptions returns a SubscriptionInformer. - Subscriptions() SubscriptionInformer -} - -type version struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// Buses returns a BusInformer. -func (v *version) Buses() BusInformer { - return &busInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// Channels returns a ChannelInformer. -func (v *version) Channels() ChannelInformer { - return &channelInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// ClusterBuses returns a ClusterBusInformer. -func (v *version) ClusterBuses() ClusterBusInformer { - return &clusterBusInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} -} - -// Subscriptions returns a SubscriptionInformer. -func (v *version) Subscriptions() SubscriptionInformer { - return &subscriptionInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} diff --git a/pkg/client/informers/externalversions/channels/v1alpha1/subscription.go b/pkg/client/informers/externalversions/channels/v1alpha1/subscription.go deleted file mode 100644 index ee2ae6d1a23..00000000000 --- a/pkg/client/informers/externalversions/channels/v1alpha1/subscription.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - time "time" - - channels_v1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - versioned "github.com/knative/eventing/pkg/client/clientset/versioned" - internalinterfaces "github.com/knative/eventing/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/knative/eventing/pkg/client/listers/channels/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// SubscriptionInformer provides access to a shared informer and lister for -// Subscriptions. -type SubscriptionInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.SubscriptionLister -} - -type subscriptionInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewSubscriptionInformer constructs a new informer for Subscription type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewSubscriptionInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredSubscriptionInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredSubscriptionInformer constructs a new informer for Subscription type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredSubscriptionInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.ChannelsV1alpha1().Subscriptions(namespace).List(options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.ChannelsV1alpha1().Subscriptions(namespace).Watch(options) - }, - }, - &channels_v1alpha1.Subscription{}, - resyncPeriod, - indexers, - ) -} - -func (f *subscriptionInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredSubscriptionInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *subscriptionInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&channels_v1alpha1.Subscription{}, f.defaultInformer) -} - -func (f *subscriptionInformer) Lister() v1alpha1.SubscriptionLister { - return v1alpha1.NewSubscriptionLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/informers/externalversions/eventing/v1alpha1/clusterprovisioner.go b/pkg/client/informers/externalversions/eventing/v1alpha1/clusterchannelprovisioner.go similarity index 53% rename from pkg/client/informers/externalversions/eventing/v1alpha1/clusterprovisioner.go rename to pkg/client/informers/externalversions/eventing/v1alpha1/clusterchannelprovisioner.go index fabfa09b5a5..fb0aae439aa 100644 --- a/pkg/client/informers/externalversions/eventing/v1alpha1/clusterprovisioner.go +++ b/pkg/client/informers/externalversions/eventing/v1alpha1/clusterchannelprovisioner.go @@ -31,58 +31,58 @@ import ( cache "k8s.io/client-go/tools/cache" ) -// ClusterProvisionerInformer provides access to a shared informer and lister for -// ClusterProvisioners. -type ClusterProvisionerInformer interface { +// ClusterChannelProvisionerInformer provides access to a shared informer and lister for +// ClusterChannelProvisioners. +type ClusterChannelProvisionerInformer interface { Informer() cache.SharedIndexInformer - Lister() v1alpha1.ClusterProvisionerLister + Lister() v1alpha1.ClusterChannelProvisionerLister } -type clusterProvisionerInformer struct { +type clusterChannelProvisionerInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc } -// NewClusterProvisionerInformer constructs a new informer for ClusterProvisioner type. +// NewClusterChannelProvisionerInformer constructs a new informer for ClusterChannelProvisioner type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. -func NewClusterProvisionerInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredClusterProvisionerInformer(client, resyncPeriod, indexers, nil) +func NewClusterChannelProvisionerInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredClusterChannelProvisionerInformer(client, resyncPeriod, indexers, nil) } -// NewFilteredClusterProvisionerInformer constructs a new informer for ClusterProvisioner type. +// NewFilteredClusterChannelProvisionerInformer constructs a new informer for ClusterChannelProvisioner type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. -func NewFilteredClusterProvisionerInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { +func NewFilteredClusterChannelProvisionerInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { return cache.NewSharedIndexInformer( &cache.ListWatch{ ListFunc: func(options v1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.EventingV1alpha1().ClusterProvisioners().List(options) + return client.EventingV1alpha1().ClusterChannelProvisioners().List(options) }, WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } - return client.EventingV1alpha1().ClusterProvisioners().Watch(options) + return client.EventingV1alpha1().ClusterChannelProvisioners().Watch(options) }, }, - &eventing_v1alpha1.ClusterProvisioner{}, + &eventing_v1alpha1.ClusterChannelProvisioner{}, resyncPeriod, indexers, ) } -func (f *clusterProvisionerInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredClusterProvisionerInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +func (f *clusterChannelProvisionerInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredClusterChannelProvisionerInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) } -func (f *clusterProvisionerInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&eventing_v1alpha1.ClusterProvisioner{}, f.defaultInformer) +func (f *clusterChannelProvisionerInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&eventing_v1alpha1.ClusterChannelProvisioner{}, f.defaultInformer) } -func (f *clusterProvisionerInformer) Lister() v1alpha1.ClusterProvisionerLister { - return v1alpha1.NewClusterProvisionerLister(f.Informer().GetIndexer()) +func (f *clusterChannelProvisionerInformer) Lister() v1alpha1.ClusterChannelProvisionerLister { + return v1alpha1.NewClusterChannelProvisionerLister(f.Informer().GetIndexer()) } diff --git a/pkg/client/informers/externalversions/eventing/v1alpha1/interface.go b/pkg/client/informers/externalversions/eventing/v1alpha1/interface.go index 2a44cf0f052..15bebacbe7f 100644 --- a/pkg/client/informers/externalversions/eventing/v1alpha1/interface.go +++ b/pkg/client/informers/externalversions/eventing/v1alpha1/interface.go @@ -26,10 +26,8 @@ import ( type Interface interface { // Channels returns a ChannelInformer. Channels() ChannelInformer - // ClusterProvisioners returns a ClusterProvisionerInformer. - ClusterProvisioners() ClusterProvisionerInformer - // Sources returns a SourceInformer. - Sources() SourceInformer + // ClusterChannelProvisioners returns a ClusterChannelProvisionerInformer. + ClusterChannelProvisioners() ClusterChannelProvisionerInformer // Subscriptions returns a SubscriptionInformer. Subscriptions() SubscriptionInformer } @@ -50,14 +48,9 @@ func (v *version) Channels() ChannelInformer { return &channelInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } -// ClusterProvisioners returns a ClusterProvisionerInformer. -func (v *version) ClusterProvisioners() ClusterProvisionerInformer { - return &clusterProvisionerInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} -} - -// Sources returns a SourceInformer. -func (v *version) Sources() SourceInformer { - return &sourceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +// ClusterChannelProvisioners returns a ClusterChannelProvisionerInformer. +func (v *version) ClusterChannelProvisioners() ClusterChannelProvisionerInformer { + return &clusterChannelProvisionerInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } // Subscriptions returns a SubscriptionInformer. diff --git a/pkg/client/informers/externalversions/eventing/v1alpha1/source.go b/pkg/client/informers/externalversions/eventing/v1alpha1/source.go deleted file mode 100644 index eb06180eed1..00000000000 --- a/pkg/client/informers/externalversions/eventing/v1alpha1/source.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - time "time" - - eventing_v1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" - versioned "github.com/knative/eventing/pkg/client/clientset/versioned" - internalinterfaces "github.com/knative/eventing/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/knative/eventing/pkg/client/listers/eventing/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// SourceInformer provides access to a shared informer and lister for -// Sources. -type SourceInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.SourceLister -} - -type sourceInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewSourceInformer constructs a new informer for Source type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewSourceInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredSourceInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredSourceInformer constructs a new informer for Source type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredSourceInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.EventingV1alpha1().Sources(namespace).List(options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.EventingV1alpha1().Sources(namespace).Watch(options) - }, - }, - &eventing_v1alpha1.Source{}, - resyncPeriod, - indexers, - ) -} - -func (f *sourceInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredSourceInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *sourceInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&eventing_v1alpha1.Source{}, f.defaultInformer) -} - -func (f *sourceInformer) Lister() v1alpha1.SourceLister { - return v1alpha1.NewSourceLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/informers/externalversions/factory.go b/pkg/client/informers/externalversions/factory.go index adee6a64b79..0cde7d2cdd1 100644 --- a/pkg/client/informers/externalversions/factory.go +++ b/pkg/client/informers/externalversions/factory.go @@ -24,10 +24,7 @@ import ( time "time" versioned "github.com/knative/eventing/pkg/client/clientset/versioned" - channels "github.com/knative/eventing/pkg/client/informers/externalversions/channels" eventing "github.com/knative/eventing/pkg/client/informers/externalversions/eventing" - feeds "github.com/knative/eventing/pkg/client/informers/externalversions/feeds" - flows "github.com/knative/eventing/pkg/client/informers/externalversions/flows" internalinterfaces "github.com/knative/eventing/pkg/client/informers/externalversions/internalinterfaces" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" @@ -175,24 +172,9 @@ type SharedInformerFactory interface { ForResource(resource schema.GroupVersionResource) (GenericInformer, error) WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool - Channels() channels.Interface Eventing() eventing.Interface - Feeds() feeds.Interface - Flows() flows.Interface -} - -func (f *sharedInformerFactory) Channels() channels.Interface { - return channels.New(f, f.namespace, f.tweakListOptions) } func (f *sharedInformerFactory) Eventing() eventing.Interface { return eventing.New(f, f.namespace, f.tweakListOptions) } - -func (f *sharedInformerFactory) Feeds() feeds.Interface { - return feeds.New(f, f.namespace, f.tweakListOptions) -} - -func (f *sharedInformerFactory) Flows() flows.Interface { - return flows.New(f, f.namespace, f.tweakListOptions) -} diff --git a/pkg/client/informers/externalversions/feeds/interface.go b/pkg/client/informers/externalversions/feeds/interface.go deleted file mode 100644 index 92dd958b383..00000000000 --- a/pkg/client/informers/externalversions/feeds/interface.go +++ /dev/null @@ -1,46 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package feeds - -import ( - v1alpha1 "github.com/knative/eventing/pkg/client/informers/externalversions/feeds/v1alpha1" - internalinterfaces "github.com/knative/eventing/pkg/client/informers/externalversions/internalinterfaces" -) - -// Interface provides access to each of this group's versions. -type Interface interface { - // V1alpha1 provides access to shared informers for resources in V1alpha1. - V1alpha1() v1alpha1.Interface -} - -type group struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// V1alpha1 returns a new v1alpha1.Interface. -func (g *group) V1alpha1() v1alpha1.Interface { - return v1alpha1.New(g.factory, g.namespace, g.tweakListOptions) -} diff --git a/pkg/client/informers/externalversions/feeds/v1alpha1/clustereventsource.go b/pkg/client/informers/externalversions/feeds/v1alpha1/clustereventsource.go deleted file mode 100644 index fe59444d500..00000000000 --- a/pkg/client/informers/externalversions/feeds/v1alpha1/clustereventsource.go +++ /dev/null @@ -1,88 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - time "time" - - feeds_v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - versioned "github.com/knative/eventing/pkg/client/clientset/versioned" - internalinterfaces "github.com/knative/eventing/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/knative/eventing/pkg/client/listers/feeds/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// ClusterEventSourceInformer provides access to a shared informer and lister for -// ClusterEventSources. -type ClusterEventSourceInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.ClusterEventSourceLister -} - -type clusterEventSourceInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// NewClusterEventSourceInformer constructs a new informer for ClusterEventSource type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewClusterEventSourceInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredClusterEventSourceInformer(client, resyncPeriod, indexers, nil) -} - -// NewFilteredClusterEventSourceInformer constructs a new informer for ClusterEventSource type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredClusterEventSourceInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.FeedsV1alpha1().ClusterEventSources().List(options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.FeedsV1alpha1().ClusterEventSources().Watch(options) - }, - }, - &feeds_v1alpha1.ClusterEventSource{}, - resyncPeriod, - indexers, - ) -} - -func (f *clusterEventSourceInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredClusterEventSourceInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *clusterEventSourceInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&feeds_v1alpha1.ClusterEventSource{}, f.defaultInformer) -} - -func (f *clusterEventSourceInformer) Lister() v1alpha1.ClusterEventSourceLister { - return v1alpha1.NewClusterEventSourceLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/informers/externalversions/feeds/v1alpha1/clustereventtype.go b/pkg/client/informers/externalversions/feeds/v1alpha1/clustereventtype.go deleted file mode 100644 index 16dedce0e0a..00000000000 --- a/pkg/client/informers/externalversions/feeds/v1alpha1/clustereventtype.go +++ /dev/null @@ -1,88 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - time "time" - - feeds_v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - versioned "github.com/knative/eventing/pkg/client/clientset/versioned" - internalinterfaces "github.com/knative/eventing/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/knative/eventing/pkg/client/listers/feeds/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// ClusterEventTypeInformer provides access to a shared informer and lister for -// ClusterEventTypes. -type ClusterEventTypeInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.ClusterEventTypeLister -} - -type clusterEventTypeInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// NewClusterEventTypeInformer constructs a new informer for ClusterEventType type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewClusterEventTypeInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredClusterEventTypeInformer(client, resyncPeriod, indexers, nil) -} - -// NewFilteredClusterEventTypeInformer constructs a new informer for ClusterEventType type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredClusterEventTypeInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.FeedsV1alpha1().ClusterEventTypes().List(options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.FeedsV1alpha1().ClusterEventTypes().Watch(options) - }, - }, - &feeds_v1alpha1.ClusterEventType{}, - resyncPeriod, - indexers, - ) -} - -func (f *clusterEventTypeInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredClusterEventTypeInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *clusterEventTypeInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&feeds_v1alpha1.ClusterEventType{}, f.defaultInformer) -} - -func (f *clusterEventTypeInformer) Lister() v1alpha1.ClusterEventTypeLister { - return v1alpha1.NewClusterEventTypeLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/informers/externalversions/feeds/v1alpha1/eventsource.go b/pkg/client/informers/externalversions/feeds/v1alpha1/eventsource.go deleted file mode 100644 index 8a08e9918ec..00000000000 --- a/pkg/client/informers/externalversions/feeds/v1alpha1/eventsource.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - time "time" - - feeds_v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - versioned "github.com/knative/eventing/pkg/client/clientset/versioned" - internalinterfaces "github.com/knative/eventing/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/knative/eventing/pkg/client/listers/feeds/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// EventSourceInformer provides access to a shared informer and lister for -// EventSources. -type EventSourceInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.EventSourceLister -} - -type eventSourceInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewEventSourceInformer constructs a new informer for EventSource type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewEventSourceInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredEventSourceInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredEventSourceInformer constructs a new informer for EventSource type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredEventSourceInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.FeedsV1alpha1().EventSources(namespace).List(options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.FeedsV1alpha1().EventSources(namespace).Watch(options) - }, - }, - &feeds_v1alpha1.EventSource{}, - resyncPeriod, - indexers, - ) -} - -func (f *eventSourceInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredEventSourceInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *eventSourceInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&feeds_v1alpha1.EventSource{}, f.defaultInformer) -} - -func (f *eventSourceInformer) Lister() v1alpha1.EventSourceLister { - return v1alpha1.NewEventSourceLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/informers/externalversions/feeds/v1alpha1/eventtype.go b/pkg/client/informers/externalversions/feeds/v1alpha1/eventtype.go deleted file mode 100644 index a31e490ed13..00000000000 --- a/pkg/client/informers/externalversions/feeds/v1alpha1/eventtype.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - time "time" - - feeds_v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - versioned "github.com/knative/eventing/pkg/client/clientset/versioned" - internalinterfaces "github.com/knative/eventing/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/knative/eventing/pkg/client/listers/feeds/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// EventTypeInformer provides access to a shared informer and lister for -// EventTypes. -type EventTypeInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.EventTypeLister -} - -type eventTypeInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewEventTypeInformer constructs a new informer for EventType type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewEventTypeInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredEventTypeInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredEventTypeInformer constructs a new informer for EventType type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredEventTypeInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.FeedsV1alpha1().EventTypes(namespace).List(options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.FeedsV1alpha1().EventTypes(namespace).Watch(options) - }, - }, - &feeds_v1alpha1.EventType{}, - resyncPeriod, - indexers, - ) -} - -func (f *eventTypeInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredEventTypeInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *eventTypeInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&feeds_v1alpha1.EventType{}, f.defaultInformer) -} - -func (f *eventTypeInformer) Lister() v1alpha1.EventTypeLister { - return v1alpha1.NewEventTypeLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/informers/externalversions/feeds/v1alpha1/feed.go b/pkg/client/informers/externalversions/feeds/v1alpha1/feed.go deleted file mode 100644 index a4397c4c71e..00000000000 --- a/pkg/client/informers/externalversions/feeds/v1alpha1/feed.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - time "time" - - feeds_v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - versioned "github.com/knative/eventing/pkg/client/clientset/versioned" - internalinterfaces "github.com/knative/eventing/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/knative/eventing/pkg/client/listers/feeds/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// FeedInformer provides access to a shared informer and lister for -// Feeds. -type FeedInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.FeedLister -} - -type feedInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewFeedInformer constructs a new informer for Feed type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFeedInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredFeedInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredFeedInformer constructs a new informer for Feed type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredFeedInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.FeedsV1alpha1().Feeds(namespace).List(options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.FeedsV1alpha1().Feeds(namespace).Watch(options) - }, - }, - &feeds_v1alpha1.Feed{}, - resyncPeriod, - indexers, - ) -} - -func (f *feedInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredFeedInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *feedInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&feeds_v1alpha1.Feed{}, f.defaultInformer) -} - -func (f *feedInformer) Lister() v1alpha1.FeedLister { - return v1alpha1.NewFeedLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/informers/externalversions/feeds/v1alpha1/interface.go b/pkg/client/informers/externalversions/feeds/v1alpha1/interface.go deleted file mode 100644 index b514cc2f3d7..00000000000 --- a/pkg/client/informers/externalversions/feeds/v1alpha1/interface.go +++ /dev/null @@ -1,73 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - internalinterfaces "github.com/knative/eventing/pkg/client/informers/externalversions/internalinterfaces" -) - -// Interface provides access to all the informers in this group version. -type Interface interface { - // ClusterEventSources returns a ClusterEventSourceInformer. - ClusterEventSources() ClusterEventSourceInformer - // ClusterEventTypes returns a ClusterEventTypeInformer. - ClusterEventTypes() ClusterEventTypeInformer - // EventSources returns a EventSourceInformer. - EventSources() EventSourceInformer - // EventTypes returns a EventTypeInformer. - EventTypes() EventTypeInformer - // Feeds returns a FeedInformer. - Feeds() FeedInformer -} - -type version struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// ClusterEventSources returns a ClusterEventSourceInformer. -func (v *version) ClusterEventSources() ClusterEventSourceInformer { - return &clusterEventSourceInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} -} - -// ClusterEventTypes returns a ClusterEventTypeInformer. -func (v *version) ClusterEventTypes() ClusterEventTypeInformer { - return &clusterEventTypeInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} -} - -// EventSources returns a EventSourceInformer. -func (v *version) EventSources() EventSourceInformer { - return &eventSourceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// EventTypes returns a EventTypeInformer. -func (v *version) EventTypes() EventTypeInformer { - return &eventTypeInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// Feeds returns a FeedInformer. -func (v *version) Feeds() FeedInformer { - return &feedInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} diff --git a/pkg/client/informers/externalversions/flows/interface.go b/pkg/client/informers/externalversions/flows/interface.go deleted file mode 100644 index 5534891ac8e..00000000000 --- a/pkg/client/informers/externalversions/flows/interface.go +++ /dev/null @@ -1,46 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package flows - -import ( - v1alpha1 "github.com/knative/eventing/pkg/client/informers/externalversions/flows/v1alpha1" - internalinterfaces "github.com/knative/eventing/pkg/client/informers/externalversions/internalinterfaces" -) - -// Interface provides access to each of this group's versions. -type Interface interface { - // V1alpha1 provides access to shared informers for resources in V1alpha1. - V1alpha1() v1alpha1.Interface -} - -type group struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// V1alpha1 returns a new v1alpha1.Interface. -func (g *group) V1alpha1() v1alpha1.Interface { - return v1alpha1.New(g.factory, g.namespace, g.tweakListOptions) -} diff --git a/pkg/client/informers/externalversions/flows/v1alpha1/flow.go b/pkg/client/informers/externalversions/flows/v1alpha1/flow.go deleted file mode 100644 index 19a5b8cf9ce..00000000000 --- a/pkg/client/informers/externalversions/flows/v1alpha1/flow.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - time "time" - - flows_v1alpha1 "github.com/knative/eventing/pkg/apis/flows/v1alpha1" - versioned "github.com/knative/eventing/pkg/client/clientset/versioned" - internalinterfaces "github.com/knative/eventing/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/knative/eventing/pkg/client/listers/flows/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// FlowInformer provides access to a shared informer and lister for -// Flows. -type FlowInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.FlowLister -} - -type flowInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewFlowInformer constructs a new informer for Flow type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFlowInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredFlowInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredFlowInformer constructs a new informer for Flow type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredFlowInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.FlowsV1alpha1().Flows(namespace).List(options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.FlowsV1alpha1().Flows(namespace).Watch(options) - }, - }, - &flows_v1alpha1.Flow{}, - resyncPeriod, - indexers, - ) -} - -func (f *flowInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredFlowInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *flowInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&flows_v1alpha1.Flow{}, f.defaultInformer) -} - -func (f *flowInformer) Lister() v1alpha1.FlowLister { - return v1alpha1.NewFlowLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/informers/externalversions/flows/v1alpha1/interface.go b/pkg/client/informers/externalversions/flows/v1alpha1/interface.go deleted file mode 100644 index dceacfb7090..00000000000 --- a/pkg/client/informers/externalversions/flows/v1alpha1/interface.go +++ /dev/null @@ -1,45 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - internalinterfaces "github.com/knative/eventing/pkg/client/informers/externalversions/internalinterfaces" -) - -// Interface provides access to all the informers in this group version. -type Interface interface { - // Flows returns a FlowInformer. - Flows() FlowInformer -} - -type version struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// Flows returns a FlowInformer. -func (v *version) Flows() FlowInformer { - return &flowInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} diff --git a/pkg/client/informers/externalversions/generic.go b/pkg/client/informers/externalversions/generic.go index 64978278fda..eb07d8f78ef 100644 --- a/pkg/client/informers/externalversions/generic.go +++ b/pkg/client/informers/externalversions/generic.go @@ -21,10 +21,7 @@ package externalversions import ( "fmt" - v1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - eventing_v1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" - feeds_v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - flows_v1alpha1 "github.com/knative/eventing/pkg/apis/flows/v1alpha1" + v1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" schema "k8s.io/apimachinery/pkg/runtime/schema" cache "k8s.io/client-go/tools/cache" ) @@ -55,42 +52,14 @@ func (f *genericInformer) Lister() cache.GenericLister { // TODO extend this to unknown resources with a client pool func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) { switch resource { - // Group=channels.knative.dev, Version=v1alpha1 - case v1alpha1.SchemeGroupVersion.WithResource("buses"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Channels().V1alpha1().Buses().Informer()}, nil + // Group=eventing.knative.dev, Version=v1alpha1 case v1alpha1.SchemeGroupVersion.WithResource("channels"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Channels().V1alpha1().Channels().Informer()}, nil - case v1alpha1.SchemeGroupVersion.WithResource("clusterbuses"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Channels().V1alpha1().ClusterBuses().Informer()}, nil - case v1alpha1.SchemeGroupVersion.WithResource("subscriptions"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Channels().V1alpha1().Subscriptions().Informer()}, nil - - // Group=eventing.knative.dev, Version=v1alpha1 - case eventing_v1alpha1.SchemeGroupVersion.WithResource("channels"): return &genericInformer{resource: resource.GroupResource(), informer: f.Eventing().V1alpha1().Channels().Informer()}, nil - case eventing_v1alpha1.SchemeGroupVersion.WithResource("clusterprovisioners"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Eventing().V1alpha1().ClusterProvisioners().Informer()}, nil - case eventing_v1alpha1.SchemeGroupVersion.WithResource("sources"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Eventing().V1alpha1().Sources().Informer()}, nil - case eventing_v1alpha1.SchemeGroupVersion.WithResource("subscriptions"): + case v1alpha1.SchemeGroupVersion.WithResource("clusterchannelprovisioners"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Eventing().V1alpha1().ClusterChannelProvisioners().Informer()}, nil + case v1alpha1.SchemeGroupVersion.WithResource("subscriptions"): return &genericInformer{resource: resource.GroupResource(), informer: f.Eventing().V1alpha1().Subscriptions().Informer()}, nil - // Group=feeds.knative.dev, Version=v1alpha1 - case feeds_v1alpha1.SchemeGroupVersion.WithResource("clustereventsources"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Feeds().V1alpha1().ClusterEventSources().Informer()}, nil - case feeds_v1alpha1.SchemeGroupVersion.WithResource("clustereventtypes"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Feeds().V1alpha1().ClusterEventTypes().Informer()}, nil - case feeds_v1alpha1.SchemeGroupVersion.WithResource("eventsources"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Feeds().V1alpha1().EventSources().Informer()}, nil - case feeds_v1alpha1.SchemeGroupVersion.WithResource("eventtypes"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Feeds().V1alpha1().EventTypes().Informer()}, nil - case feeds_v1alpha1.SchemeGroupVersion.WithResource("feeds"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Feeds().V1alpha1().Feeds().Informer()}, nil - - // Group=flows.knative.dev, Version=v1alpha1 - case flows_v1alpha1.SchemeGroupVersion.WithResource("flows"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Flows().V1alpha1().Flows().Informer()}, nil - } return nil, fmt.Errorf("no informer found for %v", resource) diff --git a/pkg/client/listers/channels/v1alpha1/bus.go b/pkg/client/listers/channels/v1alpha1/bus.go deleted file mode 100644 index 52d0d164e29..00000000000 --- a/pkg/client/listers/channels/v1alpha1/bus.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// BusLister helps list Buses. -type BusLister interface { - // List lists all Buses in the indexer. - List(selector labels.Selector) (ret []*v1alpha1.Bus, err error) - // Buses returns an object that can list and get Buses. - Buses(namespace string) BusNamespaceLister - BusListerExpansion -} - -// busLister implements the BusLister interface. -type busLister struct { - indexer cache.Indexer -} - -// NewBusLister returns a new BusLister. -func NewBusLister(indexer cache.Indexer) BusLister { - return &busLister{indexer: indexer} -} - -// List lists all Buses in the indexer. -func (s *busLister) List(selector labels.Selector) (ret []*v1alpha1.Bus, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Bus)) - }) - return ret, err -} - -// Buses returns an object that can list and get Buses. -func (s *busLister) Buses(namespace string) BusNamespaceLister { - return busNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// BusNamespaceLister helps list and get Buses. -type BusNamespaceLister interface { - // List lists all Buses in the indexer for a given namespace. - List(selector labels.Selector) (ret []*v1alpha1.Bus, err error) - // Get retrieves the Bus from the indexer for a given namespace and name. - Get(name string) (*v1alpha1.Bus, error) - BusNamespaceListerExpansion -} - -// busNamespaceLister implements the BusNamespaceLister -// interface. -type busNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all Buses in the indexer for a given namespace. -func (s busNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Bus, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Bus)) - }) - return ret, err -} - -// Get retrieves the Bus from the indexer for a given namespace and name. -func (s busNamespaceLister) Get(name string) (*v1alpha1.Bus, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("bus"), name) - } - return obj.(*v1alpha1.Bus), nil -} diff --git a/pkg/client/listers/channels/v1alpha1/channel.go b/pkg/client/listers/channels/v1alpha1/channel.go deleted file mode 100644 index 3ea15686cfa..00000000000 --- a/pkg/client/listers/channels/v1alpha1/channel.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// ChannelLister helps list Channels. -type ChannelLister interface { - // List lists all Channels in the indexer. - List(selector labels.Selector) (ret []*v1alpha1.Channel, err error) - // Channels returns an object that can list and get Channels. - Channels(namespace string) ChannelNamespaceLister - ChannelListerExpansion -} - -// channelLister implements the ChannelLister interface. -type channelLister struct { - indexer cache.Indexer -} - -// NewChannelLister returns a new ChannelLister. -func NewChannelLister(indexer cache.Indexer) ChannelLister { - return &channelLister{indexer: indexer} -} - -// List lists all Channels in the indexer. -func (s *channelLister) List(selector labels.Selector) (ret []*v1alpha1.Channel, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Channel)) - }) - return ret, err -} - -// Channels returns an object that can list and get Channels. -func (s *channelLister) Channels(namespace string) ChannelNamespaceLister { - return channelNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// ChannelNamespaceLister helps list and get Channels. -type ChannelNamespaceLister interface { - // List lists all Channels in the indexer for a given namespace. - List(selector labels.Selector) (ret []*v1alpha1.Channel, err error) - // Get retrieves the Channel from the indexer for a given namespace and name. - Get(name string) (*v1alpha1.Channel, error) - ChannelNamespaceListerExpansion -} - -// channelNamespaceLister implements the ChannelNamespaceLister -// interface. -type channelNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all Channels in the indexer for a given namespace. -func (s channelNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Channel, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Channel)) - }) - return ret, err -} - -// Get retrieves the Channel from the indexer for a given namespace and name. -func (s channelNamespaceLister) Get(name string) (*v1alpha1.Channel, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("channel"), name) - } - return obj.(*v1alpha1.Channel), nil -} diff --git a/pkg/client/listers/channels/v1alpha1/clusterbus.go b/pkg/client/listers/channels/v1alpha1/clusterbus.go deleted file mode 100644 index 5415692f299..00000000000 --- a/pkg/client/listers/channels/v1alpha1/clusterbus.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// ClusterBusLister helps list ClusterBuses. -type ClusterBusLister interface { - // List lists all ClusterBuses in the indexer. - List(selector labels.Selector) (ret []*v1alpha1.ClusterBus, err error) - // Get retrieves the ClusterBus from the index for a given name. - Get(name string) (*v1alpha1.ClusterBus, error) - ClusterBusListerExpansion -} - -// clusterBusLister implements the ClusterBusLister interface. -type clusterBusLister struct { - indexer cache.Indexer -} - -// NewClusterBusLister returns a new ClusterBusLister. -func NewClusterBusLister(indexer cache.Indexer) ClusterBusLister { - return &clusterBusLister{indexer: indexer} -} - -// List lists all ClusterBuses in the indexer. -func (s *clusterBusLister) List(selector labels.Selector) (ret []*v1alpha1.ClusterBus, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.ClusterBus)) - }) - return ret, err -} - -// Get retrieves the ClusterBus from the index for a given name. -func (s *clusterBusLister) Get(name string) (*v1alpha1.ClusterBus, error) { - obj, exists, err := s.indexer.GetByKey(name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("clusterbus"), name) - } - return obj.(*v1alpha1.ClusterBus), nil -} diff --git a/pkg/client/listers/channels/v1alpha1/expansion_generated.go b/pkg/client/listers/channels/v1alpha1/expansion_generated.go deleted file mode 100644 index 96d1fd82104..00000000000 --- a/pkg/client/listers/channels/v1alpha1/expansion_generated.go +++ /dev/null @@ -1,47 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -// BusListerExpansion allows custom methods to be added to -// BusLister. -type BusListerExpansion interface{} - -// BusNamespaceListerExpansion allows custom methods to be added to -// BusNamespaceLister. -type BusNamespaceListerExpansion interface{} - -// ChannelListerExpansion allows custom methods to be added to -// ChannelLister. -type ChannelListerExpansion interface{} - -// ChannelNamespaceListerExpansion allows custom methods to be added to -// ChannelNamespaceLister. -type ChannelNamespaceListerExpansion interface{} - -// ClusterBusListerExpansion allows custom methods to be added to -// ClusterBusLister. -type ClusterBusListerExpansion interface{} - -// SubscriptionListerExpansion allows custom methods to be added to -// SubscriptionLister. -type SubscriptionListerExpansion interface{} - -// SubscriptionNamespaceListerExpansion allows custom methods to be added to -// SubscriptionNamespaceLister. -type SubscriptionNamespaceListerExpansion interface{} diff --git a/pkg/client/listers/channels/v1alpha1/subscription.go b/pkg/client/listers/channels/v1alpha1/subscription.go deleted file mode 100644 index b910f451ede..00000000000 --- a/pkg/client/listers/channels/v1alpha1/subscription.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// SubscriptionLister helps list Subscriptions. -type SubscriptionLister interface { - // List lists all Subscriptions in the indexer. - List(selector labels.Selector) (ret []*v1alpha1.Subscription, err error) - // Subscriptions returns an object that can list and get Subscriptions. - Subscriptions(namespace string) SubscriptionNamespaceLister - SubscriptionListerExpansion -} - -// subscriptionLister implements the SubscriptionLister interface. -type subscriptionLister struct { - indexer cache.Indexer -} - -// NewSubscriptionLister returns a new SubscriptionLister. -func NewSubscriptionLister(indexer cache.Indexer) SubscriptionLister { - return &subscriptionLister{indexer: indexer} -} - -// List lists all Subscriptions in the indexer. -func (s *subscriptionLister) List(selector labels.Selector) (ret []*v1alpha1.Subscription, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Subscription)) - }) - return ret, err -} - -// Subscriptions returns an object that can list and get Subscriptions. -func (s *subscriptionLister) Subscriptions(namespace string) SubscriptionNamespaceLister { - return subscriptionNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// SubscriptionNamespaceLister helps list and get Subscriptions. -type SubscriptionNamespaceLister interface { - // List lists all Subscriptions in the indexer for a given namespace. - List(selector labels.Selector) (ret []*v1alpha1.Subscription, err error) - // Get retrieves the Subscription from the indexer for a given namespace and name. - Get(name string) (*v1alpha1.Subscription, error) - SubscriptionNamespaceListerExpansion -} - -// subscriptionNamespaceLister implements the SubscriptionNamespaceLister -// interface. -type subscriptionNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all Subscriptions in the indexer for a given namespace. -func (s subscriptionNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Subscription, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Subscription)) - }) - return ret, err -} - -// Get retrieves the Subscription from the indexer for a given namespace and name. -func (s subscriptionNamespaceLister) Get(name string) (*v1alpha1.Subscription, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("subscription"), name) - } - return obj.(*v1alpha1.Subscription), nil -} diff --git a/pkg/client/listers/eventing/v1alpha1/clusterchannelprovisioner.go b/pkg/client/listers/eventing/v1alpha1/clusterchannelprovisioner.go new file mode 100644 index 00000000000..daa65a79b81 --- /dev/null +++ b/pkg/client/listers/eventing/v1alpha1/clusterchannelprovisioner.go @@ -0,0 +1,65 @@ +/* +Copyright 2018 The Knative 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. +*/ + +// Code generated by lister-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + v1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" +) + +// ClusterChannelProvisionerLister helps list ClusterChannelProvisioners. +type ClusterChannelProvisionerLister interface { + // List lists all ClusterChannelProvisioners in the indexer. + List(selector labels.Selector) (ret []*v1alpha1.ClusterChannelProvisioner, err error) + // Get retrieves the ClusterChannelProvisioner from the index for a given name. + Get(name string) (*v1alpha1.ClusterChannelProvisioner, error) + ClusterChannelProvisionerListerExpansion +} + +// clusterChannelProvisionerLister implements the ClusterChannelProvisionerLister interface. +type clusterChannelProvisionerLister struct { + indexer cache.Indexer +} + +// NewClusterChannelProvisionerLister returns a new ClusterChannelProvisionerLister. +func NewClusterChannelProvisionerLister(indexer cache.Indexer) ClusterChannelProvisionerLister { + return &clusterChannelProvisionerLister{indexer: indexer} +} + +// List lists all ClusterChannelProvisioners in the indexer. +func (s *clusterChannelProvisionerLister) List(selector labels.Selector) (ret []*v1alpha1.ClusterChannelProvisioner, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1alpha1.ClusterChannelProvisioner)) + }) + return ret, err +} + +// Get retrieves the ClusterChannelProvisioner from the index for a given name. +func (s *clusterChannelProvisionerLister) Get(name string) (*v1alpha1.ClusterChannelProvisioner, error) { + obj, exists, err := s.indexer.GetByKey(name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1alpha1.Resource("clusterchannelprovisioner"), name) + } + return obj.(*v1alpha1.ClusterChannelProvisioner), nil +} diff --git a/pkg/client/listers/eventing/v1alpha1/clusterprovisioner.go b/pkg/client/listers/eventing/v1alpha1/clusterprovisioner.go deleted file mode 100644 index f380ac06d1b..00000000000 --- a/pkg/client/listers/eventing/v1alpha1/clusterprovisioner.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// ClusterProvisionerLister helps list ClusterProvisioners. -type ClusterProvisionerLister interface { - // List lists all ClusterProvisioners in the indexer. - List(selector labels.Selector) (ret []*v1alpha1.ClusterProvisioner, err error) - // Get retrieves the ClusterProvisioner from the index for a given name. - Get(name string) (*v1alpha1.ClusterProvisioner, error) - ClusterProvisionerListerExpansion -} - -// clusterProvisionerLister implements the ClusterProvisionerLister interface. -type clusterProvisionerLister struct { - indexer cache.Indexer -} - -// NewClusterProvisionerLister returns a new ClusterProvisionerLister. -func NewClusterProvisionerLister(indexer cache.Indexer) ClusterProvisionerLister { - return &clusterProvisionerLister{indexer: indexer} -} - -// List lists all ClusterProvisioners in the indexer. -func (s *clusterProvisionerLister) List(selector labels.Selector) (ret []*v1alpha1.ClusterProvisioner, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.ClusterProvisioner)) - }) - return ret, err -} - -// Get retrieves the ClusterProvisioner from the index for a given name. -func (s *clusterProvisionerLister) Get(name string) (*v1alpha1.ClusterProvisioner, error) { - obj, exists, err := s.indexer.GetByKey(name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("clusterprovisioner"), name) - } - return obj.(*v1alpha1.ClusterProvisioner), nil -} diff --git a/pkg/client/listers/eventing/v1alpha1/expansion_generated.go b/pkg/client/listers/eventing/v1alpha1/expansion_generated.go index f3854a6804d..ce1c8af2399 100644 --- a/pkg/client/listers/eventing/v1alpha1/expansion_generated.go +++ b/pkg/client/listers/eventing/v1alpha1/expansion_generated.go @@ -26,17 +26,9 @@ type ChannelListerExpansion interface{} // ChannelNamespaceLister. type ChannelNamespaceListerExpansion interface{} -// ClusterProvisionerListerExpansion allows custom methods to be added to -// ClusterProvisionerLister. -type ClusterProvisionerListerExpansion interface{} - -// SourceListerExpansion allows custom methods to be added to -// SourceLister. -type SourceListerExpansion interface{} - -// SourceNamespaceListerExpansion allows custom methods to be added to -// SourceNamespaceLister. -type SourceNamespaceListerExpansion interface{} +// ClusterChannelProvisionerListerExpansion allows custom methods to be added to +// ClusterChannelProvisionerLister. +type ClusterChannelProvisionerListerExpansion interface{} // SubscriptionListerExpansion allows custom methods to be added to // SubscriptionLister. diff --git a/pkg/client/listers/eventing/v1alpha1/source.go b/pkg/client/listers/eventing/v1alpha1/source.go deleted file mode 100644 index ec5c3a667ba..00000000000 --- a/pkg/client/listers/eventing/v1alpha1/source.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// SourceLister helps list Sources. -type SourceLister interface { - // List lists all Sources in the indexer. - List(selector labels.Selector) (ret []*v1alpha1.Source, err error) - // Sources returns an object that can list and get Sources. - Sources(namespace string) SourceNamespaceLister - SourceListerExpansion -} - -// sourceLister implements the SourceLister interface. -type sourceLister struct { - indexer cache.Indexer -} - -// NewSourceLister returns a new SourceLister. -func NewSourceLister(indexer cache.Indexer) SourceLister { - return &sourceLister{indexer: indexer} -} - -// List lists all Sources in the indexer. -func (s *sourceLister) List(selector labels.Selector) (ret []*v1alpha1.Source, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Source)) - }) - return ret, err -} - -// Sources returns an object that can list and get Sources. -func (s *sourceLister) Sources(namespace string) SourceNamespaceLister { - return sourceNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// SourceNamespaceLister helps list and get Sources. -type SourceNamespaceLister interface { - // List lists all Sources in the indexer for a given namespace. - List(selector labels.Selector) (ret []*v1alpha1.Source, err error) - // Get retrieves the Source from the indexer for a given namespace and name. - Get(name string) (*v1alpha1.Source, error) - SourceNamespaceListerExpansion -} - -// sourceNamespaceLister implements the SourceNamespaceLister -// interface. -type sourceNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all Sources in the indexer for a given namespace. -func (s sourceNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Source, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Source)) - }) - return ret, err -} - -// Get retrieves the Source from the indexer for a given namespace and name. -func (s sourceNamespaceLister) Get(name string) (*v1alpha1.Source, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("source"), name) - } - return obj.(*v1alpha1.Source), nil -} diff --git a/pkg/client/listers/feeds/v1alpha1/clustereventsource.go b/pkg/client/listers/feeds/v1alpha1/clustereventsource.go deleted file mode 100644 index 53211b2539c..00000000000 --- a/pkg/client/listers/feeds/v1alpha1/clustereventsource.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// ClusterEventSourceLister helps list ClusterEventSources. -type ClusterEventSourceLister interface { - // List lists all ClusterEventSources in the indexer. - List(selector labels.Selector) (ret []*v1alpha1.ClusterEventSource, err error) - // Get retrieves the ClusterEventSource from the index for a given name. - Get(name string) (*v1alpha1.ClusterEventSource, error) - ClusterEventSourceListerExpansion -} - -// clusterEventSourceLister implements the ClusterEventSourceLister interface. -type clusterEventSourceLister struct { - indexer cache.Indexer -} - -// NewClusterEventSourceLister returns a new ClusterEventSourceLister. -func NewClusterEventSourceLister(indexer cache.Indexer) ClusterEventSourceLister { - return &clusterEventSourceLister{indexer: indexer} -} - -// List lists all ClusterEventSources in the indexer. -func (s *clusterEventSourceLister) List(selector labels.Selector) (ret []*v1alpha1.ClusterEventSource, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.ClusterEventSource)) - }) - return ret, err -} - -// Get retrieves the ClusterEventSource from the index for a given name. -func (s *clusterEventSourceLister) Get(name string) (*v1alpha1.ClusterEventSource, error) { - obj, exists, err := s.indexer.GetByKey(name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("clustereventsource"), name) - } - return obj.(*v1alpha1.ClusterEventSource), nil -} diff --git a/pkg/client/listers/feeds/v1alpha1/clustereventtype.go b/pkg/client/listers/feeds/v1alpha1/clustereventtype.go deleted file mode 100644 index 1fd170b69af..00000000000 --- a/pkg/client/listers/feeds/v1alpha1/clustereventtype.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// ClusterEventTypeLister helps list ClusterEventTypes. -type ClusterEventTypeLister interface { - // List lists all ClusterEventTypes in the indexer. - List(selector labels.Selector) (ret []*v1alpha1.ClusterEventType, err error) - // Get retrieves the ClusterEventType from the index for a given name. - Get(name string) (*v1alpha1.ClusterEventType, error) - ClusterEventTypeListerExpansion -} - -// clusterEventTypeLister implements the ClusterEventTypeLister interface. -type clusterEventTypeLister struct { - indexer cache.Indexer -} - -// NewClusterEventTypeLister returns a new ClusterEventTypeLister. -func NewClusterEventTypeLister(indexer cache.Indexer) ClusterEventTypeLister { - return &clusterEventTypeLister{indexer: indexer} -} - -// List lists all ClusterEventTypes in the indexer. -func (s *clusterEventTypeLister) List(selector labels.Selector) (ret []*v1alpha1.ClusterEventType, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.ClusterEventType)) - }) - return ret, err -} - -// Get retrieves the ClusterEventType from the index for a given name. -func (s *clusterEventTypeLister) Get(name string) (*v1alpha1.ClusterEventType, error) { - obj, exists, err := s.indexer.GetByKey(name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("clustereventtype"), name) - } - return obj.(*v1alpha1.ClusterEventType), nil -} diff --git a/pkg/client/listers/feeds/v1alpha1/eventsource.go b/pkg/client/listers/feeds/v1alpha1/eventsource.go deleted file mode 100644 index 15ef8d8fc0b..00000000000 --- a/pkg/client/listers/feeds/v1alpha1/eventsource.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// EventSourceLister helps list EventSources. -type EventSourceLister interface { - // List lists all EventSources in the indexer. - List(selector labels.Selector) (ret []*v1alpha1.EventSource, err error) - // EventSources returns an object that can list and get EventSources. - EventSources(namespace string) EventSourceNamespaceLister - EventSourceListerExpansion -} - -// eventSourceLister implements the EventSourceLister interface. -type eventSourceLister struct { - indexer cache.Indexer -} - -// NewEventSourceLister returns a new EventSourceLister. -func NewEventSourceLister(indexer cache.Indexer) EventSourceLister { - return &eventSourceLister{indexer: indexer} -} - -// List lists all EventSources in the indexer. -func (s *eventSourceLister) List(selector labels.Selector) (ret []*v1alpha1.EventSource, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.EventSource)) - }) - return ret, err -} - -// EventSources returns an object that can list and get EventSources. -func (s *eventSourceLister) EventSources(namespace string) EventSourceNamespaceLister { - return eventSourceNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// EventSourceNamespaceLister helps list and get EventSources. -type EventSourceNamespaceLister interface { - // List lists all EventSources in the indexer for a given namespace. - List(selector labels.Selector) (ret []*v1alpha1.EventSource, err error) - // Get retrieves the EventSource from the indexer for a given namespace and name. - Get(name string) (*v1alpha1.EventSource, error) - EventSourceNamespaceListerExpansion -} - -// eventSourceNamespaceLister implements the EventSourceNamespaceLister -// interface. -type eventSourceNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all EventSources in the indexer for a given namespace. -func (s eventSourceNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.EventSource, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.EventSource)) - }) - return ret, err -} - -// Get retrieves the EventSource from the indexer for a given namespace and name. -func (s eventSourceNamespaceLister) Get(name string) (*v1alpha1.EventSource, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("eventsource"), name) - } - return obj.(*v1alpha1.EventSource), nil -} diff --git a/pkg/client/listers/feeds/v1alpha1/eventtype.go b/pkg/client/listers/feeds/v1alpha1/eventtype.go deleted file mode 100644 index 9dda5741959..00000000000 --- a/pkg/client/listers/feeds/v1alpha1/eventtype.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// EventTypeLister helps list EventTypes. -type EventTypeLister interface { - // List lists all EventTypes in the indexer. - List(selector labels.Selector) (ret []*v1alpha1.EventType, err error) - // EventTypes returns an object that can list and get EventTypes. - EventTypes(namespace string) EventTypeNamespaceLister - EventTypeListerExpansion -} - -// eventTypeLister implements the EventTypeLister interface. -type eventTypeLister struct { - indexer cache.Indexer -} - -// NewEventTypeLister returns a new EventTypeLister. -func NewEventTypeLister(indexer cache.Indexer) EventTypeLister { - return &eventTypeLister{indexer: indexer} -} - -// List lists all EventTypes in the indexer. -func (s *eventTypeLister) List(selector labels.Selector) (ret []*v1alpha1.EventType, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.EventType)) - }) - return ret, err -} - -// EventTypes returns an object that can list and get EventTypes. -func (s *eventTypeLister) EventTypes(namespace string) EventTypeNamespaceLister { - return eventTypeNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// EventTypeNamespaceLister helps list and get EventTypes. -type EventTypeNamespaceLister interface { - // List lists all EventTypes in the indexer for a given namespace. - List(selector labels.Selector) (ret []*v1alpha1.EventType, err error) - // Get retrieves the EventType from the indexer for a given namespace and name. - Get(name string) (*v1alpha1.EventType, error) - EventTypeNamespaceListerExpansion -} - -// eventTypeNamespaceLister implements the EventTypeNamespaceLister -// interface. -type eventTypeNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all EventTypes in the indexer for a given namespace. -func (s eventTypeNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.EventType, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.EventType)) - }) - return ret, err -} - -// Get retrieves the EventType from the indexer for a given namespace and name. -func (s eventTypeNamespaceLister) Get(name string) (*v1alpha1.EventType, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("eventtype"), name) - } - return obj.(*v1alpha1.EventType), nil -} diff --git a/pkg/client/listers/feeds/v1alpha1/expansion_generated.go b/pkg/client/listers/feeds/v1alpha1/expansion_generated.go deleted file mode 100644 index 6a7bb9bd92f..00000000000 --- a/pkg/client/listers/feeds/v1alpha1/expansion_generated.go +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -// ClusterEventSourceListerExpansion allows custom methods to be added to -// ClusterEventSourceLister. -type ClusterEventSourceListerExpansion interface{} - -// ClusterEventTypeListerExpansion allows custom methods to be added to -// ClusterEventTypeLister. -type ClusterEventTypeListerExpansion interface{} - -// EventSourceListerExpansion allows custom methods to be added to -// EventSourceLister. -type EventSourceListerExpansion interface{} - -// EventSourceNamespaceListerExpansion allows custom methods to be added to -// EventSourceNamespaceLister. -type EventSourceNamespaceListerExpansion interface{} - -// EventTypeListerExpansion allows custom methods to be added to -// EventTypeLister. -type EventTypeListerExpansion interface{} - -// EventTypeNamespaceListerExpansion allows custom methods to be added to -// EventTypeNamespaceLister. -type EventTypeNamespaceListerExpansion interface{} - -// FeedListerExpansion allows custom methods to be added to -// FeedLister. -type FeedListerExpansion interface{} - -// FeedNamespaceListerExpansion allows custom methods to be added to -// FeedNamespaceLister. -type FeedNamespaceListerExpansion interface{} diff --git a/pkg/client/listers/feeds/v1alpha1/feed.go b/pkg/client/listers/feeds/v1alpha1/feed.go deleted file mode 100644 index bb55a0740b9..00000000000 --- a/pkg/client/listers/feeds/v1alpha1/feed.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// FeedLister helps list Feeds. -type FeedLister interface { - // List lists all Feeds in the indexer. - List(selector labels.Selector) (ret []*v1alpha1.Feed, err error) - // Feeds returns an object that can list and get Feeds. - Feeds(namespace string) FeedNamespaceLister - FeedListerExpansion -} - -// feedLister implements the FeedLister interface. -type feedLister struct { - indexer cache.Indexer -} - -// NewFeedLister returns a new FeedLister. -func NewFeedLister(indexer cache.Indexer) FeedLister { - return &feedLister{indexer: indexer} -} - -// List lists all Feeds in the indexer. -func (s *feedLister) List(selector labels.Selector) (ret []*v1alpha1.Feed, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Feed)) - }) - return ret, err -} - -// Feeds returns an object that can list and get Feeds. -func (s *feedLister) Feeds(namespace string) FeedNamespaceLister { - return feedNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// FeedNamespaceLister helps list and get Feeds. -type FeedNamespaceLister interface { - // List lists all Feeds in the indexer for a given namespace. - List(selector labels.Selector) (ret []*v1alpha1.Feed, err error) - // Get retrieves the Feed from the indexer for a given namespace and name. - Get(name string) (*v1alpha1.Feed, error) - FeedNamespaceListerExpansion -} - -// feedNamespaceLister implements the FeedNamespaceLister -// interface. -type feedNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all Feeds in the indexer for a given namespace. -func (s feedNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Feed, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Feed)) - }) - return ret, err -} - -// Get retrieves the Feed from the indexer for a given namespace and name. -func (s feedNamespaceLister) Get(name string) (*v1alpha1.Feed, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("feed"), name) - } - return obj.(*v1alpha1.Feed), nil -} diff --git a/pkg/client/listers/flows/v1alpha1/expansion_generated.go b/pkg/client/listers/flows/v1alpha1/expansion_generated.go deleted file mode 100644 index cd115a41fa4..00000000000 --- a/pkg/client/listers/flows/v1alpha1/expansion_generated.go +++ /dev/null @@ -1,27 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -// FlowListerExpansion allows custom methods to be added to -// FlowLister. -type FlowListerExpansion interface{} - -// FlowNamespaceListerExpansion allows custom methods to be added to -// FlowNamespaceLister. -type FlowNamespaceListerExpansion interface{} diff --git a/pkg/client/listers/flows/v1alpha1/flow.go b/pkg/client/listers/flows/v1alpha1/flow.go deleted file mode 100644 index 7358d8f0d5f..00000000000 --- a/pkg/client/listers/flows/v1alpha1/flow.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2018 The Knative 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/flows/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// FlowLister helps list Flows. -type FlowLister interface { - // List lists all Flows in the indexer. - List(selector labels.Selector) (ret []*v1alpha1.Flow, err error) - // Flows returns an object that can list and get Flows. - Flows(namespace string) FlowNamespaceLister - FlowListerExpansion -} - -// flowLister implements the FlowLister interface. -type flowLister struct { - indexer cache.Indexer -} - -// NewFlowLister returns a new FlowLister. -func NewFlowLister(indexer cache.Indexer) FlowLister { - return &flowLister{indexer: indexer} -} - -// List lists all Flows in the indexer. -func (s *flowLister) List(selector labels.Selector) (ret []*v1alpha1.Flow, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Flow)) - }) - return ret, err -} - -// Flows returns an object that can list and get Flows. -func (s *flowLister) Flows(namespace string) FlowNamespaceLister { - return flowNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// FlowNamespaceLister helps list and get Flows. -type FlowNamespaceLister interface { - // List lists all Flows in the indexer for a given namespace. - List(selector labels.Selector) (ret []*v1alpha1.Flow, err error) - // Get retrieves the Flow from the indexer for a given namespace and name. - Get(name string) (*v1alpha1.Flow, error) - FlowNamespaceListerExpansion -} - -// flowNamespaceLister implements the FlowNamespaceLister -// interface. -type flowNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all Flows in the indexer for a given namespace. -func (s flowNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Flow, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.Flow)) - }) - return ret, err -} - -// Get retrieves the Flow from the indexer for a given namespace and name. -func (s flowNamespaceLister) Get(name string) (*v1alpha1.Flow, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("flow"), name) - } - return obj.(*v1alpha1.Flow), nil -} diff --git a/pkg/controller/bus/controller.go b/pkg/controller/bus/controller.go deleted file mode 100644 index fa5b80a77a7..00000000000 --- a/pkg/controller/bus/controller.go +++ /dev/null @@ -1,726 +0,0 @@ -/* -Copyright 2018 The Knative 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 bus - -import ( - "fmt" - "reflect" - "time" - - "github.com/golang/glog" - "github.com/knative/eventing/pkg/buses" - "github.com/knative/eventing/pkg/controller" - "github.com/knative/eventing/pkg/system" - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/wait" - kubeinformers "k8s.io/client-go/informers" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/kubernetes/scheme" - typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1" - appslisters "k8s.io/client-go/listers/apps/v1" - corelisters "k8s.io/client-go/listers/core/v1" - rbaclisters "k8s.io/client-go/listers/rbac/v1beta1" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/cache" - "k8s.io/client-go/tools/record" - "k8s.io/client-go/util/workqueue" - - clientset "github.com/knative/eventing/pkg/client/clientset/versioned" - channelscheme "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" - informers "github.com/knative/eventing/pkg/client/informers/externalversions" - listers "github.com/knative/eventing/pkg/client/listers/channels/v1alpha1" - sharedclientset "github.com/knative/pkg/client/clientset/versioned" - sharedinformers "github.com/knative/pkg/client/informers/externalversions" - - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - "github.com/knative/eventing/pkg/controller/util" -) - -const ( - controllerAgentName = "bus-controller" - serviceAccountName = "bus-operator" -) - -const ( - // SuccessSynced is used as part of the Event 'reason' when a Bus is synced - SuccessSynced = "Synced" - // ErrResourceExists is used as part of the Event 'reason' when a Bus fails - // to sync due to a Service of the same name already existing. - ErrResourceExists = "ErrResourceExists" - - // MessageResourceExists is the message used for Events when a resource - // fails to sync due to a Service already existing - MessageResourceExists = "Resource %q already exists and is not managed by Bus" - // MessageResourceSynced is the message used for an Event fired when a Bus - // is synced successfully - MessageResourceSynced = "Bus synced successfully" -) - -const ( - // ServiceSynced is used as part of the condition reason when the bus (k8s) service is successfully created. - ServiceSynced = "ServiceSynced" - // ServiceError is used as part of the condition reason when the bus (k8s) service creation failed. - ServiceError = "ServiceError" - // DeploymentSynced is used as part of the condition reason when a bus deployment is successfully created. - DeploymentSynced = "DeploymentSynced" - // DeploymentError is used as part of the condition reason when a bus deployment creation failed. - DeploymentError = "DeploymentError" -) - -// Controller is the controller implementation for Bus resources -type Controller struct { - // kubeclientset is a standard kubernetes clientset - kubeclientset kubernetes.Interface - // busclientset is a clientset for our own API group - busclientset clientset.Interface - - deploymentsLister appslisters.DeploymentLister - deploymentsSynced cache.InformerSynced - servicesLister corelisters.ServiceLister - servicesSynced cache.InformerSynced - serviceAccountsLister corelisters.ServiceAccountLister - serviceAccountsSynced cache.InformerSynced - clusterRoleBindingsLister rbaclisters.ClusterRoleBindingLister - clusterRoleBindingsSynced cache.InformerSynced - busesLister listers.BusLister - busesSynced cache.InformerSynced - - // workqueue is a rate limited work queue. This is used to queue work to be - // processed instead of performing it as soon as a change happens. This - // means we can ensure we only process a fixed amount of resources at a - // time, and makes it easy to ensure we are never processing the same item - // simultaneously in two different workers. - workqueue workqueue.RateLimitingInterface - // recorder is an event recorder for recording Event resources to the - // Kubernetes API. - recorder record.EventRecorder -} - -// NewController returns a new bus controller -func NewController( - kubeclientset kubernetes.Interface, - busclientset clientset.Interface, - sharedclientset sharedclientset.Interface, - restConfig *rest.Config, - kubeInformerFactory kubeinformers.SharedInformerFactory, - busInformerFactory informers.SharedInformerFactory, - istioInformerFactory sharedinformers.SharedInformerFactory, -) controller.Interface { - - // obtain references to shared index informers for the Bus, Deployment and Service - // types. - busInformer := busInformerFactory.Channels().V1alpha1().Buses() - deploymentInformer := kubeInformerFactory.Apps().V1().Deployments() - serviceInformer := kubeInformerFactory.Core().V1().Services() - serviceAccountInformer := kubeInformerFactory.Core().V1().ServiceAccounts() - clusterRoleBindingInformer := kubeInformerFactory.Rbac().V1beta1().ClusterRoleBindings() - - // Create event broadcaster - // Add bus-controller types to the default Kubernetes Scheme so Events can be - // logged for bus-controller types. - channelscheme.AddToScheme(scheme.Scheme) - glog.V(4).Info("Creating event broadcaster") - eventBroadcaster := record.NewBroadcaster() - eventBroadcaster.StartLogging(glog.Infof) - eventBroadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: kubeclientset.CoreV1().Events("")}) - recorder := eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: controllerAgentName}) - - controller := &Controller{ - kubeclientset: kubeclientset, - busclientset: busclientset, - deploymentsLister: deploymentInformer.Lister(), - deploymentsSynced: deploymentInformer.Informer().HasSynced, - servicesLister: serviceInformer.Lister(), - servicesSynced: serviceInformer.Informer().HasSynced, - serviceAccountsLister: serviceAccountInformer.Lister(), - serviceAccountsSynced: serviceAccountInformer.Informer().HasSynced, - clusterRoleBindingsLister: clusterRoleBindingInformer.Lister(), - clusterRoleBindingsSynced: clusterRoleBindingInformer.Informer().HasSynced, - busesLister: busInformer.Lister(), - busesSynced: busInformer.Informer().HasSynced, - workqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "Buses"), - recorder: recorder, - } - - glog.Info("Setting up event handlers") - // Set up an event handler for when Bus resources change - busInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: controller.enqueueBus, - UpdateFunc: func(old, new interface{}) { - controller.enqueueBus(new) - }, - }) - // Set up an event handler for when Service resources change. This - // handler will lookup the owner of the given Service, and if it is - // owned by a Bus resource will enqueue that Bus resource for - // processing. This way, we don't need to implement custom logic for - // handling Service resources. More info on this pattern: - // https://github.com/kubernetes/community/blob/8cafef897a22026d42f5e5bb3f104febe7e29830/contributors/devel/controllers.md - serviceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: controller.handleObject, - UpdateFunc: func(old, new interface{}) { - newService := new.(*corev1.Service) - oldService := old.(*corev1.Service) - if newService.ResourceVersion == oldService.ResourceVersion { - // Periodic resync will send update events for all known Services. - // Two different versions of the same Service will always have different RVs. - return - } - controller.handleObject(new) - }, - DeleteFunc: controller.handleObject, - }) - - return controller -} - -// Run will set up the event handlers for types we are interested in, as well -// as syncing informer caches and starting workers. It will block until stopCh -// is closed, at which point it will shutdown the workqueue and wait for -// workers to finish processing their current work items. -func (c *Controller) Run(threadiness int, stopCh <-chan struct{}) error { - defer runtime.HandleCrash() - defer c.workqueue.ShutDown() - - // Start the informer factories to begin populating the informer caches - glog.Info("Starting Bus controller") - - // Wait for the caches to be synced before starting workers - glog.Info("Waiting for informer caches to sync") - if ok := cache.WaitForCacheSync(stopCh, c.deploymentsSynced, c.servicesSynced, c.busesSynced); !ok { - return fmt.Errorf("failed to wait for caches to sync") - } - - glog.Info("Starting workers") - // Launch two workers to process Bus resources - for i := 0; i < threadiness; i++ { - go wait.Until(c.runWorker, time.Second, stopCh) - } - - glog.Info("Started workers") - <-stopCh - glog.Info("Shutting down workers") - - return nil -} - -// runWorker is a long-running function that will continually call the -// processNextWorkItem function in order to read and process a message on the -// workqueue. -func (c *Controller) runWorker() { - for c.processNextWorkItem() { - } -} - -// processNextWorkItem will read a single work item off the workqueue and -// attempt to process it, by calling the syncHandler. -func (c *Controller) processNextWorkItem() bool { - obj, shutdown := c.workqueue.Get() - - if shutdown { - return false - } - - // We wrap this block in a func so we can defer c.workqueue.Done. - err := func(obj interface{}) error { - // We call Done here so the workqueue knows we have finished - // processing this item. We also must remember to call Forget if we - // do not want this work item being re-queued. For example, we do - // not call Forget if a transient error occurs, instead the item is - // put back on the workqueue and attempted again after a back-off - // period. - defer c.workqueue.Done(obj) - var key string - var ok bool - // We expect strings to come off the workqueue. These are of the - // form namespace/name. We do this as the delayed nature of the - // workqueue means the items in the informer cache may actually be - // more up to date that when the item was initially put onto the - // workqueue. - if key, ok = obj.(string); !ok { - // As the item in the workqueue is actually invalid, we call - // Forget here else we'd go into a loop of attempting to - // process a work item that is invalid. - c.workqueue.Forget(obj) - runtime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj)) - return nil - } - // Run the syncHandler, passing it the namespace/name string of the - // Bus resource to be synced. - if err := c.syncHandler(key); err != nil { - return fmt.Errorf("error syncing bus '%s': %v", key, err) - } - // Finally, if no error occurs we Forget this item so it does not - // get queued again until another change happens. - c.workqueue.Forget(obj) - glog.Infof("Successfully synced bus '%s'", key) - return nil - }(obj) - - if err != nil { - runtime.HandleError(err) - return true - } - - return true -} - -// syncHandler compares the actual state with the desired, and attempts to -// converge the two. It then updates the Status block of the Bus resource -// with the current status of the resource. -func (c *Controller) syncHandler(key string) error { - // Convert the namespace/name string into a distinct namespace and name - namespace, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - runtime.HandleError(fmt.Errorf("invalid resource key: %s", key)) - return nil - } - - // Get the Bus resource with this namespace/name - bus, err := c.busesLister.Buses(namespace).Get(name) - if err != nil { - // The Bus resource may no longer exist, in which case we stop - // processing. - if errors.IsNotFound(err) { - runtime.HandleError(fmt.Errorf("bus '%s' in work queue no longer exists", key)) - return nil - } - - return err - } - - // NEVER modify objects from the store. It's a read-only, local cache. - // You can use DeepCopy() to make a deep copy of original object and modify this copy - // Or create a copy manually for better performance - busCopy := bus.DeepCopy() - - // Sync Service derived from the Bus - dispatcherService, err := c.syncBusDispatcherService(busCopy) - - if err != nil { - busCopy.Status.Service = nil - serviceCondition := util.NewBusCondition(channelsv1alpha1.BusServiceable, corev1.ConditionFalse, ServiceError, err.Error()) - util.SetBusCondition(&busCopy.Status, *serviceCondition) - c.compareAndUpdateBusStatus(bus, busCopy) - return err - } - - busCopy.Status.Service = &corev1.LocalObjectReference{Name: dispatcherService.Name} - serviceCondition := util.NewBusCondition(channelsv1alpha1.BusServiceable, corev1.ConditionTrue, ServiceSynced, "service successfully synced") - util.SetBusCondition(&busCopy.Status, *serviceCondition) - - // Sync Deployment derived from the Bus - _, err = c.syncBusDispatcherDeployment(busCopy) - - if err != nil { - dispatchCondition := util.NewBusCondition(channelsv1alpha1.BusDispatching, corev1.ConditionFalse, DeploymentError, err.Error()) - util.SetBusCondition(&busCopy.Status, *dispatchCondition) - c.compareAndUpdateBusStatus(bus, busCopy) - return err - } - - dispatchCondition := util.NewBusCondition(channelsv1alpha1.BusDispatching, corev1.ConditionTrue, DeploymentSynced, "deployment successfully synced") - util.SetBusCondition(&busCopy.Status, *dispatchCondition) - - // Sync Deployment derived from the Bus - provisionerDeployment, err := c.syncBusProvisionerDeployment(busCopy) - - if err != nil { - provisionCondition := util.NewBusCondition(channelsv1alpha1.BusProvisioning, corev1.ConditionFalse, DeploymentError, err.Error()) - util.SetBusCondition(&busCopy.Status, *provisionCondition) - c.compareAndUpdateBusStatus(bus, busCopy) - return err - } - - if provisionerDeployment != nil { - provisionCondition := util.NewBusCondition(channelsv1alpha1.BusProvisioning, corev1.ConditionTrue, DeploymentSynced, "deployment successfully synced") - util.SetBusCondition(&busCopy.Status, *provisionCondition) - } else { - util.RemoveBusCondition(&busCopy.Status, channelsv1alpha1.BusProvisioning) - } - - // Finally, we update the status block of the Bus resource to reflect the - // current state of the world - err = c.compareAndUpdateBusStatus(bus, busCopy) - - if err != nil { - return err - } - - c.recorder.Event(bus, corev1.EventTypeNormal, SuccessSynced, MessageResourceSynced) - return nil -} - -func (c *Controller) syncBusDispatcherService(bus *channelsv1alpha1.Bus) (*corev1.Service, error) { - // Get the service with the specified service name - serviceName := controller.BusDispatcherServiceName(bus.Name, bus.Namespace) - service, err := c.servicesLister.Services(system.Namespace).Get(serviceName) - // If the resource doesn't exist, we'll create it - if errors.IsNotFound(err) { - service, err = c.kubeclientset.CoreV1().Services(system.Namespace).Create(newDispatcherService(bus)) - } - - // If an error occurs during Get/Create, we'll requeue the item so we can - // attempt processing again later. This could have been caused by a - // temporary network failure, or any other transient reason. - if err != nil { - return nil, err - } - - // If the Service is not controlled by this Bus resource, we should log - // a warning to the event recorder and return - if !metav1.IsControlledBy(service, bus) { - msg := fmt.Sprintf(MessageResourceExists, service.Name) - c.recorder.Event(bus, corev1.EventTypeWarning, ErrResourceExists, msg) - return nil, fmt.Errorf(msg) - } - - return service, nil -} - -func (c *Controller) syncBusDispatcherDeployment(bus *channelsv1alpha1.Bus) (*appsv1.Deployment, error) { - // Get the deployment with the specified deployment name - deploymentName := controller.BusDispatcherDeploymentName(bus.Name, bus.Namespace) - deployment, err := c.deploymentsLister.Deployments(system.Namespace).Get(deploymentName) - // If the resource doesn't exist, we'll create it - if errors.IsNotFound(err) { - deployment, err = c.kubeclientset.AppsV1().Deployments(system.Namespace).Create(newDispatcherDeployment(bus)) - } - - // If an error occurs during Get/Create, we'll requeue the item so we can - // attempt processing again later. This could have been caused by a - // temporary network failure, or any other transient reason. - if err != nil { - return nil, err - } - - // If the Deployment is not controlled by this Bus resource, we should log - // a warning to the event recorder and return - if !metav1.IsControlledBy(deployment, bus) { - msg := fmt.Sprintf(MessageResourceExists, deployment.Name) - c.recorder.Event(bus, corev1.EventTypeWarning, ErrResourceExists, msg) - return nil, fmt.Errorf(msg) - } - - // If the Deployment does not match the Bus's proposed Deployment we should update - // the Deployment resource. - proposedDeployment := newDispatcherDeployment(bus) - if !reflect.DeepEqual(proposedDeployment.Spec, deployment.Spec) { - glog.V(4).Infof("Bus %s dispatcher spec updated", bus.Name) - deployment, err = c.kubeclientset.AppsV1().Deployments(system.Namespace).Update(proposedDeployment) - - if err != nil { - return nil, err - } - } - - return deployment, nil -} - -func (c *Controller) syncBusProvisionerDeployment(bus *channelsv1alpha1.Bus) (*appsv1.Deployment, error) { - provisioner := bus.Spec.Provisioner - - // Get the deployment with the specified deployment name - deploymentName := controller.BusProvisionerDeploymentName(bus.Name, bus.Namespace) - deployment, err := c.deploymentsLister.Deployments(system.Namespace).Get(deploymentName) - - // If the resource shouldn't exists - if provisioner == nil { - // If the resource exists, we'll delete it - if deployment != nil { - err = c.kubeclientset.AppsV1().Deployments(system.Namespace).Delete(deploymentName, nil) - } - if errors.IsNotFound(err) { - return nil, nil - } - return nil, err - } - - // If the resource doesn't exist, we'll create it - if errors.IsNotFound(err) { - deployment, err = c.kubeclientset.AppsV1().Deployments(system.Namespace).Create(newProvisionerDeployment(bus)) - } - - // If an error occurs during Get/Create, we'll requeue the item so we can - // attempt processing again later. This could have been caused by a - // temporary network failure, or any other transient reason. - if err != nil { - return nil, err - } - - // If the Deployment is not controlled by this Bus resource, we should log - // a warning to the event recorder and return - if !metav1.IsControlledBy(deployment, bus) { - msg := fmt.Sprintf(MessageResourceExists, deployment.Name) - c.recorder.Event(bus, corev1.EventTypeWarning, ErrResourceExists, msg) - return nil, fmt.Errorf(msg) - } - - // If the Deployment does not match the Bus's proposed Deployment we should update - // the Deployment resource. - proposedDeployment := newProvisionerDeployment(bus) - if !reflect.DeepEqual(proposedDeployment.Spec, deployment.Spec) { - glog.V(4).Infof("Bus %s provisioner spec updated", bus.Name) - deployment, err = c.kubeclientset.AppsV1().Deployments(system.Namespace).Update(proposedDeployment) - - if err != nil { - return nil, err - } - } - - return deployment, nil -} - -func (c *Controller) compareAndUpdateBusStatus(bus *channelsv1alpha1.Bus, busCopy *channelsv1alpha1.Bus) error { - util.ConsolidateBusCondition(busCopy) - - // Only update if status has changed - if !equality.Semantic.DeepEqual(bus.Status, busCopy.Status) { - // If the CustomResourceSubresources feature gate is not enabled, - // we must use Update instead of UpdateStatus to update the Status block of the Bus resource. - // UpdateStatus will not allow changes to the Spec of the resource, - // which is ideal for ensuring nothing other than resource status has been updated. - _, err := c.busclientset.ChannelsV1alpha1().Buses(bus.Namespace).Update(busCopy) - return err - } - return nil -} - -// enqueueBus takes a Bus resource and converts it into a namespace/name -// string which is then put onto the work queue. This method should *not* be -// passed resources of any type other than Bus. -func (c *Controller) enqueueBus(obj interface{}) { - var key string - var err error - if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { - runtime.HandleError(err) - return - } - c.workqueue.AddRateLimited(key) -} - -// handleObject will take any resource implementing metav1.Object and attempt -// to find the Bus resource that 'owns' it. It does this by looking at the -// objects metadata.ownerReferences field for an appropriate OwnerReference. -// It then enqueues that Bus resource to be processed. If the object does not -// have an appropriate OwnerReference, it will simply be skipped. -func (c *Controller) handleObject(obj interface{}) { - var object metav1.Object - var ok bool - if object, ok = obj.(metav1.Object); !ok { - tombstone, ok := obj.(cache.DeletedFinalStateUnknown) - if !ok { - runtime.HandleError(fmt.Errorf("error decoding object, invalid type")) - return - } - object, ok = tombstone.Obj.(metav1.Object) - if !ok { - runtime.HandleError(fmt.Errorf("error decoding object tombstone, invalid type")) - return - } - glog.V(4).Infof("Recovered deleted object '%s' from tombstone", object.GetName()) - } - glog.V(4).Infof("Processing object: %s", object.GetName()) - if ownerRef := metav1.GetControllerOf(object); ownerRef != nil { - // If this object is not owned by a Bus, we should not do anything more - // with it. - if ownerRef.Kind != "Bus" { - return - } - - bus, err := c.busesLister.Buses(object.GetNamespace()).Get(ownerRef.Name) - if err != nil { - glog.V(4).Infof("ignoring orphaned object '%s' of bus '%s'", object.GetSelfLink(), ownerRef.Name) - return - } - - c.enqueueBus(bus) - return - } -} - -// newDispatcherService creates a new Service for a Bus resource. It also sets -// the appropriate OwnerReferences on the resource so handleObject can discover -// the Bus resource that 'owns' it. -func newDispatcherService(bus *channelsv1alpha1.Bus) *corev1.Service { - labels := dispatcherLabels(bus.Name, bus.Namespace) - return &corev1.Service{ - ObjectMeta: metav1.ObjectMeta{ - Name: controller.BusDispatcherServiceName(bus.Name, bus.Namespace), - Namespace: system.Namespace, - Labels: labels, - OwnerReferences: []metav1.OwnerReference{ - *metav1.NewControllerRef(bus, schema.GroupVersionKind{ - Group: channelsv1alpha1.SchemeGroupVersion.Group, - Version: channelsv1alpha1.SchemeGroupVersion.Version, - Kind: "Bus", - }), - }, - }, - Spec: corev1.ServiceSpec{ - Selector: labels, - Ports: []corev1.ServicePort{ - { - Name: "http", - Port: 80, - TargetPort: intstr.FromInt(buses.MessageReceiverPort), - }, - }, - }, - } -} - -// newDispatcherDeployment creates a new Deployment for a Bus resource. It also sets -// the appropriate OwnerReferences on the resource so handleObject can discover -// the Bus resource that 'owns' it. -func newDispatcherDeployment(bus *channelsv1alpha1.Bus) *appsv1.Deployment { - labels := dispatcherLabels(bus.Name, bus.Namespace) - one := int32(1) - container := bus.Spec.Dispatcher.DeepCopy() - container.Env = append(container.Env, - corev1.EnvVar{ - Name: "PORT", - Value: "8080", - }, - corev1.EnvVar{ - Name: "BUS_NAMESPACE", - Value: bus.Namespace, - }, - corev1.EnvVar{ - Name: "BUS_NAME", - Value: bus.Name, - }, - ) - volumes := []corev1.Volume{} - if bus.Spec.Volumes != nil { - volumes = *bus.Spec.Volumes - } - return &appsv1.Deployment{ - ObjectMeta: metav1.ObjectMeta{ - Name: controller.BusDispatcherDeploymentName(bus.Name, bus.Namespace), - Namespace: system.Namespace, - OwnerReferences: []metav1.OwnerReference{ - *metav1.NewControllerRef(bus, schema.GroupVersionKind{ - Group: channelsv1alpha1.SchemeGroupVersion.Group, - Version: channelsv1alpha1.SchemeGroupVersion.Version, - Kind: "Bus", - }), - }, - }, - Spec: appsv1.DeploymentSpec{ - Replicas: &one, - Selector: &metav1.LabelSelector{ - MatchLabels: labels, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - "sidecar.istio.io/inject": "true", - }, - Labels: labels, - }, - Spec: corev1.PodSpec{ - ServiceAccountName: serviceAccountName, - Containers: []corev1.Container{ - *container, - }, - Volumes: volumes, - }, - }, - }, - } -} - -// newProvisionerDeployment creates a new Deployment for a Bus resource. It also sets -// the appropriate OwnerReferences on the resource so handleObject can discover -// the Bus resource that 'owns' it. -func newProvisionerDeployment(bus *channelsv1alpha1.Bus) *appsv1.Deployment { - labels := provisionerLabels(bus.Name, bus.Namespace) - one := int32(1) - container := bus.Spec.Provisioner.DeepCopy() - container.Env = append(container.Env, - corev1.EnvVar{ - Name: "BUS_NAMESPACE", - Value: bus.Namespace, - }, - corev1.EnvVar{ - Name: "BUS_NAME", - Value: bus.Name, - }, - ) - volumes := []corev1.Volume{} - if bus.Spec.Volumes != nil { - volumes = *bus.Spec.Volumes - } - return &appsv1.Deployment{ - ObjectMeta: metav1.ObjectMeta{ - Name: controller.BusProvisionerDeploymentName(bus.Name, bus.Namespace), - Namespace: system.Namespace, - OwnerReferences: []metav1.OwnerReference{ - *metav1.NewControllerRef(bus, schema.GroupVersionKind{ - Group: channelsv1alpha1.SchemeGroupVersion.Group, - Version: channelsv1alpha1.SchemeGroupVersion.Version, - Kind: "Bus", - }), - }, - }, - Spec: appsv1.DeploymentSpec{ - Replicas: &one, - Selector: &metav1.LabelSelector{ - MatchLabels: labels, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - "sidecar.istio.io/inject": "true", - }, - Labels: labels, - }, - Spec: corev1.PodSpec{ - ServiceAccountName: serviceAccountName, - Containers: []corev1.Container{ - *container, - }, - Volumes: volumes, - }, - }, - }, - } -} - -func dispatcherLabels(busName, namespace string) map[string]string { - return map[string]string{ - "bus": busName, - "namespace": namespace, - "role": "dispatcher", - } -} - -func provisionerLabels(busName, namespace string) map[string]string { - return map[string]string{ - "bus": busName, - "namespace": namespace, - "role": "provisioner", - } -} diff --git a/pkg/controller/bus/stub_test.go b/pkg/controller/bus/stub_test.go deleted file mode 100644 index 6979e8b37ce..00000000000 --- a/pkg/controller/bus/stub_test.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright 2018 The Knative 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 bus - -import "testing" - -func TestStub(t *testing.T) { - // TODO: Implement tests in this directory, please. - // This file is used to make code coverage on this directly count. -} diff --git a/pkg/controller/channel/controller.go b/pkg/controller/channel/controller.go deleted file mode 100644 index 158059927ef..00000000000 --- a/pkg/controller/channel/controller.go +++ /dev/null @@ -1,563 +0,0 @@ -/* -Copyright 2018 The Knative 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 channel - -import ( - "fmt" - "time" - - "github.com/golang/glog" - "github.com/knative/eventing/pkg/controller" - istiolisters "github.com/knative/pkg/client/listers/istio/v1alpha3" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/wait" - kubeinformers "k8s.io/client-go/informers" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/kubernetes/scheme" - typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1" - corelisters "k8s.io/client-go/listers/core/v1" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/cache" - "k8s.io/client-go/tools/record" - "k8s.io/client-go/util/workqueue" - - clientset "github.com/knative/eventing/pkg/client/clientset/versioned" - channelscheme "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" - informers "github.com/knative/eventing/pkg/client/informers/externalversions" - listers "github.com/knative/eventing/pkg/client/listers/channels/v1alpha1" - "github.com/knative/eventing/pkg/system" - sharedclientset "github.com/knative/pkg/client/clientset/versioned" - sharedinformers "github.com/knative/pkg/client/informers/externalversions" - - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - "github.com/knative/eventing/pkg/controller/util" - istiov1alpha3 "github.com/knative/pkg/apis/istio/v1alpha3" -) - -const controllerAgentName = "channel-controller" - -const ( - // SuccessSynced is used as part of the Event 'reason' when a Channel is synced - SuccessSynced = "Synced" - // ErrResourceExists is used as part of the Event 'reason' when a Channel fails - // to sync due to a Service of the same name already existing. - ErrResourceExists = "ErrResourceExists" - - // MessageResourceExists is the message used for Events when a resource - // fails to sync due to a Service already existing - MessageResourceExists = "Resource %q already exists and is not managed by Channel" - // MessageResourceSynced is the message used for an Event fired when a Channel - // is synced successfully - MessageResourceSynced = "Channel synced successfully" -) - -const ( - // ServiceSynced is used as part of the condition reason when the channel (k8s) service is successfully created. - ServiceSynced = "ServiceSynced" - // ServiceError is used as part of the condition reason when the channel (k8s) service creation failed. - ServiceError = "ServiceError" - // VirtualServiceSynced is used as part of the condition reason when the channel istio virtual service is successfully created. - VirtualServiceSynced = "VirtualServiceSynced" - // VirtualServiceError is used as part of the condition reason when the channel istio virtual service creation failed. - VirtualServiceError = "VirtualServiceError" -) - -const ( - PortNumber = 80 - PortName = "http" -) - -// Controller is the controller implementation for Channel resources -type Controller struct { - // kubeclientset is a standard kubernetes clientset - kubeclientset kubernetes.Interface - // channelclientset is a clientset for our own API group - channelclientset clientset.Interface - // sharedclientset is a clientset for shared API groups - sharedclientset sharedclientset.Interface - - virtualservicesLister istiolisters.VirtualServiceLister - virtualservicesSynced cache.InformerSynced - servicesLister corelisters.ServiceLister - servicesSynced cache.InformerSynced - channelsLister listers.ChannelLister - channelsSynced cache.InformerSynced - - // workqueue is a rate limited work queue. This is used to queue work to be - // processed instead of performing it as soon as a change happens. This - // means we can ensure we only process a fixed amount of resources at a - // time, and makes it easy to ensure we are never processing the same item - // simultaneously in two different workers. - workqueue workqueue.RateLimitingInterface - // recorder is an event recorder for recording Event resources to the - // Kubernetes API. - recorder record.EventRecorder -} - -// NewController returns a new channel controller -func NewController( - kubeclientset kubernetes.Interface, - channelclientset clientset.Interface, - sharedclientset sharedclientset.Interface, - restConfig *rest.Config, - kubeInformerFactory kubeinformers.SharedInformerFactory, - channelInformerFactory informers.SharedInformerFactory, - sharedInformerFactory sharedinformers.SharedInformerFactory, -) controller.Interface { - - // obtain references to shared index informers for the Service and Channel types. - virtualserviceInformer := sharedInformerFactory.Networking().V1alpha3().VirtualServices() - serviceInformer := kubeInformerFactory.Core().V1().Services() - channelInformer := channelInformerFactory.Channels().V1alpha1().Channels() - - // Create event broadcaster - // Add channel-controller types to the default Kubernetes Scheme so Events can be - // logged for channel-controller types. - channelscheme.AddToScheme(scheme.Scheme) - glog.V(4).Info("Creating event broadcaster") - eventBroadcaster := record.NewBroadcaster() - eventBroadcaster.StartLogging(glog.Infof) - eventBroadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: kubeclientset.CoreV1().Events("")}) - recorder := eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: controllerAgentName}) - - controller := &Controller{ - kubeclientset: kubeclientset, - channelclientset: channelclientset, - sharedclientset: sharedclientset, - virtualservicesLister: virtualserviceInformer.Lister(), - virtualservicesSynced: virtualserviceInformer.Informer().HasSynced, - servicesLister: serviceInformer.Lister(), - servicesSynced: serviceInformer.Informer().HasSynced, - channelsLister: channelInformer.Lister(), - channelsSynced: channelInformer.Informer().HasSynced, - workqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "Channels"), - recorder: recorder, - } - - glog.Info("Setting up event handlers") - // Set up an event handler for when Channel resources change - channelInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: controller.enqueueChannel, - UpdateFunc: func(old, new interface{}) { - controller.enqueueChannel(new) - }, - }) - // Set up an event handler for when Service resources change. This - // handler will lookup the owner of the given Service, and if it is - // owned by a Channel resource will enqueue that Channel resource for - // processing. This way, we don't need to implement custom logic for - // handling Service resources. More info on this pattern: - // https://github.com/kubernetes/community/blob/8cafef897a22026d42f5e5bb3f104febe7e29830/contributors/devel/controllers.md - serviceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: controller.handleObject, - UpdateFunc: func(old, new interface{}) { - newService := new.(*corev1.Service) - oldService := old.(*corev1.Service) - if newService.ResourceVersion == oldService.ResourceVersion { - // Periodic resync will send update events for all known Services. - // Two different versions of the same Service will always have different RVs. - return - } - controller.handleObject(new) - }, - DeleteFunc: controller.handleObject, - }) - - return controller -} - -// Run will set up the event handlers for types we are interested in, as well -// as syncing informer caches and starting workers. It will block until stopCh -// is closed, at which point it will shutdown the workqueue and wait for -// workers to finish processing their current work items. -func (c *Controller) Run(threadiness int, stopCh <-chan struct{}) error { - defer runtime.HandleCrash() - defer c.workqueue.ShutDown() - - // Start the informer factories to begin populating the informer caches - glog.Info("Starting Channel controller") - - // Wait for the caches to be synced before starting workers - glog.Info("Waiting for informer caches to sync") - if ok := cache.WaitForCacheSync(stopCh, c.servicesSynced, c.channelsSynced); !ok { - return fmt.Errorf("failed to wait for caches to sync") - } - - glog.Info("Starting workers") - // Launch two workers to process Channel resources - for i := 0; i < threadiness; i++ { - go wait.Until(c.runWorker, time.Second, stopCh) - } - - glog.Info("Started workers") - <-stopCh - glog.Info("Shutting down workers") - - return nil -} - -// runWorker is a long-running function that will continually call the -// processNextWorkItem function in order to read and process a message on the -// workqueue. -func (c *Controller) runWorker() { - for c.processNextWorkItem() { - } -} - -// processNextWorkItem will read a single work item off the workqueue and -// attempt to process it, by calling the syncHandler. -func (c *Controller) processNextWorkItem() bool { - obj, shutdown := c.workqueue.Get() - - if shutdown { - return false - } - - // We wrap this block in a func so we can defer c.workqueue.Done. - err := func(obj interface{}) error { - // We call Done here so the workqueue knows we have finished - // processing this item. We also must remember to call Forget if we - // do not want this work item being re-queued. For example, we do - // not call Forget if a transient error occurs, instead the item is - // put back on the workqueue and attempted again after a back-off - // period. - defer c.workqueue.Done(obj) - var key string - var ok bool - // We expect strings to come off the workqueue. These are of the - // form namespace/name. We do this as the delayed nature of the - // workqueue means the items in the informer cache may actually be - // more up to date that when the item was initially put onto the - // workqueue. - if key, ok = obj.(string); !ok { - // As the item in the workqueue is actually invalid, we call - // Forget here else we'd go into a loop of attempting to - // process a work item that is invalid. - c.workqueue.Forget(obj) - runtime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj)) - return nil - } - // Run the syncHandler, passing it the namespace/name string of the - // Channel resource to be synced. - if err := c.syncHandler(key); err != nil { - return fmt.Errorf("error syncing channel '%s': %v", key, err) - } - // Finally, if no error occurs we Forget this item so it does not - // get queued again until another change happens. - c.workqueue.Forget(obj) - glog.Infof("Successfully synced channel '%s'", key) - return nil - }(obj) - - if err != nil { - runtime.HandleError(err) - return true - } - - return true -} - -// syncHandler compares the actual state with the desired, and attempts to -// converge the two. It then updates the Status block of the Channel resource -// with the current status of the resource. -func (c *Controller) syncHandler(key string) error { - // Convert the namespace/name string into a distinct namespace and name - namespace, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - runtime.HandleError(fmt.Errorf("invalid resource key: %s", key)) - return nil - } - - // Get the Channel resource with this namespace/name - channel, err := c.channelsLister.Channels(namespace).Get(name) - if err != nil { - // The Channel resource may no longer exist, in which case we stop - // processing. - if errors.IsNotFound(err) { - runtime.HandleError(fmt.Errorf("channel '%s' in work queue no longer exists", key)) - return nil - } - - return err - } - - var service *corev1.Service - var virtualService *istiov1alpha3.VirtualService - var serviceErr, virtualServiceErr error - - // Sync Service derived from the Channel - service, serviceErr = c.syncChannelService(channel) - if serviceErr != nil { - c.updateChannelStatus(channel, service, serviceErr, virtualService, virtualServiceErr) - return serviceErr - } - - // Sync VirtualService derived from a Channel - virtualService, virtualServiceErr = c.syncChannelVirtualService(channel) - if virtualServiceErr != nil { - c.updateChannelStatus(channel, service, serviceErr, virtualService, virtualServiceErr) - return virtualServiceErr - } - - // Finally, we update the status block of the Channel resource to reflect the - // current state of the world - err = c.updateChannelStatus(channel, service, serviceErr, virtualService, virtualServiceErr) - if err != nil { - return err - } - - c.recorder.Event(channel, corev1.EventTypeNormal, SuccessSynced, MessageResourceSynced) - return nil -} - -func (c *Controller) syncChannelService(channel *channelsv1alpha1.Channel) (*corev1.Service, error) { - // Get the service with the specified service name - serviceName := controller.ChannelServiceName(channel.ObjectMeta.Name) - service, err := c.servicesLister.Services(channel.Namespace).Get(serviceName) - // If the resource doesn't exist, we'll create it - if errors.IsNotFound(err) { - service, err = c.kubeclientset.CoreV1().Services(channel.Namespace).Create(newService(channel)) - } - - // If an error occurs during Get/Create, we'll requeue the item so we can - // attempt processing again later. This could have been caused by a - // temporary network failure, or any other transient reason. - if err != nil { - return nil, err - } - - // If the Service is not controlled by this Channel resource, we should log - // a warning to the event recorder and return - if !metav1.IsControlledBy(service, channel) { - msg := fmt.Sprintf(MessageResourceExists, service.Name) - c.recorder.Event(channel, corev1.EventTypeWarning, ErrResourceExists, msg) - return nil, fmt.Errorf(msg) - } - - return service, nil -} - -func (c *Controller) syncChannelVirtualService(channel *channelsv1alpha1.Channel) (*istiov1alpha3.VirtualService, error) { - // Get the VirtualService with the specified Channel name - virtualserviceName := controller.ChannelVirtualServiceName(channel.ObjectMeta.Name) - virtualservice, err := c.virtualservicesLister.VirtualServices(channel.Namespace).Get(virtualserviceName) - - // If the resource doesn't exist, we'll create it - if errors.IsNotFound(err) { - virtualservice, err = c.sharedclientset.NetworkingV1alpha3().VirtualServices(channel.Namespace).Create(newVirtualService(channel)) - } - - // If an error occurs during Get/Create, we'll requeue the item so we can - // attempt processing again later. This could have been caused by a - // temporary network failure, or any other transient reason. - if err != nil { - return nil, err - } - - // If the Service is not controlled by this Channel resource, we should log - // a warning to the event recorder and return - if !metav1.IsControlledBy(virtualservice, channel) { - msg := fmt.Sprintf(MessageResourceExists, virtualservice.Name) - c.recorder.Event(channel, corev1.EventTypeWarning, ErrResourceExists, msg) - return nil, fmt.Errorf(msg) - } - - return virtualservice, nil -} - -func (c *Controller) updateChannelStatus(channel *channelsv1alpha1.Channel, - service *corev1.Service, serviceError error, - virtualService *istiov1alpha3.VirtualService, virtualServiceError error) error { - // NEVER modify objects from the store. It's a read-only, local cache. - // You can use DeepCopy() to make a deep copy of original object and modify this copy - // Or create a copy manually for better performance - channelCopy := channel.DeepCopy() - - // Update ChannelStatus - - if service != nil { - channelCopy.Status.Service = &corev1.LocalObjectReference{Name: service.Name} - serviceCondition := util.NewChannelCondition(channelsv1alpha1.ChannelServiceable, corev1.ConditionTrue, ServiceSynced, "service successfully synced") - util.SetChannelCondition(&channelCopy.Status, *serviceCondition) - } else { - channelCopy.Status.Service = nil - serviceCondition := util.NewChannelCondition(channelsv1alpha1.ChannelServiceable, corev1.ConditionFalse, ServiceError, serviceError.Error()) - util.SetChannelCondition(&channelCopy.Status, *serviceCondition) - } - - if virtualService != nil { - channelCopy.Status.VirtualService = &corev1.LocalObjectReference{Name: virtualService.Name} - serviceCondition := util.NewChannelCondition(channelsv1alpha1.ChannelRoutable, corev1.ConditionTrue, VirtualServiceSynced, "virtual service successfully synced") - util.SetChannelCondition(&channelCopy.Status, *serviceCondition) - } else { - channelCopy.Status.VirtualService = nil - serviceCondition := util.NewChannelCondition(channelsv1alpha1.ChannelRoutable, corev1.ConditionFalse, VirtualServiceError, virtualServiceError.Error()) - util.SetChannelCondition(&channelCopy.Status, *serviceCondition) - } - - util.ConsolidateChannelCondition(&channelCopy.Status) - - channelCopy.Status.DomainInternal = controller.ServiceHostName(service.Name, service.Namespace) - - // Only update if status has changed - if !equality.Semantic.DeepEqual(channel.Status, channelCopy.Status) { - // If the CustomResourceSubresources feature gate is not enabled, - // we must use Update instead of UpdateStatus to update the Status block of the Channel resource. - // UpdateStatus will not allow changes to the Spec of the resource, - // which is ideal for ensuring nothing other than resource status has been updated. - _, err := c.channelclientset.ChannelsV1alpha1().Channels(channel.Namespace).Update(channelCopy) - return err - } - return nil -} - -// enqueueChannel takes a Channel resource and converts it into a namespace/name -// string which is then put onto the work queue. This method should *not* be -// passed resources of any type other than Channel. -func (c *Controller) enqueueChannel(obj interface{}) { - var key string - var err error - if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { - runtime.HandleError(err) - return - } - c.workqueue.AddRateLimited(key) -} - -// handleObject will take any resource implementing metav1.Object and attempt -// to find the Channel resource that 'owns' it. It does this by looking at the -// objects metadata.ownerReferences field for an appropriate OwnerReference. -// It then enqueues that Channel resource to be processed. If the object does not -// have an appropriate OwnerReference, it will simply be skipped. -func (c *Controller) handleObject(obj interface{}) { - var object metav1.Object - var ok bool - if object, ok = obj.(metav1.Object); !ok { - tombstone, ok := obj.(cache.DeletedFinalStateUnknown) - if !ok { - runtime.HandleError(fmt.Errorf("error decoding object, invalid type")) - return - } - object, ok = tombstone.Obj.(metav1.Object) - if !ok { - runtime.HandleError(fmt.Errorf("error decoding object tombstone, invalid type")) - return - } - glog.V(4).Infof("Recovered deleted object '%s' from tombstone", object.GetName()) - } - glog.V(4).Infof("Processing object: %s", object.GetName()) - if ownerRef := metav1.GetControllerOf(object); ownerRef != nil { - // If this object is not owned by a Channel, we should not do anything more - // with it. - if ownerRef.Kind != "Channel" { - return - } - - channel, err := c.channelsLister.Channels(object.GetNamespace()).Get(ownerRef.Name) - if err != nil { - glog.V(4).Infof("ignoring orphaned object '%s' of channel '%s'", object.GetSelfLink(), ownerRef.Name) - return - } - - c.enqueueChannel(channel) - return - } -} - -// newService creates a new Service for a Channel resource. It also sets -// the appropriate OwnerReferences on the resource so handleObject can discover -// the Channel resource that 'owns' it. -func newService(channel *channelsv1alpha1.Channel) *corev1.Service { - labels := map[string]string{ - "channel": channel.Name, - } - return &corev1.Service{ - ObjectMeta: metav1.ObjectMeta{ - Name: controller.ChannelServiceName(channel.ObjectMeta.Name), - Namespace: channel.Namespace, - Labels: labels, - OwnerReferences: []metav1.OwnerReference{ - *metav1.NewControllerRef(channel, schema.GroupVersionKind{ - Group: channelsv1alpha1.SchemeGroupVersion.Group, - Version: channelsv1alpha1.SchemeGroupVersion.Version, - Kind: "Channel", - }), - }, - }, - Spec: corev1.ServiceSpec{ - Ports: []corev1.ServicePort{ - {Name: PortName, Port: PortNumber}, - }, - }, - } -} - -// newVirtualService creates a new VirtualService for a Channel resource. It also sets -// the appropriate OwnerReferences on the resource so handleObject can discover -// the Channel resource that 'owns' it. -func newVirtualService(channel *channelsv1alpha1.Channel) *istiov1alpha3.VirtualService { - labels := map[string]string{ - "channel": channel.Name, - } - var destinationHost string - if channel.Spec.Bus != "" { - labels["bus"] = channel.Spec.Bus - destinationHost = controller.ServiceHostName(controller.BusDispatcherServiceName(channel.Spec.Bus, channel.Namespace), system.Namespace) - } - if channel.Spec.ClusterBus != "" { - labels["clusterBus"] = channel.Spec.ClusterBus - destinationHost = controller.ServiceHostName(controller.ClusterBusDispatcherServiceName(channel.Spec.ClusterBus), system.Namespace) - } - return &istiov1alpha3.VirtualService{ - ObjectMeta: metav1.ObjectMeta{ - Name: controller.ChannelVirtualServiceName(channel.Name), - Namespace: channel.Namespace, - Labels: labels, - OwnerReferences: []metav1.OwnerReference{ - *metav1.NewControllerRef(channel, schema.GroupVersionKind{ - Group: channelsv1alpha1.SchemeGroupVersion.Group, - Version: channelsv1alpha1.SchemeGroupVersion.Version, - Kind: "Channel", - }), - }, - }, - Spec: istiov1alpha3.VirtualServiceSpec{ - Hosts: []string{ - controller.ServiceHostName(controller.ChannelServiceName(channel.Name), channel.Namespace), - controller.ChannelHostName(channel.Name, channel.Namespace), - }, - Http: []istiov1alpha3.HTTPRoute{{ - Rewrite: &istiov1alpha3.HTTPRewrite{ - Authority: controller.ChannelHostName(channel.Name, channel.Namespace), - }, - Route: []istiov1alpha3.DestinationWeight{{ - Destination: istiov1alpha3.Destination{ - Host: destinationHost, - Port: istiov1alpha3.PortSelector{ - Number: PortNumber, - }, - }}, - }}, - }, - }, - } -} diff --git a/pkg/controller/clusterbus/controller.go b/pkg/controller/clusterbus/controller.go deleted file mode 100644 index db5418a9de7..00000000000 --- a/pkg/controller/clusterbus/controller.go +++ /dev/null @@ -1,703 +0,0 @@ -/* -Copyright 2017 The Knative 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 clusterbus - -import ( - "fmt" - "reflect" - "time" - - "github.com/knative/eventing/pkg/buses" - - "github.com/golang/glog" - "github.com/knative/eventing/pkg/controller" - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/wait" - kubeinformers "k8s.io/client-go/informers" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/kubernetes/scheme" - typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1" - appslisters "k8s.io/client-go/listers/apps/v1" - corelisters "k8s.io/client-go/listers/core/v1" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/cache" - "k8s.io/client-go/tools/record" - "k8s.io/client-go/util/workqueue" - - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - clientset "github.com/knative/eventing/pkg/client/clientset/versioned" - channelscheme "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" - informers "github.com/knative/eventing/pkg/client/informers/externalversions" - listers "github.com/knative/eventing/pkg/client/listers/channels/v1alpha1" - "github.com/knative/eventing/pkg/controller/util" - "github.com/knative/eventing/pkg/system" - sharedclientset "github.com/knative/pkg/client/clientset/versioned" - sharedinformers "github.com/knative/pkg/client/informers/externalversions" -) - -const ( - controllerAgentName = "clusterbus-controller" - serviceAccountName = "bus-operator" -) - -const ( - // SuccessSynced is used as part of the Event 'reason' when a ClusterBus is synced - SuccessSynced = "Synced" - // ErrResourceExists is used as part of the Event 'reason' when a ClusterBus fails - // to sync due to a Service of the same name already existing. - ErrResourceExists = "ErrResourceExists" - - // MessageResourceExists is the message used for Events when a resource - // fails to sync due to a Service already existing - MessageResourceExists = "Resource %q already exists and is not managed by ClusterBus" - // MessageResourceSynced is the message used for an Event fired when a ClusterBus - // is synced successfully - MessageResourceSynced = "ClusterBus synced successfully" -) - -const ( - // ServiceSynced is used as part of the condition reason when the bus (k8s) service is successfully created. - ServiceSynced = "ServiceSynced" - // ServiceError is used as part of the condition reason when the bus (k8s) service creation failed. - ServiceError = "ServiceError" - // DeploymentSynced is used as part of the condition reason when a bus deployment is successfully created. - DeploymentSynced = "DeploymentSynced" - // DeploymentError is used as part of the condition reason when a bus deployment creation failed. - DeploymentError = "DeploymentError" -) - -// Controller is the controller implementation for ClusterBus resources -type Controller struct { - // kubeclientset is a standard kubernetes clientset - kubeclientset kubernetes.Interface - // clusterbusclientset is a clientset for our own API group - clusterbusclientset clientset.Interface - - deploymentsLister appslisters.DeploymentLister - deploymentsSynced cache.InformerSynced - servicesLister corelisters.ServiceLister - servicesSynced cache.InformerSynced - clusterBusesLister listers.ClusterBusLister - clusterBusesSynced cache.InformerSynced - - // workqueue is a rate limited work queue. This is used to queue work to be - // processed instead of performing it as soon as a change happens. This - // means we can ensure we only process a fixed amount of resources at a - // time, and makes it easy to ensure we are never processing the same item - // simultaneously in two different workers. - workqueue workqueue.RateLimitingInterface - // recorder is an event recorder for recording Event resources to the - // Kubernetes API. - recorder record.EventRecorder -} - -// NewController returns a new clusterbus controller -func NewController( - kubeclientset kubernetes.Interface, - clusterbusclientset clientset.Interface, - sharedclientset sharedclientset.Interface, - restConfig *rest.Config, - kubeInformerFactory kubeinformers.SharedInformerFactory, - clusterBusInformerFactory informers.SharedInformerFactory, - sharedInformerFactory sharedinformers.SharedInformerFactory, -) controller.Interface { - - // obtain references to shared index informers for the ClusterBus, Deployment and Service - // types. - clusterBusInformer := clusterBusInformerFactory.Channels().V1alpha1().ClusterBuses() - deploymentInformer := kubeInformerFactory.Apps().V1().Deployments() - serviceInformer := kubeInformerFactory.Core().V1().Services() - - // Create event broadcaster - // Add clusterbus-controller types to the default Kubernetes Scheme so Events can be - // logged for clusterbus-controller types. - channelscheme.AddToScheme(scheme.Scheme) - glog.V(4).Info("Creating event broadcaster") - eventBroadcaster := record.NewBroadcaster() - eventBroadcaster.StartLogging(glog.Infof) - eventBroadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: kubeclientset.CoreV1().Events("")}) - recorder := eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: controllerAgentName}) - - controller := &Controller{ - kubeclientset: kubeclientset, - clusterbusclientset: clusterbusclientset, - deploymentsLister: deploymentInformer.Lister(), - deploymentsSynced: deploymentInformer.Informer().HasSynced, - servicesLister: serviceInformer.Lister(), - servicesSynced: serviceInformer.Informer().HasSynced, - clusterBusesLister: clusterBusInformer.Lister(), - clusterBusesSynced: clusterBusInformer.Informer().HasSynced, - workqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "ClusterBuses"), - recorder: recorder, - } - - glog.Info("Setting up event handlers") - // Set up an event handler for when ClusterBus resources change - clusterBusInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: controller.enqueueClusterBus, - UpdateFunc: func(old, new interface{}) { - controller.enqueueClusterBus(new) - }, - }) - // Set up an event handler for when Service resources change. This - // handler will lookup the owner of the given Service, and if it is - // owned by a ClusterBus resource will enqueue that ClusterBus resource for - // processing. This way, we don't need to implement custom logic for - // handling Service resources. More info on this pattern: - // https://github.com/kubernetes/community/blob/8cafef897a22026d42f5e5bb3f104febe7e29830/contributors/devel/controllers.md - serviceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: controller.handleObject, - UpdateFunc: func(old, new interface{}) { - newService := new.(*corev1.Service) - oldService := old.(*corev1.Service) - if newService.ResourceVersion == oldService.ResourceVersion { - // Periodic resync will send update events for all known Services. - // Two different versions of the same Service will always have different RVs. - return - } - controller.handleObject(new) - }, - DeleteFunc: controller.handleObject, - }) - - return controller -} - -// Run will set up the event handlers for types we are interested in, as well -// as syncing informer caches and starting workers. It will block until stopCh -// is closed, at which point it will shutdown the workqueue and wait for -// workers to finish processing their current work items. -func (c *Controller) Run(threadiness int, stopCh <-chan struct{}) error { - defer runtime.HandleCrash() - defer c.workqueue.ShutDown() - - // Start the informer factories to begin populating the informer caches - glog.Info("Starting ClusterBus controller") - - // Wait for the caches to be synced before starting workers - glog.Info("Waiting for informer caches to sync") - if ok := cache.WaitForCacheSync(stopCh, c.deploymentsSynced, c.servicesSynced, c.clusterBusesSynced); !ok { - return fmt.Errorf("failed to wait for caches to sync") - } - - glog.Info("Starting workers") - // Launch two workers to process ClusterBus resources - for i := 0; i < threadiness; i++ { - go wait.Until(c.runWorker, time.Second, stopCh) - } - - glog.Info("Started workers") - <-stopCh - glog.Info("Shutting down workers") - - return nil -} - -// runWorker is a long-running function that will continually call the -// processNextWorkItem function in order to read and process a message on the -// workqueue. -func (c *Controller) runWorker() { - for c.processNextWorkItem() { - } -} - -// processNextWorkItem will read a single work item off the workqueue and -// attempt to process it, by calling the syncHandler. -func (c *Controller) processNextWorkItem() bool { - obj, shutdown := c.workqueue.Get() - - if shutdown { - return false - } - - // We wrap this block in a func so we can defer c.workqueue.Done. - err := func(obj interface{}) error { - // We call Done here so the workqueue knows we have finished - // processing this item. We also must remember to call Forget if we - // do not want this work item being re-queued. For example, we do - // not call Forget if a transient error occurs, instead the item is - // put back on the workqueue and attempted again after a back-off - // period. - defer c.workqueue.Done(obj) - var key string - var ok bool - // We expect strings to come off the workqueue. These are of the - // form namespace/name. We do this as the delayed nature of the - // workqueue means the items in the informer cache may actually be - // more up to date that when the item was initially put onto the - // workqueue. - if key, ok = obj.(string); !ok { - // As the item in the workqueue is actually invalid, we call - // Forget here else we'd go into a loop of attempting to - // process a work item that is invalid. - c.workqueue.Forget(obj) - runtime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj)) - return nil - } - // Run the syncHandler, passing it the namespace/name string of the - // ClusterBus resource to be synced. - if err := c.syncHandler(key); err != nil { - return fmt.Errorf("error syncing clusterbus '%s': %v", key, err) - } - // Finally, if no error occurs we Forget this item so it does not - // get queued again until another change happens. - c.workqueue.Forget(obj) - glog.Infof("Successfully synced clusterbus '%s'", key) - return nil - }(obj) - - if err != nil { - runtime.HandleError(err) - return true - } - - return true -} - -// syncHandler compares the actual state with the desired, and attempts to -// converge the two. It then updates the Status block of the ClusterBus resource -// with the current status of the resource. -func (c *Controller) syncHandler(key string) error { - // Convert the namespace/name string into a distinct namespace and name - _, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - runtime.HandleError(fmt.Errorf("invalid resource key: %s", key)) - return nil - } - - // Get the ClusterBus resource with this name - clusterBus, err := c.clusterBusesLister.Get(name) - if err != nil { - // The ClusterBus resource may no longer exist, in which case we stop - // processing. - if errors.IsNotFound(err) { - runtime.HandleError(fmt.Errorf("clusterbus '%s' in work queue no longer exists", key)) - return nil - } - - return err - } - - // NEVER modify objects from the store. It's a read-only, local cache. - // You can use DeepCopy() to make a deep copy of original object and modify this copy - // Or create a copy manually for better performance - clusterBusCopy := clusterBus.DeepCopy() - - // Sync Service derived from the ClusterBus - dispatcherService, err := c.syncClusterBusDispatcherService(clusterBusCopy) - - if err != nil { - clusterBusCopy.Status.Service = nil - serviceCondition := util.NewBusCondition(channelsv1alpha1.BusServiceable, corev1.ConditionFalse, ServiceError, err.Error()) - util.SetBusCondition(&clusterBusCopy.Status, *serviceCondition) - c.compareAndUpdateBusStatus(clusterBus, clusterBusCopy) - return err - } - - clusterBusCopy.Status.Service = &corev1.LocalObjectReference{Name: dispatcherService.Name} - serviceCondition := util.NewBusCondition(channelsv1alpha1.BusServiceable, corev1.ConditionTrue, ServiceSynced, "service successfully synced") - util.SetBusCondition(&clusterBusCopy.Status, *serviceCondition) - - // Sync Deployment derived from the ClusterBus - _, err = c.syncClusterBusDispatcherDeployment(clusterBusCopy) - - if err != nil { - dispatchCondition := util.NewBusCondition(channelsv1alpha1.BusDispatching, corev1.ConditionFalse, DeploymentError, err.Error()) - util.SetBusCondition(&clusterBusCopy.Status, *dispatchCondition) - c.compareAndUpdateBusStatus(clusterBus, clusterBusCopy) - return err - } - - dispatchCondition := util.NewBusCondition(channelsv1alpha1.BusDispatching, corev1.ConditionTrue, DeploymentSynced, "deployment successfully synced") - util.SetBusCondition(&clusterBusCopy.Status, *dispatchCondition) - - // Sync Deployment derived from the ClusterBus - provisionerDeployment, err := c.syncClusterBusProvisionerDeployment(clusterBusCopy) - - if err != nil { - provisionCondition := util.NewBusCondition(channelsv1alpha1.BusProvisioning, corev1.ConditionFalse, DeploymentError, err.Error()) - util.SetBusCondition(&clusterBusCopy.Status, *provisionCondition) - c.compareAndUpdateBusStatus(clusterBus, clusterBusCopy) - return err - } - - if provisionerDeployment != nil { - provisionCondition := util.NewBusCondition(channelsv1alpha1.BusProvisioning, corev1.ConditionTrue, DeploymentSynced, "deployment successfully synced") - util.SetBusCondition(&clusterBusCopy.Status, *provisionCondition) - } else { - util.RemoveBusCondition(&clusterBusCopy.Status, channelsv1alpha1.BusProvisioning) - } - - // Finally, we update the status block of the ClusterBus resource to reflect the - // current state of the world - err = c.compareAndUpdateBusStatus(clusterBus, clusterBusCopy) - if err != nil { - return err - } - - c.recorder.Event(clusterBus, corev1.EventTypeNormal, SuccessSynced, MessageResourceSynced) - return nil -} - -func (c *Controller) syncClusterBusDispatcherService(clusterBus *channelsv1alpha1.ClusterBus) (*corev1.Service, error) { - // Get the service with the specified service name - serviceName := controller.ClusterBusDispatcherServiceName(clusterBus.ObjectMeta.Name) - service, err := c.servicesLister.Services(system.Namespace).Get(serviceName) - // If the resource doesn't exist, we'll create it - if errors.IsNotFound(err) { - service, err = c.kubeclientset.CoreV1().Services(system.Namespace).Create(newDispatcherService(clusterBus)) - } - - // If an error occurs during Get/Create, we'll requeue the item so we can - // attempt processing again later. This could have been caused by a - // temporary network failure, or any other transient reason. - if err != nil { - return nil, err - } - - // If the Service is not controlled by this ClusterBus resource, we should log - // a warning to the event recorder and return - if !metav1.IsControlledBy(service, clusterBus) { - msg := fmt.Sprintf(MessageResourceExists, service.Name) - c.recorder.Event(clusterBus, corev1.EventTypeWarning, ErrResourceExists, msg) - return nil, fmt.Errorf(msg) - } - - return service, nil -} - -func (c *Controller) syncClusterBusDispatcherDeployment(clusterBus *channelsv1alpha1.ClusterBus) (*appsv1.Deployment, error) { - // Get the deployment with the specified deployment name - deploymentName := controller.ClusterBusDispatcherDeploymentName(clusterBus.ObjectMeta.Name) - deployment, err := c.deploymentsLister.Deployments(system.Namespace).Get(deploymentName) - // If the resource doesn't exist, we'll create it - if errors.IsNotFound(err) { - deployment, err = c.kubeclientset.AppsV1().Deployments(system.Namespace).Create(newDispatcherDeployment(clusterBus)) - } - - // If an error occurs during Get/Create, we'll requeue the item so we can - // attempt processing again later. This could have been caused by a - // temporary network failure, or any other transient reason. - if err != nil { - return nil, err - } - - // If the Deployment is not controlled by this ClusterBus resource, we should log - // a warning to the event recorder and return - if !metav1.IsControlledBy(deployment, clusterBus) { - msg := fmt.Sprintf(MessageResourceExists, deployment.Name) - c.recorder.Event(clusterBus, corev1.EventTypeWarning, ErrResourceExists, msg) - return nil, fmt.Errorf(msg) - } - - // If the Deployment does not match the ClusterBus's proposed Deployment we should update - // the Deployment resource. - proposedDeployment := newDispatcherDeployment(clusterBus) - if !reflect.DeepEqual(proposedDeployment.Spec, deployment.Spec) { - glog.V(4).Infof("ClusterBus %s dispatcher spec updated", clusterBus.Name) - deployment, err = c.kubeclientset.AppsV1().Deployments(system.Namespace).Update(proposedDeployment) - - if err != nil { - return nil, err - } - } - - return deployment, nil -} - -func (c *Controller) syncClusterBusProvisionerDeployment(clusterBus *channelsv1alpha1.ClusterBus) (*appsv1.Deployment, error) { - provisioner := clusterBus.Spec.Provisioner - - // Get the deployment with the specified deployment name - deploymentName := controller.ClusterBusProvisionerDeploymentName(clusterBus.ObjectMeta.Name) - deployment, err := c.deploymentsLister.Deployments(system.Namespace).Get(deploymentName) - - // If the resource shouldn't exists - if provisioner == nil { - // If the resource exists, we'll delete it - if deployment != nil { - err = c.kubeclientset.AppsV1().Deployments(system.Namespace).Delete(deploymentName, nil) - } - if errors.IsNotFound(err) { - return nil, nil - } - return nil, err - } - - // If the resource doesn't exist, we'll create it - if errors.IsNotFound(err) { - deployment, err = c.kubeclientset.AppsV1().Deployments(system.Namespace).Create(newProvisionerDeployment(clusterBus)) - } - - // If an error occurs during Get/Create, we'll requeue the item so we can - // attempt processing again later. This could have been caused by a - // temporary network failure, or any other transient reason. - if err != nil { - return nil, err - } - - // If the Deployment is not controlled by this ClusterBus resource, we should log - // a warning to the event recorder and return - if !metav1.IsControlledBy(deployment, clusterBus) { - msg := fmt.Sprintf(MessageResourceExists, deployment.Name) - c.recorder.Event(clusterBus, corev1.EventTypeWarning, ErrResourceExists, msg) - return nil, fmt.Errorf(msg) - } - - // If the Deployment does not match the ClusterBus's proposed Deployment we should update - // the Deployment resource. - proposedDeployment := newProvisionerDeployment(clusterBus) - if !reflect.DeepEqual(proposedDeployment.Spec, deployment.Spec) { - glog.V(4).Infof("ClusterBus %s provisioner spec updated", clusterBus.Name) - deployment, err = c.kubeclientset.AppsV1().Deployments(system.Namespace).Update(proposedDeployment) - - if err != nil { - return nil, err - } - } - - return deployment, nil -} - -func (c *Controller) compareAndUpdateBusStatus(clusterBus *channelsv1alpha1.ClusterBus, clusterBusCopy *channelsv1alpha1.ClusterBus) error { - util.ConsolidateBusCondition(clusterBusCopy) - // Only update if status has changed - if !equality.Semantic.DeepEqual(clusterBus.Status, clusterBusCopy.Status) { - // If the CustomResourceSubresources feature gate is not enabled, - // we must use Update instead of UpdateStatus to update the Status block of the ClusterBus resource. - // UpdateStatus will not allow changes to the Spec of the resource, - // which is ideal for ensuring nothing other than resource status has been updated. - _, err := c.clusterbusclientset.ChannelsV1alpha1().ClusterBuses().Update(clusterBusCopy) - return err - } - return nil -} - -// enqueueClusterBus takes a ClusterBus resource and converts it into a namespace/name -// string which is then put onto the work queue. This method should *not* be -// passed resources of any type other than ClusterBus. -func (c *Controller) enqueueClusterBus(obj interface{}) { - var key string - var err error - if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { - runtime.HandleError(err) - return - } - c.workqueue.AddRateLimited(key) -} - -// handleObject will take any resource implementing metav1.Object and attempt -// to find the ClusterBus resource that 'owns' it. It does this by looking at the -// objects metadata.ownerReferences field for an appropriate OwnerReference. -// It then enqueues that ClusterBus resource to be processed. If the object does not -// have an appropriate OwnerReference, it will simply be skipped. -func (c *Controller) handleObject(obj interface{}) { - var object metav1.Object - var ok bool - if object, ok = obj.(metav1.Object); !ok { - tombstone, ok := obj.(cache.DeletedFinalStateUnknown) - if !ok { - runtime.HandleError(fmt.Errorf("error decoding object, invalid type")) - return - } - object, ok = tombstone.Obj.(metav1.Object) - if !ok { - runtime.HandleError(fmt.Errorf("error decoding object tombstone, invalid type")) - return - } - glog.V(4).Infof("Recovered deleted object '%s' from tombstone", object.GetName()) - } - glog.V(4).Infof("Processing object: %s", object.GetName()) - if ownerRef := metav1.GetControllerOf(object); ownerRef != nil { - // If this object is not owned by a ClusterBus, we should not do anything more - // with it. - if ownerRef.Kind != "ClusterBus" { - return - } - - clusterBus, err := c.clusterBusesLister.Get(ownerRef.Name) - if err != nil { - glog.V(4).Infof("ignoring orphaned object '%s' of clusterbus '%s'", object.GetSelfLink(), ownerRef.Name) - return - } - - c.enqueueClusterBus(clusterBus) - return - } -} - -// newDispatcherService creates a new Service for a ClusterBus resource. It also sets -// the appropriate OwnerReferences on the resource so handleObject can discover -// the ClusterBus resource that 'owns' it. -func newDispatcherService(clusterBus *channelsv1alpha1.ClusterBus) *corev1.Service { - labels := dispatcherLabels(clusterBus.Name) - return &corev1.Service{ - ObjectMeta: metav1.ObjectMeta{ - Name: controller.ClusterBusDispatcherServiceName(clusterBus.ObjectMeta.Name), - Namespace: system.Namespace, - Labels: labels, - OwnerReferences: []metav1.OwnerReference{ - *metav1.NewControllerRef(clusterBus, schema.GroupVersionKind{ - Group: channelsv1alpha1.SchemeGroupVersion.Group, - Version: channelsv1alpha1.SchemeGroupVersion.Version, - Kind: "ClusterBus", - }), - }, - }, - Spec: corev1.ServiceSpec{ - Selector: labels, - Ports: []corev1.ServicePort{ - { - Name: "http", - Port: 80, - TargetPort: intstr.FromInt(buses.MessageReceiverPort), - }, - }, - }, - } -} - -// newDispatcherDeployment creates a new Deployment for a ClusterBus resource. It also sets -// the appropriate OwnerReferences on the resource so handleObject can discover -// the ClusterBus resource that 'owns' it. -func newDispatcherDeployment(clusterBus *channelsv1alpha1.ClusterBus) *appsv1.Deployment { - labels := dispatcherLabels(clusterBus.Name) - one := int32(1) - container := clusterBus.Spec.Dispatcher.DeepCopy() - container.Env = append(container.Env, - corev1.EnvVar{ - Name: "PORT", - Value: "8080", - }, - corev1.EnvVar{ - Name: "BUS_NAME", - Value: clusterBus.Name, - }, - ) - volumes := []corev1.Volume{} - if clusterBus.Spec.Volumes != nil { - volumes = *clusterBus.Spec.Volumes - } - return &appsv1.Deployment{ - ObjectMeta: metav1.ObjectMeta{ - Name: controller.ClusterBusDispatcherDeploymentName(clusterBus.ObjectMeta.Name), - Namespace: system.Namespace, - OwnerReferences: []metav1.OwnerReference{ - *metav1.NewControllerRef(clusterBus, schema.GroupVersionKind{ - Group: channelsv1alpha1.SchemeGroupVersion.Group, - Version: channelsv1alpha1.SchemeGroupVersion.Version, - Kind: "ClusterBus", - }), - }, - }, - Spec: appsv1.DeploymentSpec{ - Replicas: &one, - Selector: &metav1.LabelSelector{ - MatchLabels: labels, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - "sidecar.istio.io/inject": "true", - }, - Labels: labels, - }, - Spec: corev1.PodSpec{ - ServiceAccountName: serviceAccountName, - Containers: []corev1.Container{ - *container, - }, - Volumes: volumes, - }, - }, - }, - } -} - -// newProvisionerDeployment creates a new Deployment for a ClusterBus resource. It also sets -// the appropriate OwnerReferences on the resource so handleObject can discover -// the ClusterBus resource that 'owns' it. -func newProvisionerDeployment(clusterBus *channelsv1alpha1.ClusterBus) *appsv1.Deployment { - labels := provisionerLabels(clusterBus.Name) - one := int32(1) - container := clusterBus.Spec.Provisioner.DeepCopy() - container.Env = append(container.Env, - corev1.EnvVar{ - Name: "BUS_NAME", - Value: clusterBus.Name, - }, - ) - volumes := []corev1.Volume{} - if clusterBus.Spec.Volumes != nil { - volumes = *clusterBus.Spec.Volumes - } - return &appsv1.Deployment{ - ObjectMeta: metav1.ObjectMeta{ - Name: controller.ClusterBusProvisionerDeploymentName(clusterBus.ObjectMeta.Name), - Namespace: system.Namespace, - OwnerReferences: []metav1.OwnerReference{ - *metav1.NewControllerRef(clusterBus, schema.GroupVersionKind{ - Group: channelsv1alpha1.SchemeGroupVersion.Group, - Version: channelsv1alpha1.SchemeGroupVersion.Version, - Kind: "ClusterBus", - }), - }, - }, - Spec: appsv1.DeploymentSpec{ - Replicas: &one, - Selector: &metav1.LabelSelector{ - MatchLabels: labels, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - "sidecar.istio.io/inject": "true", - }, - Labels: labels, - }, - Spec: corev1.PodSpec{ - ServiceAccountName: serviceAccountName, - Containers: []corev1.Container{ - *container, - }, - Volumes: volumes, - }, - }, - }, - } -} - -func dispatcherLabels(busName string) map[string]string { - return map[string]string{ - "clusterBus": busName, - "role": "dispatcher", - } -} - -func provisionerLabels(busName string) map[string]string { - return map[string]string{ - "clusterBus": busName, - "role": "provisioner", - } -} diff --git a/pkg/controller/clusterbus/stub_test.go b/pkg/controller/clusterbus/stub_test.go deleted file mode 100644 index a6d484c77fe..00000000000 --- a/pkg/controller/clusterbus/stub_test.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright 2018 The Knative 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 clusterbus - -import "testing" - -func TestStub(t *testing.T) { - // TODO: Implement tests in this directory, please. - // This file is used to make code coverage on this directly count. -} diff --git a/pkg/controller/eventing/inmemory/channel/reconcile.go b/pkg/controller/eventing/inmemory/channel/reconcile.go index 439361e8978..b8f56034219 100644 --- a/pkg/controller/eventing/inmemory/channel/reconcile.go +++ b/pkg/controller/eventing/inmemory/channel/reconcile.go @@ -19,30 +19,25 @@ package channel import ( "context" - eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" - "github.com/knative/eventing/pkg/controller" - cpcontroller "github.com/knative/eventing/pkg/controller/eventing/inmemory/clusterprovisioner" - "github.com/knative/eventing/pkg/sidecar/configmap" - "github.com/knative/eventing/pkg/sidecar/fanout" - "github.com/knative/eventing/pkg/sidecar/multichannelfanout" - "github.com/knative/eventing/pkg/system" - istiov1alpha3 "github.com/knative/pkg/apis/istio/v1alpha3" "go.uber.org/zap" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/equality" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/sets" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" + + eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + "github.com/knative/eventing/pkg/controller" + ccpcontroller "github.com/knative/eventing/pkg/controller/eventing/inmemory/clusterchannelprovisioner" + util "github.com/knative/eventing/pkg/provisioners" + "github.com/knative/eventing/pkg/sidecar/configmap" + "github.com/knative/eventing/pkg/sidecar/fanout" + "github.com/knative/eventing/pkg/sidecar/multichannelfanout" ) const ( - portName = "http" - portNumber = 80 finalizerName = controllerAgentName ) @@ -100,7 +95,7 @@ func (r *reconciler) Reconcile(request reconcile.Request) (reconcile.Result, err // regardless of the error. } - if updateStatusErr := r.updateChannel(ctx, c); updateStatusErr != nil { + if updateStatusErr := util.UpdateChannel(ctx, r.client, c); updateStatusErr != nil { logger.Info("Error updating Channel Status", zap.Error(updateStatusErr)) return reconcile.Result{}, updateStatusErr } @@ -109,10 +104,10 @@ func (r *reconciler) Reconcile(request reconcile.Request) (reconcile.Result, err } // shouldReconcile determines if this Controller should control (and therefore reconcile) a given -// ClusterProvisioner. This Controller only handles in-memory channels. +// ClusterChannelProvisioner. This Controller only handles in-memory channels. func (r *reconciler) shouldReconcile(c *eventingv1alpha1.Channel) bool { if c.Spec.Provisioner != nil { - return cpcontroller.IsControlled(c.Spec.Provisioner, cpcontroller.Channel) + return ccpcontroller.IsControlled(c.Spec.Provisioner) } return false } @@ -136,201 +131,39 @@ func (r *reconciler) reconcile(ctx context.Context, c *eventingv1alpha1.Channel) if c.DeletionTimestamp != nil { // K8s garbage collection will delete the K8s service and VirtualService for this channel. // We use a finalizer to ensure the channel config has been synced. - r.removeFinalizer(c) + util.RemoveFinalizer(c, finalizerName) return nil } - r.addFinalizer(c) - c.Status.SetSubscribable(c.Namespace, c.Name) + util.AddFinalizer(c, finalizerName) - if svc, err := r.createK8sService(ctx, c); err != nil { + svc, err := util.CreateK8sService(ctx, r.client, c) + if err != nil { logger.Info("Error creating the Channel's K8s Service", zap.Error(err)) return err - } else { - c.Status.SetSinkable(controller.ServiceHostName(svc.Name, svc.Namespace)) - } - - if err := r.createVirtualService(ctx, c); err != nil { - logger.Info("Error creating the Virtual Service for the Channel", zap.Error(err)) - return err - } - - c.Status.MarkProvisioned() - return nil -} - -func (r *reconciler) addFinalizer(c *eventingv1alpha1.Channel) { - finalizers := sets.NewString(c.Finalizers...) - finalizers.Insert(finalizerName) - c.Finalizers = finalizers.List() -} - -func (r *reconciler) removeFinalizer(c *eventingv1alpha1.Channel) { - finalizers := sets.NewString(c.Finalizers...) - finalizers.Delete(finalizerName) - c.Finalizers = finalizers.List() -} - -func (r *reconciler) getK8sService(ctx context.Context, c *eventingv1alpha1.Channel) (*corev1.Service, error) { - svcKey := types.NamespacedName{ - Namespace: c.Namespace, - Name: controller.ChannelServiceName(c.Name), - } - svc := &corev1.Service{} - err := r.client.Get(ctx, svcKey, svc) - return svc, err -} - -func (r *reconciler) createK8sService(ctx context.Context, c *eventingv1alpha1.Channel) (*corev1.Service, error) { - svc, err := r.getK8sService(ctx, c) - - if errors.IsNotFound(err) { - svc = newK8sService(c) - err = r.client.Create(ctx, svc) - } - - // If an error occurred in either Get or Create, we need to reconcile again. - if err != nil { - return nil, err } // Check if this Channel is the owner of the K8s service. if !metav1.IsControlledBy(svc, c) { - r.logger.Warn("Channel's K8s Service is not owned by the Channel", zap.Any("channel", c), zap.Any("service", svc)) - } - return svc, nil -} - -func (r *reconciler) getVirtualService(ctx context.Context, c *eventingv1alpha1.Channel) (*istiov1alpha3.VirtualService, error) { - vsk := client.ObjectKey{ - Namespace: c.Namespace, - Name: controller.ChannelVirtualServiceName(c.ObjectMeta.Name), + logger.Warn("Channel's K8s Service is not owned by the Channel", zap.Any("channel", c), zap.Any("service", svc)) } - vs := &istiov1alpha3.VirtualService{} - err := r.client.Get(ctx, vsk, vs) - return vs, err -} -func (r *reconciler) createVirtualService(ctx context.Context, c *eventingv1alpha1.Channel) error { - virtualService, err := r.getVirtualService(ctx, c) + c.Status.SetAddress(controller.ServiceHostName(svc.Name, svc.Namespace)) - // If the resource doesn't exist, we'll create it - if errors.IsNotFound(err) { - virtualService = newVirtualService(c) - err = r.client.Create(ctx, virtualService) - } + virtualService, err := util.CreateVirtualService(ctx, r.client, c) - // If an error occurs during Get/Create, we'll requeue the item so we can - // attempt processing again later. This could have been caused by a - // temporary network failure, or any other transient reason. if err != nil { + logger.Info("Error creating the Virtual Service for the Channel", zap.Error(err)) return err } // If the Virtual Service is not controlled by this Channel, we should log a warning, but don't // consider it an error. if !metav1.IsControlledBy(virtualService, c) { - r.logger.Warn("VirtualService not owned by Channel", zap.Any("channel", c), zap.Any("virtualService", virtualService)) + logger.Warn("VirtualService not owned by Channel", zap.Any("channel", c), zap.Any("virtualService", virtualService)) } - return nil -} -// newK8sService creates a new Service for a Channel resource. It also sets the appropriate -// OwnerReferences on the resource so handleObject can discover the Channel resource that 'owns' it. -// As well as being garbage collected when the Channel is deleted. -func newK8sService(c *eventingv1alpha1.Channel) *corev1.Service { - labels := map[string]string{ - "channel": c.Name, - "provisioner": c.Spec.Provisioner.Ref.Name, - } - return &corev1.Service{ - ObjectMeta: metav1.ObjectMeta{ - Name: controller.ChannelServiceName(c.ObjectMeta.Name), - Namespace: c.Namespace, - Labels: labels, - OwnerReferences: []metav1.OwnerReference{ - *metav1.NewControllerRef(c, schema.GroupVersionKind{ - Group: eventingv1alpha1.SchemeGroupVersion.Group, - Version: eventingv1alpha1.SchemeGroupVersion.Version, - Kind: "Channel", - }), - }, - }, - Spec: corev1.ServiceSpec{ - Ports: []corev1.ServicePort{ - { - Name: portName, - Port: portNumber, - }, - }, - }, - } -} - -// newVirtualService creates a new VirtualService for a Channel resource. It also sets the -// appropriate OwnerReferences on the resource so handleObject can discover the Channel resource -// that 'owns' it. As well as being garbage collected when the Channel is deleted. -func newVirtualService(channel *eventingv1alpha1.Channel) *istiov1alpha3.VirtualService { - labels := map[string]string{ - "channel": channel.Name, - "provisioner": channel.Spec.Provisioner.Ref.Name, - } - destinationHost := controller.ServiceHostName(controller.ClusterBusDispatcherServiceName(channel.Spec.Provisioner.Ref.Name), system.Namespace) - return &istiov1alpha3.VirtualService{ - ObjectMeta: metav1.ObjectMeta{ - Name: controller.ChannelVirtualServiceName(channel.Name), - Namespace: channel.Namespace, - Labels: labels, - OwnerReferences: []metav1.OwnerReference{ - *metav1.NewControllerRef(channel, schema.GroupVersionKind{ - Group: eventingv1alpha1.SchemeGroupVersion.Group, - Version: eventingv1alpha1.SchemeGroupVersion.Version, - Kind: "Channel", - }), - }, - }, - Spec: istiov1alpha3.VirtualServiceSpec{ - Hosts: []string{ - controller.ServiceHostName(controller.ChannelServiceName(channel.Name), channel.Namespace), - controller.ChannelHostName(channel.Name, channel.Namespace), - }, - Http: []istiov1alpha3.HTTPRoute{{ - Rewrite: &istiov1alpha3.HTTPRewrite{ - Authority: controller.ChannelHostName(channel.Name, channel.Namespace), - }, - Route: []istiov1alpha3.DestinationWeight{{ - Destination: istiov1alpha3.Destination{ - Host: destinationHost, - Port: istiov1alpha3.PortSelector{ - Number: portNumber, - }, - }}, - }}, - }, - }, - } -} - -func (r *reconciler) updateChannel(ctx context.Context, u *eventingv1alpha1.Channel) error { - o := &eventingv1alpha1.Channel{} - if err := r.client.Get(ctx, client.ObjectKey{Namespace: u.Namespace, Name: u.Name}, o); err != nil { - r.logger.Info("Error getting Channel for status update", zap.Error(err), zap.Any("updatedChannel", u)) - return err - } - - updated := false - if !equality.Semantic.DeepEqual(o.Finalizers, u.Finalizers) { - updated = true - o.SetFinalizers(u.Finalizers) - } - if !equality.Semantic.DeepEqual(o.Status, u.Status) { - updated = true - o.Status = u.Status - } - - if updated { - return r.client.Update(ctx, o) - } + c.Status.MarkProvisioned() return nil } @@ -386,16 +219,16 @@ func (r *reconciler) createNewConfigMap(data map[string]string) *corev1.ConfigMa func multiChannelFanoutConfig(channels []eventingv1alpha1.Channel) *multichannelfanout.Config { cc := make([]multichannelfanout.ChannelConfig, 0) for _, c := range channels { - channelable := c.Spec.Channelable - if channelable != nil { - cc = append(cc, multichannelfanout.ChannelConfig{ - Namespace: c.Namespace, - Name: c.Name, - FanoutConfig: fanout.Config{ - Subscriptions: c.Spec.Channelable.Subscribers, - }, - }) + channelConfig := multichannelfanout.ChannelConfig{ + Namespace: c.Namespace, + Name: c.Name, + } + if c.Spec.Subscribable != nil { + channelConfig.FanoutConfig = fanout.Config{ + Subscriptions: c.Spec.Subscribable.Subscribers, + } } + cc = append(cc, channelConfig) } return &multichannelfanout.Config{ ChannelConfigs: cc, diff --git a/pkg/controller/eventing/inmemory/channel/reconcile_test.go b/pkg/controller/eventing/inmemory/channel/reconcile_test.go index 13466bad4ae..7542a4df80e 100644 --- a/pkg/controller/eventing/inmemory/channel/reconcile_test.go +++ b/pkg/controller/eventing/inmemory/channel/reconcile_test.go @@ -24,12 +24,13 @@ import ( "testing" "github.com/google/go-cmp/cmp" + eventingduck "github.com/knative/eventing/pkg/apis/duck/v1alpha1" eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" controllertesting "github.com/knative/eventing/pkg/controller/testing" + util "github.com/knative/eventing/pkg/provisioners" "github.com/knative/eventing/pkg/sidecar/configmap" "github.com/knative/eventing/pkg/sidecar/fanout" "github.com/knative/eventing/pkg/sidecar/multichannelfanout" - duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" istiov1alpha3 "github.com/knative/pkg/apis/istio/v1alpha3" "go.uber.org/zap" corev1 "k8s.io/api/core/v1" @@ -43,7 +44,7 @@ import ( ) const ( - cpName = "in-memory-channel" + ccpName = "in-memory-channel" cNamespace = "test-namespace" cName = "test-channel" @@ -73,16 +74,16 @@ var ( Namespace: cNamespace, Name: "c1", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: "foo", + SubscriberURI: "foo", }, { - SinkableDomain: "bar", + ReplyURI: "bar", }, { - CallableDomain: "baz", - SinkableDomain: "qux", + SubscriberURI: "baz", + ReplyURI: "qux", }, }, }, @@ -91,9 +92,9 @@ var ( Namespace: cNamespace, Name: "c3", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: "steve", + SubscriberURI: "steve", }, }, }, @@ -111,22 +112,20 @@ var ( Kind: "Channel", }, Spec: eventingv1alpha1.ChannelSpec{ - Provisioner: &eventingv1alpha1.ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: cpName, - }, + Provisioner: &corev1.ObjectReference{ + Name: ccpName, }, - Channelable: &duckv1alpha1.Channelable{ - Subscribers: []duckv1alpha1.ChannelSubscriberSpec{ + Subscribable: &eventingduck.Subscribable{ + Subscribers: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: "foo", + SubscriberURI: "foo", }, { - SinkableDomain: "bar", + ReplyURI: "bar", }, { - CallableDomain: "baz", - SinkableDomain: "qux", + SubscriberURI: "baz", + ReplyURI: "qux", }, }, }, @@ -141,15 +140,13 @@ var ( Kind: "Channel", }, Spec: eventingv1alpha1.ChannelSpec{ - Provisioner: &eventingv1alpha1.ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: "some-other-provisioner", - }, + Provisioner: &corev1.ObjectReference{ + Name: "some-other-provisioner", }, - Channelable: &duckv1alpha1.Channelable{ - Subscribers: []duckv1alpha1.ChannelSubscriberSpec{ + Subscribable: &eventingduck.Subscribable{ + Subscribers: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: "anything", + SubscriberURI: "anything", }, }, }, @@ -164,15 +161,13 @@ var ( Kind: "Channel", }, Spec: eventingv1alpha1.ChannelSpec{ - Provisioner: &eventingv1alpha1.ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: cpName, - }, + Provisioner: &corev1.ObjectReference{ + Name: ccpName, }, - Channelable: &duckv1alpha1.Channelable{ - Subscribers: []duckv1alpha1.ChannelSubscriberSpec{ + Subscribable: &eventingduck.Subscribable{ + Subscribers: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: "steve", + SubscriberURI: "steve", }, }, }, @@ -225,7 +220,7 @@ func TestReconcile(t *testing.T) { { Name: "Channel not reconciled - nil ref", InitialState: []runtime.Object{ - makeChannelNilRef(), + makeChannelNilProvisioner(), }, }, { @@ -314,7 +309,7 @@ func TestReconcile(t *testing.T) { MockGets: errorGettingK8sService(), }, WantPresent: []runtime.Object{ - makeChannelWithFinalizerAndSubscribable(), + makeChannelWithFinalizer(), }, WantErrMsg: testErrorMessage, }, @@ -329,7 +324,7 @@ func TestReconcile(t *testing.T) { }, WantPresent: []runtime.Object{ // TODO: This should have a useful error message saying that the K8s Service failed. - makeChannelWithFinalizerAndSubscribable(), + makeChannelWithFinalizer(), }, WantErrMsg: testErrorMessage, }, @@ -358,7 +353,7 @@ func TestReconcile(t *testing.T) { WantPresent: []runtime.Object{ // TODO: This should have a useful error message saying that the VirtualService // failed. - makeChannelWithFinalizerAndSubscribableAndSinkable(), + makeChannelWithFinalizerAndAddress(), }, WantErrMsg: testErrorMessage, }, @@ -375,7 +370,7 @@ func TestReconcile(t *testing.T) { WantPresent: []runtime.Object{ // TODO: This should have a useful error message saying that the VirtualService // failed. - makeChannelWithFinalizerAndSubscribableAndSinkable(), + makeChannelWithFinalizerAndAddress(), }, WantErrMsg: testErrorMessage, }, @@ -429,7 +424,47 @@ func TestReconcile(t *testing.T) { // not string equality, so it can't be done in WantPresent. Instead, we verify // during the update call, swapping out the data and WantPresent with that inserted // data. - MockUpdates: verifyConfigMapData(), + MockUpdates: verifyConfigMapData(channelsConfig), + }, + WantPresent: []runtime.Object{ + makeReadyChannel(), + makeK8sService(), + makeVirtualService(), + makeConfigMapWithVerifyConfigMapData(), + }, + }, + { + Name: "Channel reconcile successful - Channel has no subscribers", + InitialState: []runtime.Object{ + makeChannel(), + makeConfigMap(), + }, + Mocks: controllertesting.Mocks{ + MockLists: (&paginatedChannelsListStruct{channels: []eventingv1alpha1.Channel{ + { + ObjectMeta: metav1.ObjectMeta{ + Namespace: "high-consul", + Name: "duarte", + }, + Spec: eventingv1alpha1.ChannelSpec{ + Provisioner: &corev1.ObjectReference{ + Name: ccpName, + }, + }, + }, + }}).MockLists(), + // This is more accurate to be in WantPresent, but we need to check JSON equality, + // not string equality, so it can't be done in WantPresent. Instead, we verify + // during the update call, swapping out the data and WantPresent with that inserted + // data. + MockUpdates: verifyConfigMapData(multichannelfanout.Config{ + ChannelConfigs: []multichannelfanout.ChannelConfig{ + { + Namespace: "high-consul", + Name: "duarte", + }, + }, + }), }, WantPresent: []runtime.Object{ makeReadyChannel(), @@ -472,10 +507,8 @@ func makeChannel() *eventingv1alpha1.Channel { UID: cUID, }, Spec: eventingv1alpha1.ChannelSpec{ - Provisioner: &eventingv1alpha1.ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: cpName, - }, + Provisioner: &corev1.ObjectReference{ + Name: ccpName, }, }, } @@ -483,21 +516,15 @@ func makeChannel() *eventingv1alpha1.Channel { return c } -func makeChannelWithFinalizerAndSubscribable() *eventingv1alpha1.Channel { +func makeChannelWithFinalizerAndAddress() *eventingv1alpha1.Channel { c := makeChannelWithFinalizer() - c.Status.SetSubscribable(c.Namespace, c.Name) - return c -} - -func makeChannelWithFinalizerAndSubscribableAndSinkable() *eventingv1alpha1.Channel { - c := makeChannelWithFinalizerAndSubscribable() - c.Status.SetSinkable(fmt.Sprintf("%s-channel.%s.svc.cluster.local", c.Name, c.Namespace)) + c.Status.SetAddress(fmt.Sprintf("%s-channel.%s.svc.cluster.local", c.Name, c.Namespace)) return c } func makeReadyChannel() *eventingv1alpha1.Channel { - // Ready channels have the finalizer and are Subscribable and Sinkable. - c := makeChannelWithFinalizerAndSubscribableAndSinkable() + // Ready channels have the finalizer and are Addressable. + c := makeChannelWithFinalizerAndAddress() c.Status.MarkProvisioned() return c } @@ -508,21 +535,15 @@ func makeChannelNilProvisioner() *eventingv1alpha1.Channel { return c } -func makeChannelNilRef() *eventingv1alpha1.Channel { - c := makeChannel() - c.Spec.Provisioner.Ref = nil - return c -} - func makeChannelWithWrongProvisionerNamespace() *eventingv1alpha1.Channel { c := makeChannel() - c.Spec.Provisioner.Ref.Namespace = "wrong-namespace" + c.Spec.Provisioner.Namespace = "wrong-namespace" return c } func makeChannelWithWrongProvisionerName() *eventingv1alpha1.Channel { c := makeChannel() - c.Spec.Provisioner.Ref.Name = "wrong-name" + c.Spec.Provisioner.Name = "wrong-name" return c } @@ -575,7 +596,7 @@ func makeK8sService() *corev1.Service { Namespace: cNamespace, Labels: map[string]string{ "channel": cName, - "provisioner": cpName, + "provisioner": ccpName, }, OwnerReferences: []metav1.OwnerReference{ { @@ -591,8 +612,8 @@ func makeK8sService() *corev1.Service { Spec: corev1.ServiceSpec{ Ports: []corev1.ServicePort{ { - Name: portName, - Port: portNumber, + Name: util.PortName, + Port: util.PortNumber, }, }, }, @@ -616,7 +637,7 @@ func makeVirtualService() *istiov1alpha3.VirtualService { Namespace: cNamespace, Labels: map[string]string{ "channel": cName, - "provisioner": cpName, + "provisioner": ccpName, }, OwnerReferences: []metav1.OwnerReference{ { @@ -642,7 +663,7 @@ func makeVirtualService() *istiov1alpha3.VirtualService { Destination: istiov1alpha3.Destination{ Host: "in-memory-channel-clusterbus.knative-eventing.svc.cluster.local", Port: istiov1alpha3.PortSelector{ - Number: portNumber, + Number: util.PortNumber, }, }}, }}, @@ -797,7 +818,7 @@ func (p *paginatedChannelsListStruct) MockLists() []controllertesting.MockList { } } -func verifyConfigMapData() []controllertesting.MockUpdate { +func verifyConfigMapData(expected multichannelfanout.Config) []controllertesting.MockUpdate { return []controllertesting.MockUpdate{ func(innerClient client.Client, ctx context.Context, obj runtime.Object) (controllertesting.MockHandled, error) { if cm, ok := obj.(*corev1.ConfigMap); ok { @@ -808,7 +829,7 @@ func verifyConfigMapData() []controllertesting.MockUpdate { return controllertesting.Handled, fmt.Errorf("test is unable to unmarshal ConfigMap data: %v", err) } - if diff := cmp.Diff(c, channelsConfig); diff != "" { + if diff := cmp.Diff(c, expected); diff != "" { return controllertesting.Handled, fmt.Errorf("test got unwanted ChannelsConfig (-want +got) %s", diff) } diff --git a/pkg/controller/eventing/inmemory/clusterprovisioner/controller.go b/pkg/controller/eventing/inmemory/clusterchannelprovisioner/controller.go similarity index 79% rename from pkg/controller/eventing/inmemory/clusterprovisioner/controller.go rename to pkg/controller/eventing/inmemory/clusterchannelprovisioner/controller.go index 3296a144733..3518b86939c 100644 --- a/pkg/controller/eventing/inmemory/clusterprovisioner/controller.go +++ b/pkg/controller/eventing/inmemory/clusterchannelprovisioner/controller.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package clusterprovisioner +package clusterchannelprovisioner import ( eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" @@ -36,7 +36,7 @@ const ( func ProvideController(mgr manager.Manager, logger *zap.Logger) (controller.Controller, error) { logger = logger.With(zap.String("controller", controllerAgentName)) - // Setup a new controller to Reconcile ClusterProvisioners that are in-memory channels. + // Setup a new controller to Reconcile ClusterChannelProvisioners that are in-memory channels. r := &reconciler{ recorder: mgr.GetRecorder(controllerAgentName), logger: logger, @@ -49,19 +49,19 @@ func ProvideController(mgr manager.Manager, logger *zap.Logger) (controller.Cont return nil, err } - // Watch ClusterProvisioners. + // Watch ClusterChannelProvisioners. err = c.Watch(&source.Kind{ - Type: &eventingv1alpha1.ClusterProvisioner{}, + Type: &eventingv1alpha1.ClusterChannelProvisioner{}, }, &handler.EnqueueRequestForObject{}) if err != nil { - logger.Error("Unable to watch ClusterProvisioners.", zap.Error(err), zap.Any("type", &eventingv1alpha1.ClusterProvisioner{})) + logger.Error("Unable to watch ClusterChannelProvisioners.", zap.Error(err), zap.Any("type", &eventingv1alpha1.ClusterChannelProvisioner{})) return nil, err } - // Watch the K8s Services that are owned by ClusterProvisioners. + // Watch the K8s Services that are owned by ClusterChannelProvisioners. err = c.Watch(&source.Kind{ Type: &corev1.Service{}, - }, &handler.EnqueueRequestForOwner{OwnerType: &eventingv1alpha1.ClusterProvisioner{}, IsController: true}) + }, &handler.EnqueueRequestForOwner{OwnerType: &eventingv1alpha1.ClusterChannelProvisioner{}, IsController: true}) if err != nil { logger.Error("Unable to watch K8s Services.", zap.Error(err)) return nil, err diff --git a/pkg/controller/eventing/inmemory/clusterchannelprovisioner/reconcile.go b/pkg/controller/eventing/inmemory/clusterchannelprovisioner/reconcile.go new file mode 100644 index 00000000000..eb7420627bd --- /dev/null +++ b/pkg/controller/eventing/inmemory/clusterchannelprovisioner/reconcile.go @@ -0,0 +1,144 @@ +/* +Copyright 2018 The Knative 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 clusterchannelprovisioner + +import ( + "context" + + "go.uber.org/zap" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/tools/record" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + util "github.com/knative/eventing/pkg/provisioners" +) + +const ( + // Name is the name of the in-memory channel ClusterChannelProvisioner. + Name = "in-memory-channel" + + // Channel is the name of the Channel resource in eventing.knative.dev/v1alpha1. + Channel = "Channel" +) + +type reconciler struct { + client client.Client + recorder record.EventRecorder + logger *zap.Logger +} + +// Verify the struct implements reconcile.Reconciler +var _ reconcile.Reconciler = &reconciler{} + +func (r *reconciler) InjectClient(c client.Client) error { + r.client = c + return nil +} + +func (r *reconciler) Reconcile(request reconcile.Request) (reconcile.Result, error) { + //TODO use this to store the logger and set a deadline + ctx := context.TODO() + logger := r.logger.With(zap.Any("request", request)) + + ccp := &eventingv1alpha1.ClusterChannelProvisioner{} + err := r.client.Get(ctx, request.NamespacedName, ccp) + + // The ClusterChannelProvisioner may have been deleted since it was added to the workqueue. If so, + // there is nothing to be done. + if errors.IsNotFound(err) { + logger.Info("Could not find ClusterChannelProvisioner", zap.Error(err)) + return reconcile.Result{}, nil + } + + // Any other error should be retried in another reconciliation. + if err != nil { + logger.Error("Unable to Get ClusterChannelProvisioner", zap.Error(err)) + return reconcile.Result{}, err + } + + // Does this Controller control this ClusterChannelProvisioner? + if !shouldReconcile(ccp.Namespace, ccp.Name) { + logger.Info("Not reconciling ClusterChannelProvisioner, it is not controlled by this Controller", zap.String("APIVersion", ccp.APIVersion), zap.String("Kind", ccp.Kind), zap.String("Namespace", ccp.Namespace), zap.String("name", ccp.Name)) + return reconcile.Result{}, nil + } + logger.Info("Reconciling ClusterChannelProvisioner.") + + // Modify a copy of this object, rather than the original. + ccp = ccp.DeepCopy() + + err = r.reconcile(ctx, ccp) + if err != nil { + logger.Info("Error reconciling ClusterChannelProvisioner", zap.Error(err)) + // Note that we do not return the error here, because we want to update the Status + // regardless of the error. + } + + if updateStatusErr := util.UpdateClusterChannelProvisionerStatus(ctx, r.client, ccp); updateStatusErr != nil { + logger.Info("Error updating ClusterChannelProvisioner Status", zap.Error(updateStatusErr)) + return reconcile.Result{}, updateStatusErr + } + + return reconcile.Result{}, err +} + +// IsControlled determines if the in-memory Channel Controller should control (and therefore +// reconcile) a given object, based on that object's ClusterChannelProvisioner reference. +func IsControlled(ref *corev1.ObjectReference) bool { + if ref != nil { + return shouldReconcile(ref.Namespace, ref.Name) + } + return false +} + +// shouldReconcile determines if this Controller should control (and therefore reconcile) a given +// ClusterChannelProvisioner. This Controller only handles in-memory channels. +func shouldReconcile(namespace, name string) bool { + return namespace == "" && name == Name +} + +func (r *reconciler) reconcile(ctx context.Context, ccp *eventingv1alpha1.ClusterChannelProvisioner) error { + logger := r.logger.With(zap.Any("clusterChannelProvisioner", ccp)) + + // We are syncing one thing. + // 1. The K8s Service to talk to all in-memory Channels. + // - There is a single K8s Service for all requests going any in-memory Channel. + + if ccp.DeletionTimestamp != nil { + // K8s garbage collection will delete the dispatcher service, once this ClusterChannelProvisioner + // is deleted, so we don't need to do anything. + return nil + } + + svc, err := util.CreateDispatcherService(ctx, r.client, ccp) + + if err != nil { + logger.Info("Error creating the ClusterChannelProvisioner's K8s Service", zap.Error(err)) + return err + } + + // Check if this ClusterChannelProvisioner is the owner of the K8s service. + if !metav1.IsControlledBy(svc, ccp) { + logger.Warn("ClusterChannelProvisioner's K8s Service is not owned by the ClusterChannelProvisioner", zap.Any("clusterChannelProvisioner", ccp), zap.Any("service", svc)) + } + + ccp.Status.MarkReady() + return nil +} diff --git a/pkg/controller/eventing/inmemory/clusterprovisioner/reconcile_test.go b/pkg/controller/eventing/inmemory/clusterchannelprovisioner/reconcile_test.go similarity index 69% rename from pkg/controller/eventing/inmemory/clusterprovisioner/reconcile_test.go rename to pkg/controller/eventing/inmemory/clusterchannelprovisioner/reconcile_test.go index f0bd62dbdce..030e8dd2025 100644 --- a/pkg/controller/eventing/inmemory/clusterprovisioner/reconcile_test.go +++ b/pkg/controller/eventing/inmemory/clusterchannelprovisioner/reconcile_test.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package clusterprovisioner +package clusterchannelprovisioner import ( "context" @@ -22,8 +22,6 @@ import ( "fmt" "testing" - eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" - "github.com/knative/eventing/pkg/system" duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" "go.uber.org/zap" corev1 "k8s.io/api/core/v1" @@ -35,11 +33,14 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" + eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" controllertesting "github.com/knative/eventing/pkg/controller/testing" + util "github.com/knative/eventing/pkg/provisioners" + "github.com/knative/eventing/pkg/system" ) const ( - cpUid = "test-uid" + ccpUid = "test-uid" testErrorMessage = "test-induced-error" ) @@ -75,63 +76,36 @@ func TestInjectClient(t *testing.T) { func TestIsControlled(t *testing.T) { testCases := map[string]struct { - ref *eventingv1alpha1.ProvisionerReference - kind string + ref *corev1.ObjectReference isControlled bool }{ "nil": { ref: nil, - kind: "Channel", - isControlled: false, - }, - "ref nil": { - ref: &eventingv1alpha1.ProvisionerReference{ - Ref: nil, - }, - kind: "Channel", isControlled: false, }, "wrong namespace": { - ref: &eventingv1alpha1.ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Namespace: "other", - Name: Name, - }, + ref: &corev1.ObjectReference{ + Namespace: "other", + Name: Name, }, - kind: "Channel", isControlled: false, }, "wrong name": { - ref: &eventingv1alpha1.ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: "other-name", - }, + ref: &corev1.ObjectReference{ + Name: "other-name", }, - kind: "Channel", - isControlled: false, - }, - "wrong kind": { - ref: &eventingv1alpha1.ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: Name, - }, - }, - kind: "Source", isControlled: false, }, "is controlled": { - ref: &eventingv1alpha1.ProvisionerReference{ - Ref: &corev1.ObjectReference{ - Name: Name, - }, + ref: &corev1.ObjectReference{ + Name: Name, }, - kind: "Channel", isControlled: true, }, } for n, tc := range testCases { t.Run(n, func(t *testing.T) { - isControlled := IsControlled(tc.ref, tc.kind) + isControlled := IsControlled(tc.ref) if isControlled != tc.isControlled { t.Errorf("Expected: %v. Actual: %v", tc.isControlled, isControlled) } @@ -142,13 +116,13 @@ func TestIsControlled(t *testing.T) { func TestReconcile(t *testing.T) { testCases := []controllertesting.TestCase{ { - Name: "CP not found", + Name: "CCP not found", }, { - Name: "Unable to get CP", + Name: "Unable to get CCP", Mocks: controllertesting.Mocks{ MockGets: []controllertesting.MockGet{ - errorGettingClusterProvisioner(), + errorGettingClusterChannelProvisioner(), }, }, WantErrMsg: testErrorMessage, @@ -156,7 +130,7 @@ func TestReconcile(t *testing.T) { { Name: "Should not reconcile - namespace", InitialState: []runtime.Object{ - &eventingv1alpha1.ClusterProvisioner{ + &eventingv1alpha1.ClusterChannelProvisioner{ ObjectMeta: metav1.ObjectMeta{ Namespace: "not empty string", Name: Name, @@ -167,7 +141,7 @@ func TestReconcile(t *testing.T) { { Name: "Should not reconcile - name", InitialState: []runtime.Object{ - &eventingv1alpha1.ClusterProvisioner{ + &eventingv1alpha1.ClusterChannelProvisioner{ ObjectMeta: metav1.ObjectMeta{ Name: "wrong-name", }, @@ -179,13 +153,13 @@ func TestReconcile(t *testing.T) { Name: "Delete succeeds", // Deleting does nothing. InitialState: []runtime.Object{ - makeDeletingClusterProvisioner(), + makeDeletingClusterChannelProvisioner(), }, }, { Name: "Create dispatcher fails", InitialState: []runtime.Object{ - makeClusterProvisioner(), + makeClusterChannelProvisioner(), }, Mocks: controllertesting.Mocks{ MockGets: []controllertesting.MockGet{ @@ -197,50 +171,50 @@ func TestReconcile(t *testing.T) { { Name: "Create dispatcher - already exists", InitialState: []runtime.Object{ - makeClusterProvisioner(), + makeClusterChannelProvisioner(), makeK8sService(), }, WantPresent: []runtime.Object{ - makeReadyClusterProvisioner(), + makeReadyClusterChannelProvisioner(), }, }, { - Name: "Create dispatcher - not owned by CP", + Name: "Create dispatcher - not owned by CCP", InitialState: []runtime.Object{ - makeClusterProvisioner(), - makeK8sServiceNotOwnedByClusterProvisioner(), + makeClusterChannelProvisioner(), + makeK8sServiceNotOwnedByClusterChannelProvisioner(), }, WantPresent: []runtime.Object{ - makeReadyClusterProvisioner(), + makeReadyClusterChannelProvisioner(), }, }, { Name: "Create dispatcher succeeds", InitialState: []runtime.Object{ - makeClusterProvisioner(), + makeClusterChannelProvisioner(), }, WantPresent: []runtime.Object{ - makeReadyClusterProvisioner(), + makeReadyClusterChannelProvisioner(), makeK8sService(), }, }, { - Name: "Error getting CP for updating Status", - // Nothing to create or update other than the status of CP itself. + Name: "Error getting CCP for updating Status", + // Nothing to create or update other than the status of CCP itself. InitialState: []runtime.Object{ - makeClusterProvisioner(), + makeClusterChannelProvisioner(), makeK8sService(), }, Mocks: controllertesting.Mocks{ - MockGets: oneSuccessfulClusterProvisionerGet(), + MockGets: oneSuccessfulClusterChannelProvisionerGet(), }, WantErrMsg: testErrorMessage, }, { Name: "Error updating Status", - // Nothing to create or update other than the status of CP itself. + // Nothing to create or update other than the status of CCP itself. InitialState: []runtime.Object{ - makeClusterProvisioner(), + makeClusterChannelProvisioner(), makeK8sService(), }, Mocks: controllertesting.Mocks{ @@ -267,40 +241,34 @@ func TestReconcile(t *testing.T) { } } -func makeClusterProvisioner() *eventingv1alpha1.ClusterProvisioner { - return &eventingv1alpha1.ClusterProvisioner{ +func makeClusterChannelProvisioner() *eventingv1alpha1.ClusterChannelProvisioner { + return &eventingv1alpha1.ClusterChannelProvisioner{ TypeMeta: metav1.TypeMeta{ APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), - Kind: "ClusterProvisioner", + Kind: "ClusterChannelProvisioner", }, ObjectMeta: metav1.ObjectMeta{ Name: Name, - UID: cpUid, - }, - Spec: eventingv1alpha1.ClusterProvisionerSpec{ - Reconciles: metav1.GroupKind{ - Group: "eventing.knative.dev/v1alpha1", - Kind: "Channel", - }, + UID: ccpUid, }, + Spec: eventingv1alpha1.ClusterChannelProvisionerSpec{}, } } -func makeReadyClusterProvisioner() *eventingv1alpha1.ClusterProvisioner { - cp := makeClusterProvisioner() - cp.Status.Conditions = []duckv1alpha1.Condition{ - { - Type: duckv1alpha1.ConditionReady, - Status: corev1.ConditionTrue, - }, - } - return cp +func makeReadyClusterChannelProvisioner() *eventingv1alpha1.ClusterChannelProvisioner { + ccp := makeClusterChannelProvisioner() + ccp.Status.Conditions = []duckv1alpha1.Condition{{ + Type: duckv1alpha1.ConditionReady, + Status: corev1.ConditionTrue, + Severity: duckv1alpha1.ConditionSeverityError, + }} + return ccp } -func makeDeletingClusterProvisioner() *eventingv1alpha1.ClusterProvisioner { - cp := makeClusterProvisioner() - cp.DeletionTimestamp = &deletionTime - return cp +func makeDeletingClusterChannelProvisioner() *eventingv1alpha1.ClusterChannelProvisioner { + ccp := makeClusterChannelProvisioner() + ccp.DeletionTimestamp = &deletionTime + return ccp } func makeK8sService() *corev1.Service { @@ -315,17 +283,17 @@ func makeK8sService() *corev1.Service { OwnerReferences: []metav1.OwnerReference{ { APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), - Kind: "ClusterProvisioner", + Kind: "ClusterChannelProvisioner", Name: Name, - UID: cpUid, + UID: ccpUid, Controller: &truePointer, BlockOwnerDeletion: &truePointer, }, }, - Labels: dispatcherLabels(Name), + Labels: util.DispatcherLabels(Name), }, Spec: corev1.ServiceSpec{ - Selector: dispatcherLabels(Name), + Selector: util.DispatcherLabels(Name), Ports: []corev1.ServicePort{ { Name: "http", @@ -337,13 +305,13 @@ func makeK8sService() *corev1.Service { } } -func makeK8sServiceNotOwnedByClusterProvisioner() *corev1.Service { +func makeK8sServiceNotOwnedByClusterChannelProvisioner() *corev1.Service { svc := makeK8sService() svc.OwnerReferences = nil return svc } -func errorGettingClusterProvisioner() controllertesting.MockGet { +func errorGettingClusterChannelProvisioner() controllertesting.MockGet { return func(client.Client, context.Context, client.ObjectKey, runtime.Object) (controllertesting.MockHandled, error) { return controllertesting.Handled, errors.New(testErrorMessage) } @@ -358,16 +326,16 @@ func errorGettingK8sService() controllertesting.MockGet { } } -func oneSuccessfulClusterProvisionerGet() []controllertesting.MockGet { +func oneSuccessfulClusterChannelProvisionerGet() []controllertesting.MockGet { return []controllertesting.MockGet{ // The first one is a pass through. func(innerClient client.Client, ctx context.Context, key client.ObjectKey, obj runtime.Object) (controllertesting.MockHandled, error) { err := innerClient.Get(ctx, key, obj) return controllertesting.Handled, err }, - // All subsequent ClusterProvisioner Gets fail. + // All subsequent ClusterChannelProvisioner Gets fail. func(_ client.Client, _ context.Context, _ client.ObjectKey, obj runtime.Object) (controllertesting.MockHandled, error) { - if _, ok := obj.(*eventingv1alpha1.ClusterProvisioner); ok { + if _, ok := obj.(*eventingv1alpha1.ClusterChannelProvisioner); ok { return controllertesting.Handled, errors.New(testErrorMessage) } return controllertesting.Unhandled, nil diff --git a/pkg/controller/eventing/inmemory/clusterprovisioner/reconcile.go b/pkg/controller/eventing/inmemory/clusterprovisioner/reconcile.go deleted file mode 100644 index a11cb53ca2f..00000000000 --- a/pkg/controller/eventing/inmemory/clusterprovisioner/reconcile.go +++ /dev/null @@ -1,220 +0,0 @@ -/* -Copyright 2018 The Knative 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 clusterprovisioner - -import ( - "context" - - eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" - "github.com/knative/eventing/pkg/controller" - "github.com/knative/eventing/pkg/system" - "go.uber.org/zap" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/client-go/tools/record" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/reconcile" -) - -const ( - // Name is the name of the in-memory channel ClusterProvisioner. - Name = "in-memory-channel" - - // Channel is the name of the Channel resource in eventing.knative.dev/v1alpha1. - Channel = "Channel" -) - -type reconciler struct { - client client.Client - recorder record.EventRecorder - logger *zap.Logger -} - -// Verify the struct implements reconcile.Reconciler -var _ reconcile.Reconciler = &reconciler{} - -func (r *reconciler) InjectClient(c client.Client) error { - r.client = c - return nil -} - -func (r *reconciler) Reconcile(request reconcile.Request) (reconcile.Result, error) { - //TODO use this to store the logger and set a deadline - ctx := context.TODO() - logger := r.logger.With(zap.Any("request", request)) - - cp := &eventingv1alpha1.ClusterProvisioner{} - err := r.client.Get(ctx, request.NamespacedName, cp) - - // The ClusterProvisioner may have been deleted since it was added to the workqueue. If so, - // there is nothing to be done. - if errors.IsNotFound(err) { - logger.Info("Could not find ClusterProvisioner", zap.Error(err)) - return reconcile.Result{}, nil - } - - // Any other error should be retried in another reconciliation. - if err != nil { - logger.Error("Unable to Get ClusterProvisioner", zap.Error(err)) - return reconcile.Result{}, err - } - - // Does this Controller control this ClusterProvisioner? - if !shouldReconcile(cp.Namespace, cp.Name, cp.Spec.Reconciles.Kind) { - logger.Info("Not reconciling ClusterProvisioner, it is not controlled by this Controller", zap.String("APIVersion", cp.APIVersion), zap.String("Kind", cp.Kind), zap.String("Namespace", cp.Namespace), zap.String("name", cp.Name)) - return reconcile.Result{}, nil - } - logger.Info("Reconciling ClusterProvisioner.") - - // Modify a copy of this object, rather than the original. - cp = cp.DeepCopy() - - err = r.reconcile(ctx, cp) - if err != nil { - logger.Info("Error reconciling ClusterProvisioner", zap.Error(err)) - // Note that we do not return the error here, because we want to update the Status - // regardless of the error. - } - - if updateStatusErr := r.updateClusterProvisionerStatus(ctx, cp); updateStatusErr != nil { - logger.Info("Error updating ClusterProvisioner Status", zap.Error(updateStatusErr)) - return reconcile.Result{}, updateStatusErr - } - - return reconcile.Result{}, err -} - -// IsControlled determines if the in-memory Channel Controller should control (and therefore -// reconcile) a given object, based on that object's ClusterProvisioner reference. kind is the kind -// of that object. -func IsControlled(ref *eventingv1alpha1.ProvisionerReference, kind string) bool { - if ref != nil && ref.Ref != nil { - return shouldReconcile(ref.Ref.Namespace, ref.Ref.Name, kind) - } - return false -} - -// shouldReconcile determines if this Controller should control (and therefore reconcile) a given -// ClusterProvisioner. This Controller only handles in-memory channels. -func shouldReconcile(namespace, name, kind string) bool { - return namespace == "" && name == Name && kind == Channel -} - -func (r *reconciler) reconcile(ctx context.Context, cp *eventingv1alpha1.ClusterProvisioner) error { - logger := r.logger.With(zap.Any("clusterProvisioner", cp)) - - // We are syncing one thing. - // 1. The K8s Service to talk to all in-memory Channels. - // - There is a single K8s Service for all requests going any in-memory Channel. - - if cp.DeletionTimestamp != nil { - // K8s garbage collection will delete the dispatcher service, once this ClusterProvisioner - // is deleted, so we don't need to do anything. - return nil - } - - if err := r.createDispatcherService(ctx, cp); err != nil { - logger.Info("Error creating the ClusterProvisioner's K8s Service", zap.Error(err)) - return err - } - - cp.Status.MarkReady() - return nil -} - -func (r *reconciler) createDispatcherService(ctx context.Context, cp *eventingv1alpha1.ClusterProvisioner) error { - svcName := controller.ClusterBusDispatcherServiceName(cp.Name) - svcKey := types.NamespacedName{ - Namespace: system.Namespace, - Name: svcName, - } - svc := &corev1.Service{} - err := r.client.Get(ctx, svcKey, svc) - - if errors.IsNotFound(err) { - svc = newDispatcherService(cp) - err = r.client.Create(ctx, svc) - } - - // If an error occurred in either Get or Create, we need to reconcile again. - if err != nil { - return err - } - - // Check if this ClusterProvisioner is the owner of the K8s service. - if !metav1.IsControlledBy(svc, cp) { - r.logger.Warn("ClusterProvisioner's K8s Service is not owned by the ClusterProvisioner", zap.Any("clusterProvisioner", cp), zap.Any("service", svc)) - } - return nil -} - -func (r *reconciler) updateClusterProvisionerStatus(ctx context.Context, u *eventingv1alpha1.ClusterProvisioner) error { - o := &eventingv1alpha1.ClusterProvisioner{} - if err := r.client.Get(ctx, client.ObjectKey{Namespace: u.Namespace, Name: u.Name}, o); err != nil { - r.logger.Info("Error getting ClusterProvisioner for status update", zap.Error(err), zap.Any("updatedClusterProvisioner", u)) - return err - } - - if !equality.Semantic.DeepEqual(o.Status, u.Status) { - o.Status = u.Status - return r.client.Update(ctx, o) - } - return nil -} - -// newDispatcherService creates a new Service for a ClusterBus resource. It also sets -// the appropriate OwnerReferences on the resource so handleObject can discover -// the ClusterBus resource that 'owns' it. -func newDispatcherService(cp *eventingv1alpha1.ClusterProvisioner) *corev1.Service { - labels := dispatcherLabels(cp.Name) - return &corev1.Service{ - ObjectMeta: metav1.ObjectMeta{ - Name: controller.ClusterBusDispatcherServiceName(cp.Name), - Namespace: system.Namespace, - Labels: labels, - OwnerReferences: []metav1.OwnerReference{ - *metav1.NewControllerRef(cp, schema.GroupVersionKind{ - Group: eventingv1alpha1.SchemeGroupVersion.Group, - Version: eventingv1alpha1.SchemeGroupVersion.Version, - Kind: "ClusterProvisioner", - }), - }, - }, - Spec: corev1.ServiceSpec{ - Selector: labels, - Ports: []corev1.ServicePort{ - { - Name: "http", - Port: 80, - TargetPort: intstr.FromInt(8080), - }, - }, - }, - } -} - -func dispatcherLabels(cpName string) map[string]string { - return map[string]string{ - "clusterProvisioner": cpName, - "role": "dispatcher", - } -} diff --git a/pkg/controller/eventing/inmemory/controller/main.go b/pkg/controller/eventing/inmemory/controller/main.go index c5485a9e719..bb0a680a72b 100644 --- a/pkg/controller/eventing/inmemory/controller/main.go +++ b/pkg/controller/eventing/inmemory/controller/main.go @@ -22,7 +22,7 @@ import ( eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" "github.com/knative/eventing/pkg/buses" "github.com/knative/eventing/pkg/controller/eventing/inmemory/channel" - "github.com/knative/eventing/pkg/controller/eventing/inmemory/clusterprovisioner" + "github.com/knative/eventing/pkg/controller/eventing/inmemory/clusterchannelprovisioner" istiov1alpha3 "github.com/knative/pkg/apis/istio/v1alpha3" "github.com/knative/pkg/signals" "go.uber.org/zap" @@ -35,8 +35,8 @@ func main() { logger := buses.NewBusLoggerFromConfig(logConfig) defer logger.Sync() logger = logger.With( - zap.String("eventing.knative.dev/clusterProvisioner", clusterprovisioner.Name), - zap.String("eventing.knative.dev/clusterProvisionerComponent", "Controller"), + zap.String("eventing.knative.dev/clusterChannelProvisioner", clusterchannelprovisioner.Name), + zap.String("eventing.knative.dev/clusterChannelProvisionerComponent", "Controller"), ) flag.Parse() @@ -49,9 +49,9 @@ func main() { eventingv1alpha1.AddToScheme(mgr.GetScheme()) istiov1alpha3.AddToScheme(mgr.GetScheme()) - // The controllers for both the ClusterProvisioner and the Channels created by that - // ClusterProvisioner run in this process. - _, err = clusterprovisioner.ProvideController(mgr, logger.Desugar()) + // The controllers for both the ClusterChannelProvisioner and the Channels created by that + // ClusterChannelProvisioner run in this process. + _, err = clusterchannelprovisioner.ProvideController(mgr, logger.Desugar()) if err != nil { logger.Fatal("Unable to create Provisioner controller", zap.Error(err)) } diff --git a/pkg/controller/eventing/subscription/provider_test.go b/pkg/controller/eventing/subscription/provider_test.go new file mode 100644 index 00000000000..0d41b41615f --- /dev/null +++ b/pkg/controller/eventing/subscription/provider_test.go @@ -0,0 +1,92 @@ +/* +Copyright 2018 The Knative 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 subscription + +import ( + "testing" + + "github.com/google/go-cmp/cmp" + "k8s.io/client-go/dynamic" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client/fake" +) + +func TestProvideController(t *testing.T) { + //TODO(grantr) This needs a mock of manager.Manager. Creating a manager + // with a fake Config fails because the Manager tries to contact the + // apiserver. + + // cfg := &rest.Config{ + // Host: "http://foo:80", + // } + // + // mgr, err := manager.New(cfg, manager.Options{}) + // if err != nil { + // t.Fatalf("Error creating manager: %v", err) + // } + // + // _, err = ProvideController(mgr) + // if err != nil { + // t.Fatalf("Error in ProvideController: %v", err) + // } +} + +func TestInjectClient(t *testing.T) { + r := &reconciler{} + orig := r.client + n := fake.NewFakeClient() + if orig == n { + t.Errorf("Original and new clients are identical: %v", orig) + } + err := r.InjectClient(n) + if err != nil { + t.Errorf("Unexpected error injecting the client: %v", err) + } + if n != r.client { + t.Errorf("Unexpected client. Expected: '%v'. Actual: '%v'", n, r.client) + } +} + +func TestInjectConfig(t *testing.T) { + r := &reconciler{} + wantCfg := &rest.Config{ + Host: "http://foo", + } + + err := r.InjectConfig(wantCfg) + if err != nil { + t.Fatalf("Unexpected error injecting the config: %v", err) + } + + gotCfg := r.restConfig + if diff := cmp.Diff(wantCfg, gotCfg); diff != "" { + t.Errorf("Unexpected config (-want, +got): %v", diff) + } + + wantDynClient, err := dynamic.NewForConfig(wantCfg) + if err != nil { + t.Fatalf("Unexpected error generating dynamic client: %v", err) + } + + // Since dynamicClient doesn't export any fields, we can only test its type. + switch r.dynamicClient.(type) { + case dynamic.Interface: + // ok + default: + t.Errorf("Unexpected dynamicClient type. Expected: %T, Got: %T", wantDynClient, r.dynamicClient) + } +} diff --git a/pkg/controller/eventing/subscription/reconcile.go b/pkg/controller/eventing/subscription/reconcile.go index 36b307e0094..5821971d5fb 100644 --- a/pkg/controller/eventing/subscription/reconcile.go +++ b/pkg/controller/eventing/subscription/reconcile.go @@ -19,8 +19,10 @@ package subscription import ( "context" "fmt" + "net/url" "github.com/golang/glog" + eventingduck "github.com/knative/eventing/pkg/apis/duck/v1alpha1" "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" "github.com/knative/eventing/pkg/controller" duckapis "github.com/knative/pkg/apis" @@ -32,11 +34,16 @@ import ( "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/sets" "k8s.io/client-go/dynamic" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" ) +const ( + finalizerName = controllerAgentName +) + // Reconcile compares the actual state with the desired, and attempts to // converge the two. It then updates the Status block of the Subscription resource // with the current status of the resource. @@ -55,17 +62,10 @@ func (r *reconciler) Reconcile(request reconcile.Request) (reconcile.Result, err return reconcile.Result{}, err } - original := subscription.DeepCopy() - // Reconcile this copy of the Subscription and then write back any status // updates regardless of whether the reconcile error out. err = r.reconcile(subscription) - if equality.Semantic.DeepEqual(original.Status, subscription.Status) { - // If we didn't change anything then don't call updateStatus. - // This is important because the copy we loaded from the informer's - // cache may be stale and we don't want to overwrite a prior update - // to status with this stale state. - } else if _, updateStatusErr := r.updateStatus(subscription); updateStatusErr != nil { + if _, updateStatusErr := r.updateStatus(subscription.DeepCopy()); updateStatusErr != nil { glog.Warningf("Failed to update subscription status: %v", updateStatusErr) return reconcile.Result{}, updateStatusErr } @@ -86,64 +86,80 @@ func (r *reconciler) reconcile(subscription *v1alpha1.Subscription) error { deletionTimestamp := accessor.GetDeletionTimestamp() glog.Infof("DeletionTimestamp: %v", deletionTimestamp) - // Reconcile the subscription to the From channel that's consuming events that are either - // going to the call or if there's no call, directly to result. - from, err := r.resolveFromChannelable(subscription.Namespace, &subscription.Spec.From) + if subscription.DeletionTimestamp != nil { + // If the subscription is Ready, then we have to remove it + // from the channel's subscriber list. + if subscription.Status.IsReady() { + err := r.syncPhysicalChannel(subscription, true) + if err != nil { + glog.Warningf("Failed to sync physical from Channel : %s", err) + return err + } + } + removeFinalizer(subscription) + return nil + } + + // Verify that `channel` exists. + _, err = r.fetchObjectReference(subscription.Namespace, &subscription.Spec.Channel) if err != nil { - glog.Warningf("Failed to resolve From %+v : %s", subscription.Spec.From, err) + glog.Warningf("Failed to validate `channel` exists: %+v, %v", subscription.Spec.Channel, err) return err } - if from.Status.Subscribable == nil { - return fmt.Errorf("from is not subscribable %s %s/%s", subscription.Spec.From.Kind, subscription.Namespace, subscription.Spec.From.Name) - } - subscription.Status.PhysicalSubscription.From = from.Status.Subscribable.Channelable - glog.Infof("Resolved from subscribable to: %+v", from.Status.Subscribable.Channelable) - - callDomain := "" - if subscription.Spec.Call != nil { - callDomain, err = r.resolveEndpointSpec(subscription.Namespace, *subscription.Spec.Call) + subscriberURI := "" + if !isNilOrEmptySubscriber(subscription.Spec.Subscriber) { + subscriberURI, err = r.resolveSubscriberSpec(subscription.Namespace, *subscription.Spec.Subscriber) if err != nil { - glog.Warningf("Failed to resolve Call %+v : %s", *subscription.Spec.Call, err) + glog.Warningf("Failed to resolve Subscriber %+v : %s", *subscription.Spec.Subscriber, err) return err } - if callDomain == "" { - return fmt.Errorf("could not get domain from call (is it not targetable?)") + if subscriberURI == "" { + return fmt.Errorf("could not get domain from subscriber (is it not targetable?)") } - subscription.Status.PhysicalSubscription.CallDomain = callDomain - glog.Infof("Resolved call to: %q", callDomain) + subscription.Status.PhysicalSubscription.SubscriberURI = subscriberURI + glog.Infof("Resolved subscriber to: %q", subscriberURI) } - resultDomain := "" - if subscription.Spec.Result != nil { - resultDomain, err = r.resolveResult(subscription.Namespace, *subscription.Spec.Result) + replyURI := "" + if !isNilOrEmptyReply(subscription.Spec.Reply) { + replyURI, err = r.resolveResult(subscription.Namespace, *subscription.Spec.Reply) if err != nil { - glog.Warningf("Failed to resolve Result %v : %v", subscription.Spec.Result, err) + glog.Warningf("Failed to resolve Result %v : %v", subscription.Spec.Reply, err) return err } - if resultDomain == "" { - glog.Warningf("Failed to resolve result %v to actual domain", *subscription.Spec.Result) + if replyURI == "" { + glog.Warningf("Failed to resolve reply %v to actual domain", *subscription.Spec.Reply) return err } - subscription.Status.PhysicalSubscription.ResultDomain = resultDomain - glog.Infof("Resolved result to: %q", resultDomain) + subscription.Status.PhysicalSubscription.ReplyURI = replyURI + glog.Infof("Resolved reply to: %q", replyURI) } // Everything that was supposed to be resolved was, so flip the status bit on that. subscription.Status.MarkReferencesResolved() - // Ok, now that we have the From and at least one of the Call/Result, let's reconcile - // the From with this information. - err = r.syncPhysicalFromChannel(subscription) + // Ok, now that we have the Channel and at least one of the Call/Result, let's reconcile + // the Channel with this information. + err = r.syncPhysicalChannel(subscription, false) if err != nil { - glog.Warningf("Failed to sync physical from Channel : %s", err) + glog.Warningf("Failed to sync physical Channel : %s", err) return err } // Everything went well, set the fact that subscriptions have been modified - subscription.Status.MarkFromReady() + subscription.Status.MarkChannelReady() + addFinalizer(subscription) return nil } +func isNilOrEmptySubscriber(sub *v1alpha1.SubscriberSpec) bool { + return sub == nil || equality.Semantic.DeepEqual(sub, &v1alpha1.SubscriberSpec{}) +} + +func isNilOrEmptyReply(reply *v1alpha1.ReplyStrategy) bool { + return reply == nil || equality.Semantic.DeepEqual(reply, &v1alpha1.ReplyStrategy{}) +} + func (r *reconciler) updateStatus(subscription *v1alpha1.Subscription) (*v1alpha1.Subscription, error) { newSubscription := &v1alpha1.Subscription{} err := r.client.Get(context.TODO(), client.ObjectKey{Namespace: subscription.Namespace, Name: subscription.Name}, newSubscription) @@ -151,94 +167,92 @@ func (r *reconciler) updateStatus(subscription *v1alpha1.Subscription) (*v1alpha if err != nil { return nil, err } - newSubscription.Status = subscription.Status - // Until #38113 is merged, we must use Update instead of UpdateStatus to - // update the Status block of the Subscription resource. UpdateStatus will not - // allow changes to the Spec of the resource, which is ideal for ensuring - // nothing other than resource status has been updated. - if err = r.client.Update(context.TODO(), newSubscription); err != nil { - return nil, err + updated := false + if !equality.Semantic.DeepEqual(newSubscription.Finalizers, subscription.Finalizers) { + newSubscription.SetFinalizers(subscription.ObjectMeta.Finalizers) + updated = true + } + + if !equality.Semantic.DeepEqual(newSubscription.Status, subscription.Status) { + newSubscription.Status = subscription.Status + updated = true + } + + if updated { + // Until #38113 is merged, we must use Update instead of UpdateStatus to + // update the Status block of the Subscription resource. UpdateStatus will not + // allow changes to the Spec of the resource, which is ideal for ensuring + // nothing other than resource status has been updated. + if err = r.client.Update(context.TODO(), newSubscription); err != nil { + return nil, err + } } + return newSubscription, nil } -// resolveEndpointSpec resolves the Spec.Call object. If it's an -// ObjectReference will resolve the object and treat it as a Targetable. If +// resolveSubscriberSpec resolves the Spec.Call object. If it's an +// ObjectReference will resolve the object and treat it as a Callable. If // it's DNSName then it's used as is. -// TODO: Once Service Routes, etc. support Targetable, use that. +// TODO: Once Service Routes, etc. support Callable, use that. // -func (r *reconciler) resolveEndpointSpec(namespace string, es v1alpha1.EndpointSpec) (string, error) { - if es.DNSName != nil && *es.DNSName != "" { - return *es.DNSName, nil +func (r *reconciler) resolveSubscriberSpec(namespace string, s v1alpha1.SubscriberSpec) (string, error) { + if s.DNSName != nil && *s.DNSName != "" { + return *s.DNSName, nil } // K8s services are special cased. They can be called, even though they do not satisfy the - // Targetable interface. - if es.TargetRef != nil && es.TargetRef.APIVersion == "v1" && es.TargetRef.Kind == "Service" { + // Callable interface. + if s.Ref != nil && s.Ref.APIVersion == "v1" && s.Ref.Kind == "Service" { svc := &corev1.Service{} svcKey := types.NamespacedName{ Namespace: namespace, - Name: es.TargetRef.Name, + Name: s.Ref.Name, } err := r.client.Get(context.TODO(), svcKey, svc) if err != nil { - glog.Warningf("Failed to fetch EndpointSpec target as a K8s Service %+v: %s", es.TargetRef, err) + glog.Warningf("Failed to fetch SubscriberSpec target as a K8s Service %+v: %s", s.Ref, err) return "", err } - return controller.ServiceHostName(svc.Name, svc.Namespace), nil + return domainToURL(controller.ServiceHostName(svc.Name, svc.Namespace)), nil } - obj, err := r.fetchObjectReference(namespace, es.TargetRef) + obj, err := r.fetchObjectReference(namespace, s.Ref) if err != nil { - glog.Warningf("Failed to fetch EndpointSpec target %+v: %s", es.TargetRef, err) + glog.Warningf("Failed to fetch SubscriberSpec target %+v: %s", s.Ref, err) return "", err } - t := duckv1alpha1.Target{} + t := duckv1alpha1.AddressableType{} err = duck.FromUnstructured(obj, &t) if err != nil { glog.Warningf("Failed to deserialize legacy target: %s", err) return "", err } - if t.Status.Targetable != nil { - return t.Status.Targetable.DomainInternal, nil + if t.Status.Address != nil { + return domainToURL(t.Status.Address.Hostname), nil } - return "", fmt.Errorf("status does not contain targetable") + return "", fmt.Errorf("status does not contain address") } // resolveResult resolves the Spec.Result object. -func (r *reconciler) resolveResult(namespace string, resultStrategy v1alpha1.ResultStrategy) (string, error) { - obj, err := r.fetchObjectReference(namespace, resultStrategy.Target) +func (r *reconciler) resolveResult(namespace string, replyStrategy v1alpha1.ReplyStrategy) (string, error) { + obj, err := r.fetchObjectReference(namespace, replyStrategy.Channel) if err != nil { - glog.Warningf("Failed to fetch ResultStrategy target %+v: %s", resultStrategy, err) + glog.Warningf("Failed to fetch ReplyStrategy channel %+v: %s", replyStrategy, err) return "", err } - s := duckv1alpha1.Sink{} + s := duckv1alpha1.AddressableType{} err = duck.FromUnstructured(obj, &s) if err != nil { - glog.Warningf("Failed to deserialize Sinkable target: %s", err) + glog.Warningf("Failed to deserialize Addressable target: %s", err) return "", err } - if s.Status.Sinkable != nil { - return s.Status.Sinkable.DomainInternal, nil - } - return "", fmt.Errorf("status does not contain sinkable") -} - -// resolveFromChannelable fetches an object based on ObjectReference. It assumes that the -// fetched object then implements Subscribable interface and returns the ObjectReference -// representing the Channelable interface. -func (r *reconciler) resolveFromChannelable(namespace string, ref *corev1.ObjectReference) (*duckv1alpha1.Subscription, error) { - obj, err := r.fetchObjectReference(namespace, ref) - if err != nil { - glog.Warningf("Failed to fetch From target %+v: %s", ref, err) - return nil, err + if s.Status.Address != nil { + return domainToURL(s.Status.Address.Hostname), nil } - - c := duckv1alpha1.Subscription{} - err = duck.FromUnstructured(obj, &c) - return &c, err + return "", fmt.Errorf("status does not contain address") } // fetchObjectReference fetches an object based on ObjectReference. @@ -252,28 +266,45 @@ func (r *reconciler) fetchObjectReference(namespace string, ref *corev1.ObjectRe return resourceClient.Get(ref.Name, metav1.GetOptions{}) } -func (r *reconciler) syncPhysicalFromChannel(sub *v1alpha1.Subscription) error { +func domainToURL(domain string) string { + u := url.URL{ + Scheme: "http", + Host: domain, + Path: "/", + } + return u.String() +} + +func (r *reconciler) syncPhysicalChannel(sub *v1alpha1.Subscription, isDeleted bool) error { glog.Infof("Reconciling Physical From Channel: %+v", sub) - subs, err := r.listAllSubscriptionsWithPhysicalFrom(sub) + subs, err := r.listAllSubscriptionsWithPhysicalChannel(sub) if err != nil { - glog.Infof("Unable to list all channels with physical from: %+v", err) + glog.Infof("Unable to list all subscriptions with physical channel: %+v", err) return err } - channelable := r.createChannelable(subs) + if !isDeleted { + // The sub we are currently reconciling has not yet written any updated status, so when listing + // it won't show any updates to the Status.PhysicalSubscription. We know that we are listing + // for subscriptions with the same PhysicalSubscription.From, so just add this one manually. + subs = append(subs, *sub) + } + subscribable := r.createSubscribable(subs) - return r.patchPhysicalFrom(sub.Namespace, sub.Status.PhysicalSubscription.From, channelable) + if patchErr := r.patchPhysicalFrom(sub.Namespace, sub.Spec.Channel, subscribable); patchErr != nil { + if isDeleted && errors.IsNotFound(patchErr) { + glog.Infof("could not find channel %v\n", sub.Spec.Channel) + return nil + } + return patchErr + } + return nil } -func (r *reconciler) listAllSubscriptionsWithPhysicalFrom(sub *v1alpha1.Subscription) ([]v1alpha1.Subscription, error) { +func (r *reconciler) listAllSubscriptionsWithPhysicalChannel(sub *v1alpha1.Subscription) ([]v1alpha1.Subscription, error) { subs := make([]v1alpha1.Subscription, 0) - // The sub we are currently reconciling has not yet written any updated status, so when listing - // it won't show any updates to the Status.PhysicalSubscription. We know that we are listing - // for subscriptions with the same PhysicalSubscription.From, so just add this one manually. - subs = append(subs, *sub) - opts := &client.ListOptions{ // TODO this is here because the fake client needs it. Remove this when it's no longer // needed. @@ -283,6 +314,7 @@ func (r *reconciler) listAllSubscriptionsWithPhysicalFrom(sub *v1alpha1.Subscrip Kind: "Subscription", }, }, + Namespace: sub.Namespace, } ctx := context.TODO() for { @@ -293,10 +325,10 @@ func (r *reconciler) listAllSubscriptionsWithPhysicalFrom(sub *v1alpha1.Subscrip } for _, s := range sl.Items { if sub.UID == s.UID { - // This is the sub that is being reconciled. It has already been added to the list. + // This is the sub that is being reconciled. Skip it. continue } - if equality.Semantic.DeepEqual(sub.Status.PhysicalSubscription.From, s.Status.PhysicalSubscription.From) { + if equality.Semantic.DeepEqual(sub.Spec.Channel, s.Spec.Channel) { subs = append(subs, s) } } @@ -308,33 +340,40 @@ func (r *reconciler) listAllSubscriptionsWithPhysicalFrom(sub *v1alpha1.Subscrip } } -func (r *reconciler) createChannelable(subs []v1alpha1.Subscription) *duckv1alpha1.Channelable { - rv := &duckv1alpha1.Channelable{} +func (r *reconciler) createSubscribable(subs []v1alpha1.Subscription) *eventingduck.Subscribable { + rv := &eventingduck.Subscribable{} for _, sub := range subs { - if sub.Status.PhysicalSubscription.CallDomain != "" || sub.Status.PhysicalSubscription.ResultDomain != "" { - rv.Subscribers = append(rv.Subscribers, duckv1alpha1.ChannelSubscriberSpec{ - CallableDomain: sub.Status.PhysicalSubscription.CallDomain, - SinkableDomain: sub.Status.PhysicalSubscription.ResultDomain, + if sub.Status.PhysicalSubscription.SubscriberURI != "" || sub.Status.PhysicalSubscription.ReplyURI != "" { + rv.Subscribers = append(rv.Subscribers, eventingduck.ChannelSubscriberSpec{ + Ref: &corev1.ObjectReference{ + APIVersion: sub.APIVersion, + Kind: sub.Kind, + Namespace: sub.Namespace, + Name: sub.Name, + UID: sub.UID, + }, + SubscriberURI: sub.Status.PhysicalSubscription.SubscriberURI, + ReplyURI: sub.Status.PhysicalSubscription.ReplyURI, }) } } return rv } -func (r *reconciler) patchPhysicalFrom(namespace string, physicalFrom corev1.ObjectReference, subs *duckv1alpha1.Channelable) error { +func (r *reconciler) patchPhysicalFrom(namespace string, physicalFrom corev1.ObjectReference, subs *eventingduck.Subscribable) error { // First get the original object and convert it to only the bits we care about s, err := r.fetchObjectReference(namespace, &physicalFrom) if err != nil { return err } - original := duckv1alpha1.Channel{} + original := eventingduck.Channel{} err = duck.FromUnstructured(s, &original) if err != nil { return err } after := original.DeepCopy() - after.Spec.Channelable = subs + after.Spec.Subscribable = subs patch, err := duck.CreatePatch(original, after) if err != nil { @@ -371,3 +410,15 @@ func (r *reconciler) CreateResourceInterface(namespace string, ref *corev1.Objec return rc.Namespace(namespace), nil } + +func addFinalizer(sub *v1alpha1.Subscription) { + finalizers := sets.NewString(sub.Finalizers...) + finalizers.Insert(finalizerName) + sub.Finalizers = finalizers.List() +} + +func removeFinalizer(sub *v1alpha1.Subscription) { + finalizers := sets.NewString(sub.Finalizers...) + finalizers.Delete(finalizerName) + sub.Finalizers = finalizers.List() +} diff --git a/pkg/controller/eventing/subscription/reconcile_test.go b/pkg/controller/eventing/subscription/reconcile_test.go index 38042eab6d2..79f56de8f99 100644 --- a/pkg/controller/eventing/subscription/reconcile_test.go +++ b/pkg/controller/eventing/subscription/reconcile_test.go @@ -20,6 +20,7 @@ import ( "fmt" "testing" + eventingduck "github.com/knative/eventing/pkg/apis/duck/v1alpha1" eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" controllertesting "github.com/knative/eventing/pkg/controller/testing" duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" @@ -27,6 +28,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/sets" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" "k8s.io/client-go/tools/record" @@ -35,24 +37,29 @@ import ( var ( trueVal = true + + // deletionTime is used when objects are marked as deleted. Rfc3339Copy() + // truncates to seconds to match the loss of precision during serialization. + deletionTime = metav1.Now().Rfc3339Copy() ) const ( - fromChannelName = "fromchannel" - resultChannelName = "resultchannel" - sourceName = "source" - routeName = "callroute" - channelKind = "Channel" - routeKind = "Route" - sourceKind = "Source" - targetDNS = "myfunction.mynamespace.svc.cluster.local" - sinkableDNS = "myresultchannel.mynamespace.svc.cluster.local" - eventType = "myeventtype" - subscriptionName = "testsubscription" - testNS = "testnamespace" - k8sServiceName = "testk8sservice" - k8sServiceDNS = "testk8sservice.testnamespace.svc.cluster.local" - otherSinkableDNS = "other-sinkable-channel.mynamespace.svc.cluster.local" + fromChannelName = "fromchannel" + resultChannelName = "resultchannel" + sourceName = "source" + routeName = "subscriberroute" + channelKind = "Channel" + routeKind = "Route" + sourceKind = "Source" + subscriptionKind = "Subscription" + targetDNS = "myfunction.mynamespace.svc.cluster.local" + sinkableDNS = "myresultchannel.mynamespace.svc.cluster.local" + eventType = "myeventtype" + subscriptionName = "testsubscription" + testNS = "testnamespace" + k8sServiceName = "testk8sservice" + k8sServiceDNS = "testk8sservice.testnamespace.svc.cluster.local" + otherAddressableDNS = "other-sinkable-channel.mynamespace.svc.cluster.local" ) func init() { @@ -74,42 +81,71 @@ var testCases = []controllertesting.TestCase{ }, { Name: "subscription, but From is not subscribable", InitialState: []runtime.Object{ - getNewSubscription(), + getNewSourceSubscription(), }, - WantErrMsg: "from is not subscribable Channel testnamespace/fromchannel", + // TODO: JSON patch is not working on the fake, see + // https://github.com/kubernetes/client-go/issues/478. Marking this as expecting a specific + // failure for now, until upstream is fixed. It should actually fail saying that there is no + // Spec.Subscribers field. + WantErrMsg: "invalid JSON document", Scheme: scheme.Scheme, Objects: []runtime.Object{ // Source channel + &unstructured.Unstructured{ + Object: map[string]interface{}{ + "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), + "kind": sourceKind, + "metadata": map[string]interface{}{ + "namespace": testNS, + "name": sourceName, + }, + "spec": map[string]interface{}{}, + }, + }, + // Subscriber (using knative route) + &unstructured.Unstructured{ + Object: map[string]interface{}{ + "apiVersion": "serving.knative.dev/v1alpha1", + "kind": routeKind, + "metadata": map[string]interface{}{ + "namespace": testNS, + "name": routeName, + }, + "status": map[string]interface{}{ + "address": map[string]interface{}{ + "hostname": targetDNS, + }, + }, + }, + }, + // Reply channel &unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), "kind": channelKind, "metadata": map[string]interface{}{ "namespace": testNS, - "name": fromChannelName, + "name": resultChannelName, }, "spec": map[string]interface{}{ - "channelable": map[string]interface{}{}, + "subscribable": map[string]interface{}{}, }, "status": map[string]interface{}{ - "notsubscribable": map[string]interface{}{ - "channelable": map[string]interface{}{ - "kind": channelKind, - "name": fromChannelName, - "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), - }, + "address": map[string]interface{}{ + "hostname": sinkableDNS, }, }, - }}, + }, + }, }, }, { - Name: "Valid from, call does not exist", + Name: "Valid channel, subscriber does not exist", InitialState: []runtime.Object{ getNewSubscription(), }, - WantErrMsg: `routes.serving.knative.dev "callroute" not found`, + WantErrMsg: `routes.serving.knative.dev "subscriberroute" not found`, WantPresent: []runtime.Object{ - getNewSubscriptionWithUnknownConditionsAndPhysicalFrom(), + getNewSubscriptionWithUnknownConditions(), }, Scheme: scheme.Scheme, Objects: []runtime.Object{ @@ -123,28 +159,20 @@ var testCases = []controllertesting.TestCase{ "name": fromChannelName, }, "spec": map[string]interface{}{ - "channelable": map[string]interface{}{}, - }, - "status": map[string]interface{}{ - "subscribable": map[string]interface{}{ - "channelable": map[string]interface{}{ - "kind": channelKind, - "name": fromChannelName, - "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), - }, - }, + "subscribable": map[string]interface{}{}, }, - }}, + }, + }, }, }, { - Name: "Valid from, call is not targetable", + Name: "Valid channel, subscriber is not callable", InitialState: []runtime.Object{ getNewSubscription(), }, WantPresent: []runtime.Object{ - getNewSubscriptionWithUnknownConditionsAndPhysicalFrom(), + getNewSubscriptionWithUnknownConditions(), }, - WantErrMsg: "status does not contain targetable", + WantErrMsg: "status does not contain address", Scheme: scheme.Scheme, Objects: []runtime.Object{ // Source channel @@ -157,19 +185,11 @@ var testCases = []controllertesting.TestCase{ "name": fromChannelName, }, "spec": map[string]interface{}{ - "channelable": map[string]interface{}{}, - }, - "status": map[string]interface{}{ - "subscribable": map[string]interface{}{ - "channelable": map[string]interface{}{ - "kind": channelKind, - "name": fromChannelName, - "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), - }, - }, + "subscribable": map[string]interface{}{}, }, - }}, - // Call (using knative route) + }, + }, + // Subscriber (using knative route) &unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": "serving.knative.dev/v1alpha1", @@ -181,15 +201,16 @@ var testCases = []controllertesting.TestCase{ "status": map[string]interface{}{ "someotherstuff": targetDNS, }, - }}, + }, + }, }, }, { - Name: "Valid from and call, result does not exist", + Name: "Valid channel and subscriber, result does not exist", InitialState: []runtime.Object{ getNewSubscription(), }, WantPresent: []runtime.Object{ - getNewSubscriptionWithUnknownConditionsAndPhysicalFromCall(), + getNewSubscriptionWithUnknownConditionsAndPhysicalSubscriber(), }, WantErrMsg: `channels.eventing.knative.dev "resultchannel" not found`, Scheme: scheme.Scheme, @@ -204,19 +225,11 @@ var testCases = []controllertesting.TestCase{ "name": fromChannelName, }, "spec": map[string]interface{}{ - "channelable": map[string]interface{}{}, - }, - "status": map[string]interface{}{ - "subscribable": map[string]interface{}{ - "channelable": map[string]interface{}{ - "kind": channelKind, - "name": fromChannelName, - "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), - }, - }, + "subscribable": map[string]interface{}{}, }, - }}, - // Call (using knative route) + }, + }, + // Subscriber (using knative route) &unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": "serving.knative.dev/v1alpha1", @@ -226,23 +239,24 @@ var testCases = []controllertesting.TestCase{ "name": routeName, }, "status": map[string]interface{}{ - "targetable": map[string]interface{}{ - "domainInternal": targetDNS, + "address": map[string]interface{}{ + "hostname": targetDNS, }, }, - }}, + }, + }, }, }, { - Name: "valid from, call, result is not sinkable", + Name: "valid channel, subscriber, result is not addressable", InitialState: []runtime.Object{ getNewSubscription(), }, - WantErrMsg: "status does not contain sinkable", + WantErrMsg: "status does not contain address", WantPresent: []runtime.Object{ // TODO: Again this works on gke cluster, but I need to set // something else up here. later... // getNewSubscriptionWithReferencesResolvedStatus(), - getNewSubscriptionWithUnknownConditionsAndPhysicalFromCall(), + getNewSubscriptionWithUnknownConditionsAndPhysicalSubscriber(), }, Scheme: scheme.Scheme, Objects: []runtime.Object{ @@ -256,19 +270,71 @@ var testCases = []controllertesting.TestCase{ "name": fromChannelName, }, "spec": map[string]interface{}{ - "channelable": map[string]interface{}{}, + "subscribable": map[string]interface{}{}, + }, + }, + }, + // Subscriber (using knative route) + &unstructured.Unstructured{ + Object: map[string]interface{}{ + "apiVersion": "serving.knative.dev/v1alpha1", + "kind": routeKind, + "metadata": map[string]interface{}{ + "namespace": testNS, + "name": routeName, }, "status": map[string]interface{}{ - "subscribable": map[string]interface{}{ - "channelable": map[string]interface{}{ - "kind": channelKind, - "name": fromChannelName, - "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), - }, + "address": map[string]interface{}{ + "hostname": targetDNS, }, }, - }}, - // Call (using knative route) + }, + }, + // Reply channel + &unstructured.Unstructured{ + Object: map[string]interface{}{ + "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), + "kind": channelKind, + "metadata": map[string]interface{}{ + "namespace": testNS, + "name": resultChannelName, + }, + "spec": map[string]interface{}{ + "subscribable": map[string]interface{}{}, + }, + }, + }, + }, + }, { + Name: "new subscription: adds status, all targets resolved, subscribers modified", + InitialState: []runtime.Object{ + getNewSubscription(), + }, + // TODO: JSON patch is not working on the fake, see + // https://github.com/kubernetes/client-go/issues/478. Marking this as expecting a specific + // failure for now, until upstream is fixed. + WantResult: reconcile.Result{}, + WantPresent: []runtime.Object{ + getNewSubscriptionWithReferencesResolvedAndPhysicalSubscriberReply(), + }, + WantErrMsg: "invalid JSON document", + Scheme: scheme.Scheme, + Objects: []runtime.Object{ + // Source channel + &unstructured.Unstructured{ + Object: map[string]interface{}{ + "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), + "kind": channelKind, + "metadata": map[string]interface{}{ + "namespace": testNS, + "name": fromChannelName, + }, + "spec": map[string]interface{}{ + "subscribable": map[string]interface{}{}, + }, + }, + }, + // Subscriber (using knative route) &unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": "serving.knative.dev/v1alpha1", @@ -278,12 +344,13 @@ var testCases = []controllertesting.TestCase{ "name": routeName, }, "status": map[string]interface{}{ - "targetable": map[string]interface{}{ - "domainInternal": targetDNS, + "address": map[string]interface{}{ + "hostname": targetDNS, }, }, - }}, - // Result channel + }, + }, + // Reply channel &unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), @@ -293,30 +360,27 @@ var testCases = []controllertesting.TestCase{ "name": resultChannelName, }, "spec": map[string]interface{}{ - "channelable": map[string]interface{}{}, + "subscribable": map[string]interface{}{}, }, "status": map[string]interface{}{ - "subscribable": map[string]interface{}{ - "channelable": map[string]interface{}{ - "kind": channelKind, - "name": fromChannelName, - "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), - }, + "address": map[string]interface{}{ + "hostname": sinkableDNS, }, }, - }}, + }, + }, }, }, { - Name: "new subscription: adds status, all targets resolved, subscribers modified", + Name: "new subscription: adds status, all targets resolved, subscribers modified -- empty but non-nil reply", InitialState: []runtime.Object{ - getNewSubscription(), + getNewSubscriptionWithEmptyNonNilReply(), }, // TODO: JSON patch is not working on the fake, see // https://github.com/kubernetes/client-go/issues/478. Marking this as expecting a specific // failure for now, until upstream is fixed. WantResult: reconcile.Result{}, WantPresent: []runtime.Object{ - getNewSubscriptionWithReferencesResolvedAndPhysicalFromCallResult(), + getNewSubscriptionWithReferencesResolvedAndPhysicalSubscriberAndNoReply(), }, WantErrMsg: "invalid JSON document", Scheme: scheme.Scheme, @@ -331,19 +395,11 @@ var testCases = []controllertesting.TestCase{ "name": fromChannelName, }, "spec": map[string]interface{}{ - "channelable": map[string]interface{}{}, + "subscribable": map[string]interface{}{}, }, - "status": map[string]interface{}{ - "subscribable": map[string]interface{}{ - "channelable": map[string]interface{}{ - "kind": channelKind, - "name": fromChannelName, - "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), - }, - }, - }, - }}, - // Call (using knative route) + }, + }, + // Subscriber (using knative route) &unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": "serving.knative.dev/v1alpha1", @@ -353,12 +409,43 @@ var testCases = []controllertesting.TestCase{ "name": routeName, }, "status": map[string]interface{}{ - "targetable": map[string]interface{}{ - "domainInternal": targetDNS, + "address": map[string]interface{}{ + "hostname": targetDNS, }, }, - }}, - // Result channel + }, + }, + }, + }, { + Name: "new subscription: adds status, all targets resolved, subscribers modified -- empty but non-nil subscriber", + InitialState: []runtime.Object{ + getNewSubscriptionWithEmptyNonNilSubscriber(), + }, + // TODO: JSON patch is not working on the fake, see + // https://github.com/kubernetes/client-go/issues/478. Marking this as expecting a specific + // failure for now, until upstream is fixed. + WantResult: reconcile.Result{}, + WantPresent: []runtime.Object{ + getNewSubscriptionWithReferencesResolvedAndPhysicalReplyAndNoSubscriber(), + }, + WantErrMsg: "invalid JSON document", + Scheme: scheme.Scheme, + Objects: []runtime.Object{ + // Source channel + &unstructured.Unstructured{ + Object: map[string]interface{}{ + "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), + "kind": channelKind, + "metadata": map[string]interface{}{ + "namespace": testNS, + "name": fromChannelName, + }, + "spec": map[string]interface{}{ + "subscribable": map[string]interface{}{}, + }, + }, + }, + // Reply channel &unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), @@ -368,21 +455,42 @@ var testCases = []controllertesting.TestCase{ "name": resultChannelName, }, "spec": map[string]interface{}{ - "channelable": map[string]interface{}{}, + "subscribable": map[string]interface{}{}, }, "status": map[string]interface{}{ - "subscribable": map[string]interface{}{ - "channelable": map[string]interface{}{ - "kind": channelKind, - "name": fromChannelName, - "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), - }, - }, - "sinkable": map[string]interface{}{ - "domainInternal": sinkableDNS, + "address": map[string]interface{}{ + "hostname": sinkableDNS, }, }, - }}, + }, + }, + }, + }, { + Name: "new subscription to non-existent K8s Service: fails with no service found", + InitialState: []runtime.Object{ + getNewSubscriptionToK8sService(), + }, + WantResult: reconcile.Result{}, + WantPresent: []runtime.Object{ + getNewSubscriptionToK8sServiceWithUnknownConditions(), + }, + WantErrMsg: "services \"testk8sservice\" not found", + Scheme: scheme.Scheme, + Objects: []runtime.Object{ + // Source channel + &unstructured.Unstructured{ + Object: map[string]interface{}{ + "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), + "kind": channelKind, + "metadata": map[string]interface{}{ + "namespace": testNS, + "name": fromChannelName, + }, + "spec": map[string]interface{}{ + "subscribable": map[string]interface{}{}, + }, + }, + }, }, }, { Name: "new subscription to K8s Service: adds status, all targets resolved, subscribers modified", @@ -395,7 +503,7 @@ var testCases = []controllertesting.TestCase{ // failure for now, until upstream is fixed. WantResult: reconcile.Result{}, WantPresent: []runtime.Object{ - getNewSubscriptionToK8sServiceWithReferencesResolvedAndPhysicalFromCallResult(), + getNewSubscriptionToK8sServiceWithReferencesResolvedAndPhysicalFromSubscriberReply(), }, WantErrMsg: "invalid JSON document", Scheme: scheme.Scheme, @@ -410,19 +518,11 @@ var testCases = []controllertesting.TestCase{ "name": fromChannelName, }, "spec": map[string]interface{}{ - "channelable": map[string]interface{}{}, - }, - "status": map[string]interface{}{ - "subscribable": map[string]interface{}{ - "channelable": map[string]interface{}{ - "kind": channelKind, - "name": fromChannelName, - "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), - }, - }, + "subscribable": map[string]interface{}{}, }, - }}, - // Call (using K8s Service) + }, + }, + // Subscriber (using K8s Service) &unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": "v1", @@ -431,8 +531,9 @@ var testCases = []controllertesting.TestCase{ "namespace": testNS, "name": k8sServiceName, }, - }}, - // Result channel + }, + }, + // Reply channel &unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), @@ -442,21 +543,15 @@ var testCases = []controllertesting.TestCase{ "name": resultChannelName, }, "spec": map[string]interface{}{ - "channelable": map[string]interface{}{}, + "subscribable": map[string]interface{}{}, }, "status": map[string]interface{}{ - "subscribable": map[string]interface{}{ - "channelable": map[string]interface{}{ - "kind": channelKind, - "name": fromChannelName, - "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), - }, - }, - "sinkable": map[string]interface{}{ - "domainInternal": sinkableDNS, + "address": map[string]interface{}{ + "hostname": sinkableDNS, }, }, - }}, + }, + }, }, }, { Name: "new subscription with from channel: adds status, all targets resolved, subscribers modified", @@ -469,7 +564,7 @@ var testCases = []controllertesting.TestCase{ WantResult: reconcile.Result{}, WantErrMsg: "invalid JSON document", WantPresent: []runtime.Object{ - getNewSubscriptionWithSourceWithReferencesResolvedAndPhysicalFromCallResult(), + getNewSubscriptionWithSourceWithReferencesResolvedAndPhysicalFromSubscriberReply(), }, Scheme: scheme.Scheme, Objects: []runtime.Object{ @@ -483,18 +578,10 @@ var testCases = []controllertesting.TestCase{ "name": sourceName, }, "spec": map[string]interface{}{ - "channelable": map[string]interface{}{}, - }, - "status": map[string]interface{}{ - "subscribable": map[string]interface{}{ - "channelable": map[string]interface{}{ - "kind": channelKind, - "name": fromChannelName, - "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), - }, - }, + "subscribable": map[string]interface{}{}, }, - }}, + }, + }, // Source channel &unstructured.Unstructured{ Object: map[string]interface{}{ @@ -505,19 +592,11 @@ var testCases = []controllertesting.TestCase{ "name": fromChannelName, }, "spec": map[string]interface{}{ - "channelable": map[string]interface{}{}, + "subscribable": map[string]interface{}{}, }, - "status": map[string]interface{}{ - "subscribable": map[string]interface{}{ - "channelable": map[string]interface{}{ - "kind": channelKind, - "name": fromChannelName, - "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), - }, - }, - }, - }}, - // Call (using knative route) + }, + }, + // Subscriber (using knative route) &unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": "serving.knative.dev/v1alpha1", @@ -527,12 +606,13 @@ var testCases = []controllertesting.TestCase{ "name": routeName, }, "status": map[string]interface{}{ - "targetable": map[string]interface{}{ - "domainInternal": targetDNS, + "address": map[string]interface{}{ + "hostname": targetDNS, }, }, - }}, - // Result channel + }, + }, + // Reply channel &unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), @@ -542,18 +622,11 @@ var testCases = []controllertesting.TestCase{ "name": resultChannelName, }, "spec": map[string]interface{}{ - "channelable": map[string]interface{}{}, + "subscribable": map[string]interface{}{}, }, "status": map[string]interface{}{ - "subscribable": map[string]interface{}{ - "channelable": map[string]interface{}{ - "kind": channelKind, - "name": fromChannelName, - "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), - }, - }, - "sinkable": map[string]interface{}{ - "domainInternal": sinkableDNS, + "address": map[string]interface{}{ + "hostname": sinkableDNS, }, }, }, @@ -566,7 +639,7 @@ var testCases = []controllertesting.TestCase{ // The first two Subscriptions both have the same physical From, so we should see that // Channel updated with both Subscriptions. getNewSubscriptionWithFromChannel(), - rename(getNewSubscriptionWithReferencesResolvedAndPhysicalFromCallResult()), + rename(getNewSubscriptionWithReferencesResolvedAndPhysicalSubscriberReply()), // This subscription has a different physical From, so we should not see it in the same // Channel as the first two. getSubscriptionWithDifferentChannel(), @@ -583,9 +656,9 @@ var testCases = []controllertesting.TestCase{ // a Strategic Merge Patch, whereas we are doing a JSON Patch). so for now, comment it // out. //getChannelWithMultipleSubscriptions(), - getNewSubscriptionWithSourceWithReferencesResolvedAndPhysicalFromCallResult(), + getNewSubscriptionWithSourceWithReferencesResolvedAndPhysicalFromSubscriberReply(), // Unaltered because this Subscription was not reconciled. - rename(getNewSubscriptionWithReferencesResolvedAndPhysicalFromCallResult()), + rename(getNewSubscriptionWithReferencesResolvedAndPhysicalSubscriberReply()), getSubscriptionWithDifferentChannel(), }, Scheme: scheme.Scheme, @@ -600,18 +673,10 @@ var testCases = []controllertesting.TestCase{ "name": sourceName, }, "spec": map[string]interface{}{ - "channelable": map[string]interface{}{}, + "subscribable": map[string]interface{}{}, }, - "status": map[string]interface{}{ - "subscribable": map[string]interface{}{ - "channelable": map[string]interface{}{ - "kind": channelKind, - "name": fromChannelName, - "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), - }, - }, - }, - }}, + }, + }, // Source channel &unstructured.Unstructured{ Object: map[string]interface{}{ @@ -622,19 +687,11 @@ var testCases = []controllertesting.TestCase{ "name": fromChannelName, }, "spec": map[string]interface{}{ - "channelable": map[string]interface{}{}, - }, - "status": map[string]interface{}{ - "subscribable": map[string]interface{}{ - "channelable": map[string]interface{}{ - "kind": channelKind, - "name": fromChannelName, - "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), - }, - }, + "subscribable": map[string]interface{}{}, }, - }}, - // Call (using knative route) + }, + }, + // Subscriber (using knative route) &unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": "serving.knative.dev/v1alpha1", @@ -644,12 +701,13 @@ var testCases = []controllertesting.TestCase{ "name": routeName, }, "status": map[string]interface{}{ - "targetable": map[string]interface{}{ - "domainInternal": targetDNS, + "address": map[string]interface{}{ + "hostname": targetDNS, }, }, - }}, - // Result channel + }, + }, + // Reply channel &unstructured.Unstructured{ Object: map[string]interface{}{ "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), @@ -659,23 +717,70 @@ var testCases = []controllertesting.TestCase{ "name": resultChannelName, }, "spec": map[string]interface{}{ - "channelable": map[string]interface{}{}, + "subscribable": map[string]interface{}{}, }, "status": map[string]interface{}{ - "subscribable": map[string]interface{}{ - "channelable": map[string]interface{}{ - "kind": channelKind, - "name": fromChannelName, - "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), - }, + "address": map[string]interface{}{ + "hostname": sinkableDNS, }, - "sinkable": map[string]interface{}{ - "domainInternal": sinkableDNS, + }, + }, + }, + }, + }, + { + Name: "delete subscription with from channel: subscribers modified", + InitialState: []runtime.Object{ + getNewDeletedSubscriptionWithChannelReady(), + }, + // TODO: JSON patch is not working on the fake, see + // https://github.com/kubernetes/client-go/issues/478. Marking this as expecting a specific + // failure for now, until upstream is fixed. + WantResult: reconcile.Result{}, + WantErrMsg: "invalid JSON document", + WantAbsent: []runtime.Object{ + // TODO: JSON patch is not working on the fake, see + // https://github.com/kubernetes/client-go/issues/478. The entire test is really to + // verify the following, but can't be done because the call to Patch fails (it assumes + // a Strategic Merge Patch, whereas we are doing a JSON Patch). so for now, comment it + // out. + //getNewDeletedSubscriptionWithChannelReady(), + }, + WantPresent: []runtime.Object{ + // TODO: JSON patch is not working on the fake, see + // https://github.com/kubernetes/client-go/issues/478. The entire test is really to + // verify the following, but can't be done because the call to Patch fails (it assumes + // a Strategic Merge Patch, whereas we are doing a JSON Patch). so for now, comment it + // out. + //getChannelWithOtherSubscription(), + }, + Objects: []runtime.Object{ + // Source channel + &unstructured.Unstructured{ + Object: map[string]interface{}{ + "apiVersion": eventingv1alpha1.SchemeGroupVersion.String(), + "kind": channelKind, + "metadata": map[string]interface{}{ + "namespace": testNS, + "name": fromChannelName, + }, + "spec": map[string]interface{}{ + "channelable": map[string]interface{}{ + "subscribers": []interface{}{ + map[string]interface{}{ + "subscriberURI": targetDNS, + "replyURI": sinkableDNS, + }, + map[string]interface{}{ + "replyURI": otherAddressableDNS, + }, + }, }, }, }, }, }, + Scheme: scheme.Scheme, }, } @@ -698,11 +803,67 @@ func TestAllCases(t *testing.T) { } } +func TestFinalizers(t *testing.T) { + var testcases = []struct { + name string + original sets.String + add bool + want sets.String + }{ + { + name: "empty, add", + original: sets.NewString(), + add: true, + want: sets.NewString(finalizerName), + }, { + name: "empty, delete", + original: sets.NewString(), + add: false, + want: sets.NewString(), + }, { + name: "existing, delete", + original: sets.NewString(finalizerName), + add: false, + want: sets.NewString(), + }, { + name: "existing, add", + original: sets.NewString(finalizerName), + add: true, + want: sets.NewString(finalizerName), + }, { + name: "existing two, delete", + original: sets.NewString(finalizerName, "someother"), + add: false, + want: sets.NewString("someother"), + }, { + name: "existing two, no change", + original: sets.NewString(finalizerName, "someother"), + add: true, + want: sets.NewString(finalizerName, "someother"), + }, + } + + for _, tc := range testcases { + original := &eventingv1alpha1.Subscription{} + original.Finalizers = tc.original.List() + if tc.add { + addFinalizer(original) + } else { + removeFinalizer(original) + } + has := sets.NewString(original.Finalizers...) + diff := has.Difference(tc.want) + if diff.Len() > 0 { + t.Errorf("%q failed, diff: %+v", tc.name, diff) + } + } +} + func getNewFromChannel() *eventingv1alpha1.Channel { return getNewChannel(fromChannelName) } -func getNewResultChannel() *eventingv1alpha1.Channel { +func getNewReplyChannel() *eventingv1alpha1.Channel { return getNewChannel(resultChannelName) } @@ -724,8 +885,8 @@ func getNewChannel(name string) *eventingv1alpha1.Channel { func rename(sub *eventingv1alpha1.Subscription) *eventingv1alpha1.Subscription { sub.Name = "renamed" sub.UID = "renamed-UID" - sub.Status.PhysicalSubscription.CallDomain = "" - sub.Status.PhysicalSubscription.ResultDomain = otherSinkableDNS + sub.Status.PhysicalSubscription.SubscriberURI = "" + sub.Status.PhysicalSubscription.ReplyURI = otherAddressableDNS return sub } @@ -734,20 +895,20 @@ func getNewSubscription() *eventingv1alpha1.Subscription { TypeMeta: subscriptionType(), ObjectMeta: om(testNS, subscriptionName), Spec: eventingv1alpha1.SubscriptionSpec{ - From: corev1.ObjectReference{ + Channel: corev1.ObjectReference{ Name: fromChannelName, Kind: channelKind, APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), }, - Call: &eventingv1alpha1.EndpointSpec{ - TargetRef: &corev1.ObjectReference{ + Subscriber: &eventingv1alpha1.SubscriberSpec{ + Ref: &corev1.ObjectReference{ Name: routeName, Kind: routeKind, APIVersion: "serving.knative.dev/v1alpha1", }, }, - Result: &eventingv1alpha1.ResultStrategy{ - Target: &corev1.ObjectReference{ + Reply: &eventingv1alpha1.ReplyStrategy{ + Channel: &corev1.ObjectReference{ Name: resultChannelName, Kind: channelKind, APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), @@ -762,10 +923,32 @@ func getNewSubscription() *eventingv1alpha1.Subscription { return subscription } +func getNewSubscriptionWithEmptyNonNilReply() *eventingv1alpha1.Subscription { + sub := getNewSubscription() + sub.Spec.Reply = &eventingv1alpha1.ReplyStrategy{} + return sub +} + +func getNewSubscriptionWithEmptyNonNilSubscriber() *eventingv1alpha1.Subscription { + sub := getNewSubscription() + sub.Spec.Subscriber = &eventingv1alpha1.SubscriberSpec{} + return sub +} + +func getNewSourceSubscription() *eventingv1alpha1.Subscription { + sub := getNewSubscription() + sub.Spec.Channel = corev1.ObjectReference{ + APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), + Kind: sourceKind, + Name: sourceName, + } + return sub +} + func getNewSubscriptionToK8sService() *eventingv1alpha1.Subscription { sub := getNewSubscription() - sub.Spec.Call = &eventingv1alpha1.EndpointSpec{ - TargetRef: &corev1.ObjectReference{ + sub.Spec.Subscriber = &eventingv1alpha1.SubscriberSpec{ + Ref: &corev1.ObjectReference{ Name: k8sServiceName, Kind: "Service", APIVersion: "v1", @@ -774,25 +957,31 @@ func getNewSubscriptionToK8sService() *eventingv1alpha1.Subscription { return sub } +func getNewSubscriptionToK8sServiceWithUnknownConditions() *eventingv1alpha1.Subscription { + sub := getNewSubscriptionToK8sService() + sub.Status.InitializeConditions() + return sub +} + func getNewSubscriptionWithFromChannel() *eventingv1alpha1.Subscription { subscription := &eventingv1alpha1.Subscription{ TypeMeta: subscriptionType(), ObjectMeta: om(testNS, subscriptionName), Spec: eventingv1alpha1.SubscriptionSpec{ - From: corev1.ObjectReference{ + Channel: corev1.ObjectReference{ Name: fromChannelName, Kind: channelKind, APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), }, - Call: &eventingv1alpha1.EndpointSpec{ - TargetRef: &corev1.ObjectReference{ + Subscriber: &eventingv1alpha1.SubscriberSpec{ + Ref: &corev1.ObjectReference{ Name: routeName, Kind: routeKind, APIVersion: "serving.knative.dev/v1alpha1", }, }, - Result: &eventingv1alpha1.ResultStrategy{ - Target: &corev1.ObjectReference{ + Reply: &eventingv1alpha1.ReplyStrategy{ + Channel: &corev1.ObjectReference{ Name: resultChannelName, Kind: channelKind, APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), @@ -812,52 +1001,54 @@ func getNewSubscriptionWithUnknownConditions() *eventingv1alpha1.Subscription { s.Status.InitializeConditions() return s } - -func getNewSubscriptionWithUnknownConditionsAndPhysicalFrom() *eventingv1alpha1.Subscription { +func getNewSubscriptionWithUnknownConditionsAndPhysicalSubscriber() *eventingv1alpha1.Subscription { s := getNewSubscriptionWithUnknownConditions() - // The original From is a Channel, so points at itself. - s.Status.PhysicalSubscription.From = s.Spec.From + s.Status.PhysicalSubscription.SubscriberURI = domainToURL(targetDNS) + return s +} + +func getNewSubscriptionWithReferencesResolvedAndPhysicalSubscriberAndNoReply() *eventingv1alpha1.Subscription { + s := getNewSubscriptionWithEmptyNonNilReply() + s.Status.InitializeConditions() + s.Status.MarkReferencesResolved() + s.Status.PhysicalSubscription.SubscriberURI = domainToURL(targetDNS) return s } -func getNewSubscriptionWithUnknownConditionsAndPhysicalFromCall() *eventingv1alpha1.Subscription { - s := getNewSubscriptionWithUnknownConditionsAndPhysicalFrom() - s.Status.PhysicalSubscription.CallDomain = targetDNS +func getNewSubscriptionWithReferencesResolvedAndPhysicalReplyAndNoSubscriber() *eventingv1alpha1.Subscription { + s := getNewSubscriptionWithEmptyNonNilSubscriber() + s.Status.InitializeConditions() + s.Status.MarkReferencesResolved() + s.Status.PhysicalSubscription.ReplyURI = domainToURL(sinkableDNS) return s } -func getNewSubscriptionWithReferencesResolvedAndPhysicalFromCallResult() *eventingv1alpha1.Subscription { - s := getNewSubscriptionWithUnknownConditionsAndPhysicalFrom() +func getNewSubscriptionWithReferencesResolvedAndPhysicalSubscriberReply() *eventingv1alpha1.Subscription { + s := getNewSubscriptionWithUnknownConditions() s.Status.MarkReferencesResolved() - s.Status.PhysicalSubscription.CallDomain = targetDNS - s.Status.PhysicalSubscription.ResultDomain = sinkableDNS + s.Status.PhysicalSubscription.SubscriberURI = domainToURL(targetDNS) + s.Status.PhysicalSubscription.ReplyURI = domainToURL(sinkableDNS) return s } -func getNewSubscriptionToK8sServiceWithReferencesResolvedAndPhysicalFromCallResult() *eventingv1alpha1.Subscription { +func getNewSubscriptionToK8sServiceWithReferencesResolvedAndPhysicalFromSubscriberReply() *eventingv1alpha1.Subscription { s := getNewSubscriptionToK8sService() s.Status.InitializeConditions() s.Status.MarkReferencesResolved() s.Status.PhysicalSubscription = eventingv1alpha1.SubscriptionStatusPhysicalSubscription{ - From: s.Spec.From, - CallDomain: k8sServiceDNS, - ResultDomain: sinkableDNS, + SubscriberURI: domainToURL(k8sServiceDNS), + ReplyURI: domainToURL(sinkableDNS), } return s } -func getNewSubscriptionWithSourceWithReferencesResolvedAndPhysicalFromCallResult() *eventingv1alpha1.Subscription { +func getNewSubscriptionWithSourceWithReferencesResolvedAndPhysicalFromSubscriberReply() *eventingv1alpha1.Subscription { s := getNewSubscriptionWithFromChannel() s.Status.InitializeConditions() s.Status.MarkReferencesResolved() s.Status.PhysicalSubscription = eventingv1alpha1.SubscriptionStatusPhysicalSubscription{ - From: corev1.ObjectReference{ - APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), - Kind: channelKind, - Name: fromChannelName, - }, - CallDomain: targetDNS, - ResultDomain: sinkableDNS, + SubscriberURI: domainToURL(targetDNS), + ReplyURI: domainToURL(sinkableDNS), } return s } @@ -869,11 +1060,20 @@ func getNewSubscriptionWithReferencesResolvedStatus() *eventingv1alpha1.Subscrip } func getSubscriptionWithDifferentChannel() *eventingv1alpha1.Subscription { - s := getNewSubscriptionWithSourceWithReferencesResolvedAndPhysicalFromCallResult() + s := getNewSubscriptionWithSourceWithReferencesResolvedAndPhysicalFromSubscriberReply() s.Name = "different-channel" s.UID = "different-channel-UID" - s.Status.PhysicalSubscription.From.Name = "other-channel" - s.Status.PhysicalSubscription.CallDomain = "some-other-domain" + s.Status.PhysicalSubscription.SubscriberURI = "some-other-domain" + return s +} + +func getNewDeletedSubscriptionWithChannelReady() *eventingv1alpha1.Subscription { + s := getNewSubscriptionWithUnknownConditions() + s.Status.MarkReferencesResolved() + s.Status.PhysicalSubscription.SubscriberURI = domainToURL(targetDNS) + s.Status.PhysicalSubscription.ReplyURI = domainToURL(sinkableDNS) + s.Status.MarkChannelReady() + s.ObjectMeta.DeletionTimestamp = &deletionTime return s } @@ -912,14 +1112,47 @@ func getChannelWithMultipleSubscriptions() *eventingv1alpha1.Channel { }, ObjectMeta: om(testNS, fromChannelName), Spec: eventingv1alpha1.ChannelSpec{ - Channelable: &duckv1alpha1.Channelable{ - Subscribers: []duckv1alpha1.ChannelSubscriberSpec{ + Subscribable: &eventingduck.Subscribable{ + Subscribers: []eventingduck.ChannelSubscriberSpec{ + { + Ref: &corev1.ObjectReference{ + APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), + Kind: subscriptionKind, + Namespace: testNS, + Name: subscriptionName, + UID: "", + }, + SubscriberURI: targetDNS, + ReplyURI: sinkableDNS, + }, { - CallableDomain: targetDNS, - SinkableDomain: sinkableDNS, + Ref: &corev1.ObjectReference{ + APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), + Kind: subscriptionKind, + Namespace: testNS, + Name: "renamed", + UID: "renamed-UID", + }, + ReplyURI: otherAddressableDNS, }, + }, + }, + }, + } +} + +func getChannelWithOtherSubscription() *eventingv1alpha1.Channel { + return &eventingv1alpha1.Channel{ + TypeMeta: metav1.TypeMeta{ + APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), + Kind: channelKind, + }, + ObjectMeta: om(testNS, fromChannelName), + Spec: eventingv1alpha1.ChannelSpec{ + Subscribable: &eventingduck.Subscribable{ + Subscribers: []eventingduck.ChannelSubscriberSpec{ { - SinkableDomain: otherSinkableDNS, + ReplyURI: otherAddressableDNS, }, }, }, diff --git a/pkg/controller/eventtype/provider_test.go b/pkg/controller/eventtype/provider_test.go deleted file mode 100644 index f205632afe4..00000000000 --- a/pkg/controller/eventtype/provider_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package eventtype - -import ( - "github.com/google/go-cmp/cmp" - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/handler" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - "testing" -) - -const ( - feedName = "feed-name" -) - -type mapTestCase struct { - name string - obj handler.MapObject - rr []reconcile.Request -} - -func TestMap(t *testing.T) { - testCases := []mapTestCase{ - { - name: "not a Feed", - obj: handler.MapObject{ - Object: getPod(), - }, - rr: []reconcile.Request{}, - }, - { - name: "Feed", - obj: handler.MapObject{ - Meta: getFeed(etNamespace, feedName, etName), - Object: getFeed(etNamespace, feedName, etName), - }, - rr: []reconcile.Request{ - { - NamespacedName: types.NamespacedName{ - Namespace: etNamespace, - Name: etName, - }, - }, - }, - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - feedToEventType := feedToEventType{} - actualRR := feedToEventType.Map(tc.obj) - if diff := cmp.Diff(tc.rr, actualRR); diff != "" { - t.Errorf("Reconcile request (-want, +got) = %v", diff) - } - }) - } -} - -func getPod() *v1.Pod { - return &v1.Pod{ - ObjectMeta: objectMeta(etNamespace, "pod-name"), - TypeMeta: metav1.TypeMeta{ - APIVersion: v1.SchemeGroupVersion.String(), - Kind: "Pod", - }, - } -} diff --git a/pkg/controller/eventtype/reconcile.go b/pkg/controller/eventtype/reconcile.go deleted file mode 100644 index a599a10a62c..00000000000 --- a/pkg/controller/eventtype/reconcile.go +++ /dev/null @@ -1,230 +0,0 @@ -/* -Copyright 2018 The Knative 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 eventtype - -import ( - "context" - "fmt" - feedsv1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - "go.uber.org/zap" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/sets" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - "strings" -) - -const ( - finalizerName = controllerAgentName -) - -// Reconcile compares the actual state of a Feed with the desired, and attempts -// to converge the two. It then updates the Status block of the Feed with -// its current state. -// If Reconcile returns a non-nil error, the request will be retried. -func (r *reconciler) Reconcile(request reconcile.Request) (reconcile.Result, error) { - //TODO use this to store the logger and set a deadline - ctx := context.TODO() - - et := &feedsv1alpha1.EventType{} - err := r.client.Get(ctx, request.NamespacedName, et) - - // The EventType may have been deleted since it was added to the workqueue. If so - // there's nothing to be done. - if errors.IsNotFound(err) { - r.logger.Error("could not find EventType", zap.Any("request", request)) - return reconcile.Result{}, nil - } - - // If the EventType exists but could not be retrieved, then we should retry. - if err != nil { - r.logger.Error("could not fetch EventType", - zap.Any("request", request), - zap.Error(err)) - return reconcile.Result{}, err - } - - // Now that we know the EventType exists, we can reconcile it. An error returned - // here means the reconcile did not complete and the EventType should be requeued - // for another attempt. - // A successful reconcile does not necessarily mean the EventType is in the desired - // state, it means no more can be done for now. In this case the EventType will - // not be reconciled again until the resync period or a watched resource changes. - if err = r.reconcile(ctx, et); err != nil { - r.logger.Error("error reconciling EventType", - zap.Any("EventType", et), - zap.Error(err)) - // Note that we do not return the error here. That is because we rely on r.updateEventType() - // to write any updated status to the API server. After updating the API server, then we - // should return this error. - } - - // Since the reconcile is a sequence of steps, earlier steps may complete - // successfully while later steps fail. The EventType is updated on failure to - // preserve any useful status or metadata changes the non-failing steps made. - if updateErr := r.updateEventType(ctx, et); updateErr != nil { - r.logger.Error("failed to update EventType", - zap.Any("EventType", et), - zap.Error(updateErr)) - // An error here means the EventType should be reconciled again, regardless of - // whether the reconcile was successful or not. - return reconcile.Result{}, updateErr - } - return reconcile.Result{}, err -} - -// reconcile tries to converge the current state of the given EventType to the desired state. This -// function should not update the EventType in the API server. This method will update 'et'. The -// calling method is responsible for writing back to the API server. -func (r *reconciler) reconcile(ctx context.Context, et *feedsv1alpha1.EventType) error { - if et.GetDeletionTimestamp() == nil { - r.addFinalizer(et) - } else { - err := r.handleDeletion(ctx, et) - if err != nil { - r.logger.Error("Error deleting the EventType", - zap.Any("EventType", et), - zap.Error(err)) - return err - } - } - return nil -} - -func (r *reconciler) addFinalizer(et *feedsv1alpha1.EventType) { - finalizers := sets.NewString(et.Finalizers...) - finalizers.Insert(finalizerName) - et.Finalizers = finalizers.List() -} - -func (r *reconciler) removeFinalizer(et *feedsv1alpha1.EventType) { - finalizers := sets.NewString(et.Finalizers...) - finalizers.Delete(finalizerName) - et.Finalizers = finalizers.List() -} - -// handleDeletion checks the finalizer conditions of an EventType marked for deletion. If the -// conditions are met, then it removes the finalizer. Otherwise it adds a Status saying why it -// can't. -func (r *reconciler) handleDeletion(ctx context.Context, et *feedsv1alpha1.EventType) error { - feeds, err := r.findFeedsUsingEventType(ctx, et) - if err != nil { - r.logger.Info("Unable to find Feeds using EventType", - zap.String("EventType.Name", et.Name), - zap.Error(err)) - return err - } - if len(feeds) == 0 { - r.removeFinalizer(et) - } else { - r.logger.Info("Cannot remove finalizer from EventType, Feed(s) still use it.", - zap.String("EventType.Name", et.Name), - zap.Int("feedsUsingEventType", len(feeds))) - } - r.updateInUseStatus(ctx, et, feeds) - return nil -} - -// findFeedsUsingEventTypes finds all the Feeds in the same namespace as et that use et. -func (r *reconciler) findFeedsUsingEventType(ctx context.Context, et *feedsv1alpha1.EventType) ( - []feedsv1alpha1.Feed, error) { - allFeeds := &feedsv1alpha1.FeedList{} - listOptions := client.InNamespace(et.Namespace) - - //TODO this is here because the fake client needs it. Remove this when it's - // no longer needed. - listOptions.Raw = &metav1.ListOptions{ - TypeMeta: metav1.TypeMeta{ - APIVersion: feedsv1alpha1.SchemeGroupVersion.String(), - Kind: "Feed", - }, - } - err := r.client.List(ctx, listOptions, allFeeds) - if err != nil { - r.logger.Error("Unable to list feeds", zap.Error(err)) - return nil, err - } - feeds := make([]feedsv1alpha1.Feed, 0, len(allFeeds.Items)) - - for _, feed := range allFeeds.Items { - if et.Name == feed.Spec.Trigger.EventType { - feeds = append(feeds, feed) - } - } - return feeds, nil -} - -func (r *reconciler) updateInUseStatus(ctx context.Context, et *feedsv1alpha1.EventType, feedsStillUsingEventType []feedsv1alpha1.Feed) { - // Filter out the existing InUse condition, if present. - var newConditions []feedsv1alpha1.CommonEventTypeCondition - for _, condition := range et.Status.Conditions { - if condition.Type != feedsv1alpha1.EventTypeInUse { - newConditions = append(newConditions, condition) - } - } - - if len(feedsStillUsingEventType) > 0 { - // Add the up-to-date InUse condition. - newConditions = append(newConditions, feedsv1alpha1.CommonEventTypeCondition{ - Type: feedsv1alpha1.EventTypeInUse, - Status: corev1.ConditionTrue, - Message: fmt.Sprintf("Still in use by the Feeds: %s", getFeedNames(feedsStillUsingEventType)), - }) - } - - et.Status.Conditions = newConditions -} - -// getFeedNames generates a single string with the names of all the feeds. -func getFeedNames(feeds []feedsv1alpha1.Feed) string { - feedNames := make([]string, 0, len(feeds)) - for _, feed := range feeds { - feedNames = append(feedNames, feed.Name) - } - return strings.Join(feedNames, ", ") -} - -func (r *reconciler) updateEventType(ctx context.Context, u *feedsv1alpha1.EventType) error { - et := &feedsv1alpha1.EventType{} - err := r.client.Get(ctx, client.ObjectKey{Namespace: u.Namespace, Name: u.Name}, et) - if err != nil { - return err - } - - updated := false - if !equality.Semantic.DeepEqual(et.Finalizers, u.Finalizers) { - et.SetFinalizers(u.ObjectMeta.Finalizers) - updated = true - } - - if !equality.Semantic.DeepEqual(et.Status, u.Status) { - et.Status = u.Status - updated = true - } - - if updated == false { - return nil - } - // Until #38113 is merged, we must use Update instead of UpdateStatus to - // update the Status block of the Feed resource. UpdateStatus will not - // allow changes to the Spec of the resource, which is ideal for ensuring - // nothing other than resource status has been updated. - return r.client.Update(ctx, et) -} diff --git a/pkg/controller/eventtype/reconcile_test.go b/pkg/controller/eventtype/reconcile_test.go deleted file mode 100644 index c0d1447758a..00000000000 --- a/pkg/controller/eventtype/reconcile_test.go +++ /dev/null @@ -1,299 +0,0 @@ -/* -Copyright 2018 The Knative 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 eventtype - -import ( - "context" - "errors" - "fmt" - feedsv1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - controllertesting "github.com/knative/eventing/pkg/controller/testing" - "go.uber.org/zap" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/tools/record" - "sigs.k8s.io/controller-runtime/pkg/client" - "testing" -) - -var ( - // deletionTime is used when objects are marked as deleted. Rfc3339Copy() - // truncates to seconds to match the loss of precision during serialization. - deletionTime = metav1.Now().Rfc3339Copy() -) - -const ( - eventSourceName = "event-source" - etNamespace = "test-namespace" - etName = "test-event-type" - reconcileKey = etNamespace + "/" + etName - - fn1 = "fake-feed-name-1" - fn2 = "fake-feed-name-2" - - getError = "test induced error getting" - listError = "test induced error listing" - updateError = "test induced error updating" -) - -func init() { - // Add types to scheme - feedsv1alpha1.AddToScheme(scheme.Scheme) -} - -func TestAllCases(t *testing.T) { - testCases := []controllertesting.TestCase{ - { - Name: "missing EventType", - ReconcileKey: reconcileKey, - }, - { - Name: "Internal error getting EventType", - ReconcileKey: reconcileKey, - WantErrMsg: getError, - Mocks: controllertesting.Mocks{ - MockGets: []controllertesting.MockGet{ - func(_ client.Client, _ context.Context, _ client.ObjectKey, _ runtime.Object) (controllertesting.MockHandled, error) { - return controllertesting.Handled, errors.New(getError) - }, - }, - }, - }, - { - Name: "new EventType: adds Finalizer", - InitialState: []runtime.Object{ - getEventType(false), - }, - ReconcileKey: reconcileKey, - WantPresent: []runtime.Object{ - getEventType(true), - }, - }, - { - Name: "tries to add finalizer -- second EventType.Get() errors", - InitialState: []runtime.Object{ - getEventType(false), - }, - WantPresent: []runtime.Object{ - // Unable to update the EventType, it should still be in the initial state. - getEventType(false), - }, - ReconcileKey: reconcileKey, - WantErrMsg: getError, - Mocks: controllertesting.Mocks{ - MockGets: []controllertesting.MockGet{ - // The first Get should pass through to the inner client. - func(innerClient client.Client, ctx context.Context, key client.ObjectKey, obj runtime.Object) (controllertesting.MockHandled, error) { - realResponse := innerClient.Get(ctx, key, obj) - return controllertesting.Handled, realResponse - }, - // The second Get, which runs inside the Update logic, should error. - func(_ client.Client, _ context.Context, _ client.ObjectKey, _ runtime.Object) (controllertesting.MockHandled, error) { - return controllertesting.Handled, errors.New(getError) - }, - }, - }, - }, - { - Name: "tries to add finalizer -- EventType.Update() errors", - InitialState: []runtime.Object{ - getEventType(false), - }, - WantPresent: []runtime.Object{ - // Unable to update the EventType, it should still be in the initial state. - getEventType(false), - }, - ReconcileKey: reconcileKey, - WantErrMsg: updateError, - Mocks: controllertesting.Mocks{ - MockUpdates: []controllertesting.MockUpdate{ - func(_ client.Client, _ context.Context, _ runtime.Object) (controllertesting.MockHandled, error) { - return controllertesting.Handled, errors.New(updateError) - }, - }, - }, - }, - { - Name: "old EventType: already has Finalizer", - InitialState: []runtime.Object{ - getEventType(true), - }, - ReconcileKey: reconcileKey, - WantPresent: []runtime.Object{ - getEventType(true), - }, - }, - { - Name: "deleting EventType: no Feeds", - InitialState: []runtime.Object{ - getDeletingEventType(true), - }, - ReconcileKey: reconcileKey, - WantPresent: []runtime.Object{ - // The Finalizer should have been removed. - getDeletingEventType(false), - }, - }, - { - Name: "deleting EventType: Feeds not using EventType", - InitialState: []runtime.Object{ - getDeletingEventType(true), - getFeedUsingOtherEventType(), - }, - ReconcileKey: reconcileKey, - WantPresent: []runtime.Object{ - // The Finalizer should have been removed. - getDeletingEventType(false), - }, - }, { - Name: "deleting EventType: Feeds using EventType in different namespace", - InitialState: []runtime.Object{ - getDeletingEventType(true), - getFeedUsingEventTypeInDifferentNamespace(), - }, - ReconcileKey: reconcileKey, - WantPresent: []runtime.Object{ - // The Finalizer should have been removed. - getDeletingEventType(false), - }, - }, - { - Name: "deleting EventType: Feeds using EventType", - InitialState: []runtime.Object{ - getDeletingEventTypeWithCompleteStatus(), - getFeedUsingEventType(fn1), - getFeedUsingEventType(fn2), - }, - ReconcileKey: reconcileKey, - WantPresent: []runtime.Object{ - // There are Feeds still using the EventType, it should still have its Finalizer and a - // new Status added stating which Feeds are blocking its deletion. - getDeletingEventTypeWithCompleteAndInUseStatus(fn1 + ", " + fn2), - }, - }, - { - Name: "deleting EventType: can't list Feeds", - InitialState: []runtime.Object{ - getDeletingEventType(true), - }, - ReconcileKey: reconcileKey, - WantPresent: []runtime.Object{ - // Unable to update the EventType, it should still be in the initial state. - getDeletingEventType(true), - }, - WantErrMsg: listError, - Mocks: controllertesting.Mocks{ - MockLists: []controllertesting.MockList{ - func(_ client.Client, _ context.Context, _ *client.ListOptions, _ runtime.Object) (controllertesting.MockHandled, error) { - return controllertesting.Handled, errors.New(listError) - }, - }, - }, - }, - } - recorder := record.NewBroadcaster().NewRecorder(scheme.Scheme, corev1.EventSource{Component: controllerAgentName}) - - for _, tc := range testCases { - c := tc.GetClient() - r := &reconciler{ - client: c, - recorder: recorder, - logger: zap.NewNop(), - } - t.Run(tc.Name, tc.Runner(t, r, c)) - } -} - -func objectMeta(namespace, name string) metav1.ObjectMeta { - return metav1.ObjectMeta{ - Namespace: namespace, - Name: name, - SelfLink: fmt.Sprintf("/apis/eventing/v1alpha1/namespaces/%s/object/%s", namespace, name), - } -} - -func getEventType(finalizer bool) *feedsv1alpha1.EventType { - et := &feedsv1alpha1.EventType{ - TypeMeta: metav1.TypeMeta{ - APIVersion: feedsv1alpha1.SchemeGroupVersion.String(), - Kind: "EventType", - }, - ObjectMeta: objectMeta(etNamespace, etName), - Spec: feedsv1alpha1.EventTypeSpec{ - EventSource: eventSourceName, - }, - } - if finalizer { - et.Finalizers = []string{finalizerName} - } - return et -} - -func getDeletingEventType(finalizer bool) *feedsv1alpha1.EventType { - et := getEventType(finalizer) - et.ObjectMeta.DeletionTimestamp = &deletionTime - return et -} - -func getDeletingEventTypeWithCompleteStatus() *feedsv1alpha1.EventType { - et := getDeletingEventType(true) - et.Status.Conditions = append(et.Status.Conditions, feedsv1alpha1.CommonEventTypeCondition{ - Type: feedsv1alpha1.EventTypeComplete, - Status: corev1.ConditionTrue, - }) - return et -} - -func getDeletingEventTypeWithCompleteAndInUseStatus(feedNames string) *feedsv1alpha1.EventType { - et := getDeletingEventTypeWithCompleteStatus() - et.Status.Conditions = append(et.Status.Conditions, feedsv1alpha1.CommonEventTypeCondition{ - Type: feedsv1alpha1.EventTypeInUse, - Status: corev1.ConditionTrue, - Message: "Still in use by the Feeds: " + feedNames, - }) - return et -} - -func getFeed(namespace, name, eventType string) *feedsv1alpha1.Feed { - feed := &feedsv1alpha1.Feed{ - TypeMeta: metav1.TypeMeta{ - APIVersion: feedsv1alpha1.SchemeGroupVersion.String(), - Kind: "Feed", - }, - ObjectMeta: objectMeta(namespace, name), - Spec: feedsv1alpha1.FeedSpec{ - Trigger: feedsv1alpha1.EventTrigger{ - EventType: eventType, - }, - }, - } - return feed -} - -func getFeedUsingOtherEventType() *feedsv1alpha1.Feed { - return getFeed(etNamespace, "feed-not-using-event-type", "some-other-event-type") -} - -func getFeedUsingEventType(feedName string) *feedsv1alpha1.Feed { - return getFeed(etNamespace, feedName, etName) -} - -func getFeedUsingEventTypeInDifferentNamespace() *feedsv1alpha1.Feed { - return getFeed("some-other-namespace", "feed-in-different-namespace", etName) -} diff --git a/pkg/controller/feed/errors.go b/pkg/controller/feed/errors.go deleted file mode 100644 index db4a451d14f..00000000000 --- a/pkg/controller/feed/errors.go +++ /dev/null @@ -1,69 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Veroute.on 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 feed - -const ( - // EventSourceDoesNotExist is a condition reason used when an EventSource - // referenced by a Feed does not exist. - EventSourceDoesNotExist string = "EventSourceDoesNotExist" - - // EventSourceDeleting is a condition reason used when an EventSource - // referenced by a feed has been marked for deletion. - EventSourceDeleting string = "EventSourceDeleting" - - // EventTypeDoesNotExist is a condition reason used when an EventType - // referenced by a Feed does not exist. - EventTypeDoesNotExist string = "EventTypeDoesNotExist" - - // EventTypeDeleting is a condition reason used when an EventType - // referenced by a feed has been marked for deletion. - EventTypeDeleting string = "EventTypeDeleting" -) - -// StatusError can be returned from lower level functions and used as the input -// for setting conditions on the Feed. -type StatusError struct { - // Reason is a one-word CamelCase reason for the failure. - Reason string - // Message is a human-readable message describing the error. - Message string -} - -// Error implements the error interface. -func (se *StatusError) Error() string { - return se.Message -} - -// EventSourceError is a StatusError specifically for EventSource errors. -type EventSourceError struct { - StatusError -} - -// Error implements the error interface. -func (es *EventSourceError) Error() string { - return es.StatusError.Error() -} - -// EventTypeError is a StatusError specifically for EventType errors. -type EventTypeError struct { - StatusError -} - -// Error implements the error interface. -func (es *EventTypeError) Error() string { - return es.StatusError.Error() -} diff --git a/pkg/controller/feed/provider.go b/pkg/controller/feed/provider.go deleted file mode 100644 index 75f075f3701..00000000000 --- a/pkg/controller/feed/provider.go +++ /dev/null @@ -1,71 +0,0 @@ -/* -Copyright 2018 The Knative 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 feed - -import ( - feedsv1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - batchv1 "k8s.io/api/batch/v1" - "k8s.io/client-go/tools/record" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/controller" - "sigs.k8s.io/controller-runtime/pkg/handler" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - "sigs.k8s.io/controller-runtime/pkg/source" -) - -const controllerAgentName = "feed-controller" - -type reconciler struct { - client client.Client - recorder record.EventRecorder -} - -// Verify the struct implements reconcile.Reconciler -var _ reconcile.Reconciler = &reconciler{} - -// ProvideController returns a Feed controller and adds it to the given Manager. -func ProvideController(mgr manager.Manager) (controller.Controller, error) { - // Setup a new controller to Reconcile Feeds. - c, err := controller.New(controllerAgentName, mgr, controller.Options{ - Reconciler: &reconciler{ - recorder: mgr.GetRecorder(controllerAgentName), - }, - }) - if err != nil { - return nil, err - } - - // Watch Feed events and enqueue Feed object key. - if err := c.Watch(&source.Kind{Type: &feedsv1alpha1.Feed{}}, &handler.EnqueueRequestForObject{}); err != nil { - return nil, err - } - - // Watch Jobs and enqueue owning Feed key. - if err := c.Watch(&source.Kind{Type: &batchv1.Job{}}, - &handler.EnqueueRequestForOwner{OwnerType: &feedsv1alpha1.Feed{}, IsController: true}); err != nil { - return nil, err - } - - return c, nil -} - -// InjectClient is called by the injector to set the reconciler's client field. -func (r *reconciler) InjectClient(c client.Client) error { - r.client = c - return nil -} diff --git a/pkg/controller/feed/reconcile.go b/pkg/controller/feed/reconcile.go deleted file mode 100644 index 1f9048168cd..00000000000 --- a/pkg/controller/feed/reconcile.go +++ /dev/null @@ -1,565 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Veroute.on 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 feed - -import ( - "context" - "encoding/base64" - "encoding/json" - "fmt" - - "github.com/golang/glog" - feedsv1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - "github.com/knative/eventing/pkg/controller/feed/resources" - "github.com/knative/eventing/pkg/sources" - "gopkg.in/yaml.v2" - batchv1 "k8s.io/api/batch/v1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/reconcile" -) - -const ( - finalizerName = controllerAgentName -) - -// Reconcile compares the actual state of a Feed with the desired, and attempts -// to converge the two. It then updates the Status block of the Feed with -// its current state. -// If Reconcile returns a non-nil error, the request will be retried. -func (r *reconciler) Reconcile(request reconcile.Request) (reconcile.Result, error) { - //TODO use this to store the logger and set a deadline - ctx := context.TODO() - - feed := &feedsv1alpha1.Feed{} - err := r.client.Get(ctx, request.NamespacedName, feed) - - // The feed may have been deleted since it was added to the workqueue. If so - // there's nothing to be done. - if errors.IsNotFound(err) { - glog.Errorf("could not find Feed %v\n", request) - return reconcile.Result{}, nil - } - - // If the feed exists but could not be retrieved, then we should retry. - if err != nil { - glog.Errorf("could not fetch Feed %v for %+v\n", err, request) - return reconcile.Result{}, err - } - - // Now that we know the feed exists, we can reconcile it. An error returned - // here means the reconcile did not complete and the Feed should be requeued - // for another attempt. - // A successful reconcile does not necessarily mean the feed is in the desired - // state, it means no more can be done for now. In this case the feed will - // not be reconciled again until the resync period or a watched resource - // changes. - if err = r.reconcile(ctx, feed); err != nil { - glog.Errorf("error reconciling Feed: %v", err) - } - - // Since the reconcile is a sequence of steps, earlier steps may complete - // successfully while later steps fail. The Feed is updated on failure to - // preserve any useful status or metadata changes the non-failing steps made. - if updateErr := r.updateFeed(ctx, feed); updateErr != nil { - glog.Errorf("failed to update Feed: %v", updateErr) - // An error here means the feed should be reconciled again, regardless of - // whether the reconcile was successful or not. - return reconcile.Result{}, updateErr - } - return reconcile.Result{}, err -} - -// reconcile tries to converge the current state of the given Feed to the -// desired state. This function should not update the Feed; the calling method -// should do that. -func (r *reconciler) reconcile(ctx context.Context, feed *feedsv1alpha1.Feed) error { - feed.Status.InitializeConditions() - // Fetch the EventSource and EventType that is being asked for - // and if they don't exist update the status to reflect this back - // to the user. - eventSource, eventType, err := r.getFeedSource(ctx, feed) - if err != nil { - switch t := err.(type) { - case *EventSourceError: - glog.Errorf("eventsource can not be used as a target : %s", err) - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionDependenciesSatisfied, - Status: corev1.ConditionFalse, - Reason: t.Reason, - Message: t.Message, - }) - case *EventTypeError: - glog.Errorf("eventtype can not be used as a target : %s", err) - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionDependenciesSatisfied, - Status: corev1.ConditionFalse, - Reason: t.Reason, - Message: t.Message, - }) - default: - // This is unreachable unless getFeedSource is refactored. - // Assume this is a non-terminal state and return the error. - return fmt.Errorf("error getting feed source: %v", err) - } - // This is a terminal state, and we've noted it in the status, so return - // nil to signal that no further reconciling is required. - return nil - } - - // TODO: Set the FeedConditionDependenciesSatisfied to true here? Or, after - // job finishes? For now, the above conveys enough information to the user - // to make sure if they make a typo they will get that relayed back to them. - // IF we make it here, clear the condition in case they actually fixed the problem - // say, by installing an event provider. - feed.Status.RemoveCondition(feedsv1alpha1.FeedConditionDependenciesSatisfied) - - // Once we found the actual type, set the owner reference for it. - // TODO: Remove this and use finalizers in the EventTypes / EventSources - // to do this properly. - // TODO: Add issue link here. can't look up right now, no wifi - r.setEventTypeOwnerReference(ctx, feed) - - if feed.GetDeletionTimestamp() == nil { - err = r.reconcileStartJob(ctx, feed, eventSource, eventType) - if err != nil { - glog.Errorf("error reconciling start Job: %v", err) - } - } else { - err = r.reconcileStopJob(ctx, feed, eventSource, eventType) - if err != nil { - glog.Errorf("error reconciling stop Job: %v", err) - } - } - return nil -} - -// reconcileStartJob creates a start Job if one doesn't exist, checks the status -// of the start Job, and updates the Feed status accordingly. -func (r *reconciler) reconcileStartJob(ctx context.Context, feed *feedsv1alpha1.Feed, es *feedsv1alpha1.EventSource, et *feedsv1alpha1.EventType) error { - bc := feed.Status.GetCondition(feedsv1alpha1.FeedConditionReady) - switch bc.Status { - case corev1.ConditionUnknown: - - job := &batchv1.Job{} - jobName := resources.JobName(feed) - - if err := r.client.Get(ctx, client.ObjectKey{Namespace: feed.Namespace, Name: jobName}, job); err != nil { - if errors.IsNotFound(err) { - job, err = r.createJob(ctx, feed, es, et) - if err != nil { - return err - } - r.recorder.Eventf(feed, corev1.EventTypeNormal, "StartJobCreated", "Created start job %q", job.Name) - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionReady, - Status: corev1.ConditionUnknown, - Reason: "StartJob", - Message: "start job in progress", - }) - } - } - feed.AddFinalizer(finalizerName) - - if resources.IsJobComplete(job) { - r.recorder.Eventf(feed, corev1.EventTypeNormal, "StartJobCompleted", "Start job %q completed", job.Name) - if err := r.setFeedContext(ctx, feed, job); err != nil { - return err - } - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionReady, - Status: corev1.ConditionTrue, - Reason: "FeedSuccess", - Message: "start job succeeded", - }) - } else if resources.IsJobFailed(job) { - r.recorder.Eventf(feed, corev1.EventTypeWarning, "StartJobFailed", "Start job %q failed: %q", job.Name, resources.JobFailedMessage(job)) - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionReady, - Status: corev1.ConditionFalse, - Reason: "FeedFailed", - Message: fmt.Sprintf("Job failed with %s", resources.JobFailedMessage(job)), - }) - } - - case corev1.ConditionTrue: - //TODO delete job - } - return nil -} - -// reconcileStopJob deletes the start Job if it exists, creates a stop Job if -// one doesn't exist, checks the status of the stop Job, and updates the Feed -// status accordingly. -func (r *reconciler) reconcileStopJob(ctx context.Context, feed *feedsv1alpha1.Feed, es *feedsv1alpha1.EventSource, et *feedsv1alpha1.EventType) error { - if feed.HasFinalizer(finalizerName) { - - // check for an existing start Job - job := &batchv1.Job{} - jobName := resources.StartJobName(feed) - - err := r.client.Get(ctx, client.ObjectKey{Namespace: feed.Namespace, Name: jobName}, job) - if err != nil && !errors.IsNotFound(err) { - return err - } - if err == nil { - // Delete the existing job and return. When it's deleted, this Feed - // will be reconciled again. - glog.Infof("Found existing start job: %s/%s", job.Namespace, job.Name) - - // Need to delete pods first to workaround the client's lack of support - // for cascading deletes. TODO remove this when client support allows. - if err = r.deleteJobPods(ctx, job); err != nil { - return err - } - r.client.Delete(ctx, job) - glog.Infof("Deleted start job: %s/%s", job.Namespace, job.Name) - return nil - } - - jobName = resources.JobName(feed) - - if err := r.client.Get(ctx, client.ObjectKey{Namespace: feed.Namespace, Name: jobName}, job); err != nil { - if errors.IsNotFound(err) { - job, err = r.createJob(ctx, feed, es, et) - if err != nil { - return err - } - r.recorder.Eventf(feed, corev1.EventTypeNormal, "StopJobCreated", "Created stop job %q", job.Name) - //TODO check for event source not found and remove finalizer - - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionReady, - Status: corev1.ConditionUnknown, - Reason: "StopJob", - Message: "stop job in progress", - }) - } - } - - if resources.IsJobComplete(job) { - r.recorder.Eventf(feed, corev1.EventTypeNormal, "StopJobCompleted", "Stop job %q completed", job.Name) - feed.RemoveFinalizer(finalizerName) - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionReady, - Status: corev1.ConditionTrue, - Reason: "FeedSuccess", - Message: "stop job succeeded", - }) - } else if resources.IsJobFailed(job) { - r.recorder.Eventf(feed, corev1.EventTypeWarning, "StopJobFailed", "Stop job %q failed: %q", job.Name, resources.JobFailedMessage(job)) - glog.Warningf("Stop job %q failed, removing finalizer on feed %q anyway.", job.Name, feed.Name) - feed.RemoveFinalizer(finalizerName) - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionReady, - Status: corev1.ConditionFalse, - Reason: "FeedFailed", - Message: fmt.Sprintf("Job failed with %s", resources.JobFailedMessage(job)), - }) - } - } - return nil -} - -// updateFeed updates the given Feed's owner references, finalizers, and status -// to the given values. It skips the update if none of those values would change. -func (r *reconciler) updateFeed(ctx context.Context, u *feedsv1alpha1.Feed) error { - feed := &feedsv1alpha1.Feed{} - err := r.client.Get(ctx, client.ObjectKey{Namespace: u.Namespace, Name: u.Name}, feed) - if err != nil { - return err - } - - updated := false - if !equality.Semantic.DeepEqual(feed.OwnerReferences, u.OwnerReferences) { - feed.SetOwnerReferences(u.ObjectMeta.OwnerReferences) - updated = true - } - - if !equality.Semantic.DeepEqual(feed.Finalizers, u.Finalizers) { - feed.SetFinalizers(u.ObjectMeta.Finalizers) - updated = true - } - - if !equality.Semantic.DeepEqual(feed.Status, u.Status) { - feed.Status = u.Status - updated = true - } - - if updated == false { - return nil - } - // Until #38113 is merged, we must use Update instead of UpdateStatus to - // update the Status block of the Feed resource. UpdateStatus will not - // allow changes to the Spec of the resource, which is ideal for ensuring - // nothing other than resource status has been updated. - return r.client.Update(ctx, feed) -} - -// getEventTypeName returns the name of the Feed's referenced EventType or -// ClusterEventType. -func (r *reconciler) getEventTypeName(feed *feedsv1alpha1.Feed) string { - if len(feed.Spec.Trigger.EventType) > 0 { - return feed.Spec.Trigger.EventType - } else if len(feed.Spec.Trigger.ClusterEventType) > 0 { - return feed.Spec.Trigger.ClusterEventType - } - return "" -} - -// setEventTypeOwnerReference makes the given Feed's referenced ClusterEventType a non-controlling -// owner of the Feed. -func (r *reconciler) setEventTypeOwnerReference(ctx context.Context, feed *feedsv1alpha1.Feed) error { - // Namespaced EventTypes use a finalizer and do not need an Owners reference. - if len(feed.Spec.Trigger.ClusterEventType) > 0 { - return r.setClusterEventTypeOwnerReference(ctx, feed) - } - return nil -} - -// setEventTypeOwnerReference makes the given Feed's referenced ClusterEventType -// a non-controlling owner of the Feed. -func (r *reconciler) setClusterEventTypeOwnerReference(ctx context.Context, feed *feedsv1alpha1.Feed) error { - et := &feedsv1alpha1.ClusterEventType{} - if err := r.client.Get(ctx, client.ObjectKey{Name: feed.Spec.Trigger.ClusterEventType}, et); err != nil { - if errors.IsNotFound(err) { - glog.Errorf("Feed ClusterEventType not found, will not set finalizer") - return nil - } - return err - } - - blockOwnerDeletion := true - isController := false - ref := metav1.NewControllerRef(et, feedsv1alpha1.SchemeGroupVersion.WithKind("ClusterEventType")) - ref.BlockOwnerDeletion = &blockOwnerDeletion - ref.Controller = &isController - - feed.SetOwnerReference(ref) - return nil -} - -// resolveTrigger extracts the trigger from the Feed, reifies the parameters, -// and turns it all into an EventTrigger. -func (r *reconciler) resolveTrigger(ctx context.Context, feed *feedsv1alpha1.Feed) (sources.EventTrigger, error) { - trigger := feed.Spec.Trigger - resolved := sources.EventTrigger{ - Resource: trigger.Resource, - EventType: r.getEventTypeName(feed), - Parameters: make(map[string]interface{}), - } - - if trigger.Parameters != nil && trigger.Parameters.Raw != nil && len(trigger.Parameters.Raw) > 0 { - p := make(map[string]interface{}) - if err := yaml.Unmarshal(trigger.Parameters.Raw, &p); err != nil { - return resolved, err - } - for k, v := range p { - resolved.Parameters[k] = v - } - } - if trigger.ParametersFrom != nil { - glog.Infof("fetching from source %+v", trigger.ParametersFrom) - for _, p := range trigger.ParametersFrom { - pfs, err := r.fetchParametersFromSource(ctx, feed.Namespace, &p) - if err != nil { - return resolved, err - } - for k, v := range pfs { - resolved.Parameters[k] = v - } - } - } - return resolved, nil -} - -// fetchParametersFromSource gets the secret value referenced by the given -// ParametersFrom and returns it as a string-keyed map. -func (r *reconciler) fetchParametersFromSource(ctx context.Context, namespace string, parametersFrom *feedsv1alpha1.ParametersFromSource) (map[string]interface{}, error) { - var params map[string]interface{} - if parametersFrom.SecretKeyRef != nil { - glog.Infof("fetching secret %+v", parametersFrom.SecretKeyRef) - data, err := r.fetchSecretKeyValue(ctx, namespace, parametersFrom.SecretKeyRef) - if err != nil { - return nil, err - } - - if err := json.Unmarshal(data, ¶ms); err != nil { - return nil, fmt.Errorf("failed to unmarshal parameters as JSON object: %v", err) - } - } - return params, nil -} - -// fetchSecretKeyValue gets the Secret referenced and returns the data in the -// referenced key. -func (r *reconciler) fetchSecretKeyValue(ctx context.Context, namespace string, secretKeyRef *feedsv1alpha1.SecretKeyReference) ([]byte, error) { - secret := &corev1.Secret{} - err := r.client.Get(ctx, client.ObjectKey{Namespace: namespace, Name: secretKeyRef.Name}, secret) - if err != nil { - return nil, err - } - return secret.Data[secretKeyRef.Key], nil -} - -// createJob creates a Job for the given Feed based on its current state, -// returning the created Job. -func (r *reconciler) createJob(ctx context.Context, feed *feedsv1alpha1.Feed, es *feedsv1alpha1.EventSource, et *feedsv1alpha1.EventType) (*batchv1.Job, error) { - trigger, err := r.resolveTrigger(ctx, feed) - if err != nil { - return nil, err - } - - job, err := resources.MakeJob(feed, es, trigger, feed.Spec.Action.DNSName) - if err != nil { - return nil, err - } - - if err := r.client.Create(ctx, job); err != nil { - return nil, err - } - return job, nil -} - -// setFeedContext sets the Feed's context from the context emitted by the given -// Job. -func (r *reconciler) setFeedContext(ctx context.Context, feed *feedsv1alpha1.Feed, job *batchv1.Job) error { - feedContext, err := r.getJobContext(ctx, job) - if err != nil { - return err - } - - marshalledFeedContext, err := json.Marshal(&feedContext.Context) - if err != nil { - return err - } - feed.Status.FeedContext = &runtime.RawExtension{ - Raw: marshalledFeedContext, - } - - return nil -} - -// getJobContext returns the FeedContext emitted by the first successful pod -// owned by this job. The feed context is extracted from the termination -// message of the first container in the pod. -func (r *reconciler) getJobContext(ctx context.Context, job *batchv1.Job) (*sources.FeedContext, error) { - pods, err := r.getJobPods(ctx, job) - if err != nil { - return nil, err - } - - for _, p := range pods { - if p.Status.Phase == corev1.PodSucceeded { - glog.Infof("Pod succeeded: %s", p.Name) - if msg := resources.GetFirstTerminationMessage(&p); msg != "" { - decodedContext, _ := base64.StdEncoding.DecodeString(msg) - glog.Infof("decoded to %q", decodedContext) - var ret sources.FeedContext - err = json.Unmarshal(decodedContext, &ret) - if err != nil { - glog.Errorf("failed to unmarshal context: %s", err) - return nil, err - } - return &ret, nil - } - } - } - return &sources.FeedContext{}, nil -} - -// getJobPods returns the array of Pods owned by the given Job. -func (r *reconciler) getJobPods(ctx context.Context, job *batchv1.Job) ([]corev1.Pod, error) { - podList := &corev1.PodList{} - listOptions := client. - InNamespace(job.Namespace). - MatchingLabels(job.Spec.Selector.MatchLabels) - - //TODO this is here because the fake client needs it. Remove this when it's - // no longer needed. - listOptions.Raw = &metav1.ListOptions{ - TypeMeta: metav1.TypeMeta{ - APIVersion: corev1.SchemeGroupVersion.String(), - Kind: "Pod", - }, - } - - if err := r.client.List(ctx, listOptions, podList); err != nil { - return nil, err - } - - return podList.Items, nil -} - -func (r *reconciler) deleteJobPods(ctx context.Context, job *batchv1.Job) error { - pods, err := r.getJobPods(ctx, job) - if err != nil { - return err - } - - for _, pod := range pods { - if err := r.client.Delete(ctx, &pod); err != nil { - return err - } - glog.Infof("Deleted start job pod: %s/%s", pod.Namespace, pod.Name) - } - return nil -} - -// getFeedSource gets the EventSource and EventType that the trigger is targeting and -// returns them. If either the source or type is not found or is in the deleting state -// returns an error of the proper type. -func (r *reconciler) getFeedSource(ctx context.Context, feed *feedsv1alpha1.Feed) (*feedsv1alpha1.EventSource, *feedsv1alpha1.EventType, error) { - es := &feedsv1alpha1.EventSource{} - if err := r.client.Get(ctx, client.ObjectKey{Namespace: feed.Namespace, Name: feed.Spec.Trigger.Service}, es); err != nil { - if errors.IsNotFound(err) { - msg := fmt.Sprintf("EventSource %s/%s does not exist", feed.Namespace, feed.Spec.Trigger.Service) - glog.Info(msg) - return nil, nil, &EventSourceError{StatusError{EventSourceDoesNotExist, msg}} - } - return nil, nil, err - } - - if feed.GetDeletionTimestamp() == nil && es.GetDeletionTimestamp() != nil { - // EventSource is being deleted so don't allow non-deleting Feeds to use it. - msg := fmt.Sprintf("EventSource %s/%s is being deleted", feed.Namespace, feed.Spec.Trigger.Service) - glog.Info(msg) - return nil, nil, &EventSourceError{StatusError{EventSourceDeleting, msg}} - } - - et := &feedsv1alpha1.EventType{} - if err := r.client.Get(ctx, client.ObjectKey{Namespace: feed.Namespace, Name: feed.Spec.Trigger.EventType}, et); err != nil { - if errors.IsNotFound(err) { - msg := fmt.Sprintf("EventType %s/%s does not exist", feed.Namespace, feed.Spec.Trigger.EventType) - glog.Info(msg) - return nil, nil, &EventTypeError{StatusError{EventTypeDoesNotExist, msg}} - } - return nil, nil, err - } - - if feed.GetDeletionTimestamp() == nil && et.GetDeletionTimestamp() != nil { - // EventType is being deleted so don't allow non-deleting Feeds to use it. - msg := fmt.Sprintf("EventType %s/%s is being deleted", feed.Namespace, feed.Spec.Trigger.EventType) - glog.Info(msg) - return nil, nil, &EventTypeError{StatusError{EventTypeDeleting, msg}} - } - return es, et, nil -} diff --git a/pkg/controller/feed/reconcile_test.go b/pkg/controller/feed/reconcile_test.go deleted file mode 100644 index 0ced4c73d86..00000000000 --- a/pkg/controller/feed/reconcile_test.go +++ /dev/null @@ -1,903 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Veroute.on 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 feed - -import ( - "context" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - "testing" - - feedsv1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - "github.com/knative/eventing/pkg/controller/feed/resources" - controllertesting "github.com/knative/eventing/pkg/controller/testing" - "github.com/knative/eventing/pkg/sources" - batchv1 "k8s.io/api/batch/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/tools/record" -) - -/* -TODO -- initial: feed with job deadline exceeded - reconciled: feed failure, job exists, finalizer -*/ - -var ( - trueVal = true - // deletionTime is used when objects are marked as deleted. Rfc3339Copy() - // truncates to seconds to match the loss of precision during serialization. - deletionTime = metav1.Now().Rfc3339Copy() -) - -const ( - targetDNS = "myservice.mynamespace.svc.cluster.local" - - getError = "test induced error getting" - createError = "test induced error creating" - - jobFailedReason = "test induced job failure reason" - jobFailedMessage = "test induced job failure message" -) - -func init() { - // Add types to scheme - feedsv1alpha1.AddToScheme(scheme.Scheme) -} - -func TestAllCases(t *testing.T) { - testCases := []controllertesting.TestCase{ - { - Name: "Feed not found", - // This should return a successful reconcile result immediately. - WantErr: false, - WantResult: reconcile.Result{}, - }, - { - Name: "Internal error getting Feed", - WantErrMsg: getError, - Mocks: controllertesting.Mocks{ - MockGets: []controllertesting.MockGet{ - func(_ client.Client, _ context.Context, _ client.ObjectKey, _ runtime.Object) (controllertesting.MockHandled, error) { - return controllertesting.Handled, errors.New(getError) - }, - }, - }, - }, - { - Name: "new feed: adds status, finalizer, creates job", - InitialState: []runtime.Object{ - getEventSource(), - getEventType(), - getNewFeed(), - }, - WantPresent: []runtime.Object{ - getStartInProgressFeed(), - getNewStartJob(), - //TODO job created event - }, - }, { - Name: "new feed: adds status, finalizer, create job fails", - InitialState: []runtime.Object{ - getEventSource(), - getEventType(), - getNewFeed(), - }, - WantPresent: []runtime.Object{ - getReadyUnknownFeed(), - //TODO job created event - }, - Mocks: controllertesting.Mocks{ - MockCreates: []controllertesting.MockCreate{ - func(_ client.Client, _ context.Context, obj runtime.Object) (controllertesting.MockHandled, error) { - // Return an error when creating a Job. - if _, ok := obj.(*batchv1.Job); ok { - return controllertesting.Handled, errors.New(createError) - } - return controllertesting.Unhandled, nil - }, - }, - }, - }, - { - Name: "new feed with secret ref: secret gets to job", - InitialState: []runtime.Object{ - getEventSource(), - getEventType(), - getFeedSecret(), - getNewSecretFeed(), - }, - WantPresent: []runtime.Object{ - getSecretStartInProgressFeed(), - getNewSecretStartJob(), - //TODO job created event - }, - }, - { - Name: "in progress feed with existing job: both unchanged", - InitialState: []runtime.Object{ - getEventSource(), - getEventType(), - getStartInProgressFeed(), - getNewStartJob(), - }, - WantPresent: []runtime.Object{ - getStartInProgressFeed(), - getNewStartJob(), - }, - }, - { - Name: "in progress feed with completed job: updated status, context, job exists", - InitialState: []runtime.Object{ - getEventSource(), - getEventType(), - getStartInProgressFeed(), - getCompletedStartFeedJob(), - getCompletedStartFeedJobPod(), - }, - WantPresent: []runtime.Object{ - getStartedFeed(), - getCompletedStartFeedJob(), - //TODO job completed event - }, - }, - { - Name: "in progress feed with failed start job: updated status, job exists", - InitialState: []runtime.Object{ - getEventSource(), - getEventType(), - getStartInProgressFeed(), - getFailedStartFeedJob(), - getCompletedStartFeedJobPod(), - }, - WantPresent: []runtime.Object{ - getStartFailedFeed(), - getFailedStartFeedJob(), - //TODO job failed event - }, - }, - { - Name: "non-existing event type: updated status", - InitialState: []runtime.Object{ - getNewFeed(), - getEventSource(), - }, - WantPresent: []runtime.Object{ - getEventTypeMissing(), - }, - }, - { - Name: "Internal Error getting EventSource", - InitialState: []runtime.Object{ - getNewFeed(), - }, - WantPresent: []runtime.Object{ - getReadyUnknownFeed(), - }, - WantErrMsg: "error getting feed source: " + getError, - Mocks: controllertesting.Mocks{ - MockGets: []controllertesting.MockGet{ - func(_ client.Client, _ context.Context, _ client.ObjectKey, obj runtime.Object) (controllertesting.MockHandled, error) { - if _, ok := obj.(*feedsv1alpha1.EventSource); ok { - return controllertesting.Handled, errors.New(getError) - } - return controllertesting.Unhandled, nil - }, - }, - }, - }, - { - Name: "deleting event type: updated status", - InitialState: []runtime.Object{ - getNewFeed(), - getEventSource(), - getDeletingEventType(), - }, - WantPresent: []runtime.Object{ - getEventTypeDeleting(), - }, - }, - { - Name: "non-existing event source: updated status", - InitialState: []runtime.Object{ - getNewFeed(), - }, - WantPresent: []runtime.Object{ - getEventSourceMissing(), - }, - }, - { - Name: "deleting event source: updated status", - InitialState: []runtime.Object{ - getNewFeed(), - getDeletingEventSource(), - }, - WantPresent: []runtime.Object{ - getEventSourceDeleting(), - }, - }, - { - Name: "deleting Feed with deleting EventSource", - InitialState: []runtime.Object{ - getDeletedStartedFeed(), - getDeletingEventSource(), - getEventType(), - }, - WantPresent: []runtime.Object{ - getDeletedStopInProgressFeed(), - }, - }, - { - Name: "deleting Feed with deleting EventType", - InitialState: []runtime.Object{ - getDeletedStartedFeed(), - getEventSource(), - getDeletingEventType(), - }, - WantPresent: []runtime.Object{ - getDeletedStopInProgressFeed(), - }, - }, - { - Name: "in progress feed with failed stop job: finalizer removed", - InitialState: []runtime.Object{ - getEventSource(), - getEventType(), - getDeletedStopInProgressFeed(), - getFailedStopJob(), - }, - WantPresent: []runtime.Object{ - getFinalizerRemovedStopJobFailedFeed(), - //TODO job failed event - }, - }, - { - Name: "failed because missing event source, now present", - InitialState: []runtime.Object{ - getFeedFailingWithMissingEventSource(), - getEventSource(), - getEventType(), - }, - WantPresent: []runtime.Object{ - getStartInProgressFeed(), - getNewStartJob(), - }, - }, - { - Name: "Deleted feed with finalizer, previously completed, feed job exists: feed job deleted", - InitialState: []runtime.Object{ - getEventSource(), - getEventType(), - getDeletedStartedFeed(), - getCompletedStartFeedJob(), - }, - WantPresent: []runtime.Object{ - getDeletedStartedFeed(), - }, - WantAbsent: []runtime.Object{ - getCompletedStartFeedJob(), - }, - }, - { - Name: "Deleted feed with finalizer, previously completed, feed job missing: stop feed job created, status updated", - InitialState: []runtime.Object{ - getEventSource(), - getEventType(), - getDeletedStartedFeed(), - }, - WantPresent: []runtime.Object{ - getDeletedStopInProgressFeed(), - getNewStopJob(), - //TODO job created event - }, - }, - { - Name: "Deleted in-progress feed with finalizer, stop feed job exists: unchanged", - InitialState: []runtime.Object{ - getEventSource(), - getEventType(), - getDeletedStopInProgressFeed(), - getInProgressStopJob(), - }, - WantPresent: []runtime.Object{ - getDeletedStopInProgressFeed(), - getInProgressStopJob(), - }, - }, - { - Name: "Deleted feed with completed stop feed job: no finalizers, update status", - InitialState: []runtime.Object{ - getEventSource(), - getEventType(), - getDeletedStopInProgressFeed(), - getCompletedStopJob(), - }, - WantPresent: []runtime.Object{ - getDeletedStoppedFeed(), - //TODO job completed event - }, - }, - } - reconcileKey := "test/test-feed" - - recorder := record.NewBroadcaster().NewRecorder(scheme.Scheme, corev1.EventSource{Component: controllerAgentName}) - - for _, tc := range testCases { - c := tc.GetClient() - r := &reconciler{ - client: c, - recorder: recorder, - } - tc.ReconcileKey = reconcileKey - t.Run(tc.Name, tc.Runner(t, r, c)) - } -} - -func getEventSource() *feedsv1alpha1.EventSource { - return &feedsv1alpha1.EventSource{ - ObjectMeta: om("test", "test-es"), - Spec: feedsv1alpha1.EventSourceSpec{ - CommonEventSourceSpec: feedsv1alpha1.CommonEventSourceSpec{ - Source: "github", - Image: "example.com/test-es-feeder", - Parameters: nil, - }, - }, - } -} - -func getDeletingEventSource() *feedsv1alpha1.EventSource { - return &feedsv1alpha1.EventSource{ - ObjectMeta: omDeleting("test", "test-es"), - Spec: feedsv1alpha1.EventSourceSpec{ - CommonEventSourceSpec: feedsv1alpha1.CommonEventSourceSpec{ - Source: "github", - Image: "example.com/test-es-feeder", - Parameters: nil, - }, - }, - } -} - -func getEventType() *feedsv1alpha1.EventType { - return &feedsv1alpha1.EventType{ - ObjectMeta: om("test", "test-et"), - Spec: feedsv1alpha1.EventTypeSpec{ - EventSource: getEventSource().Name, - }, - } -} - -func getDeletingEventType() *feedsv1alpha1.EventType { - return &feedsv1alpha1.EventType{ - ObjectMeta: omDeleting("test", "test-et"), - Spec: feedsv1alpha1.EventTypeSpec{ - EventSource: getEventSource().Name, - }, - } -} - -func getFeedContext() *sources.FeedContext { - return &sources.FeedContext{ - Context: map[string]interface{}{ - "foo": "bar", - }, - } -} - -func getNewFeed() *feedsv1alpha1.Feed { - return &feedsv1alpha1.Feed{ - TypeMeta: feedType(), - ObjectMeta: om("test", "test-feed"), - Spec: feedsv1alpha1.FeedSpec{ - Action: feedsv1alpha1.FeedAction{ - DNSName: targetDNS, - }, - Trigger: feedsv1alpha1.EventTrigger{ - EventType: getEventType().Name, - Resource: "", - Service: "", - Parameters: nil, - ParametersFrom: nil, - }, - }, - } -} - -func getFeedSecret() *corev1.Secret { - secretMap := map[string]interface{}{"foo": "bar"} - data, err := json.Marshal(secretMap) - if err != nil { - panic(err) - } - return &corev1.Secret{ - ObjectMeta: om("test", "feed-secret"), - Data: map[string][]byte{ - "test-secret-key": data, - }, - } - -} - -func getNewSecretFeed() *feedsv1alpha1.Feed { - feed := getNewFeed() - feed.Spec.Trigger.ParametersFrom = []feedsv1alpha1.ParametersFromSource{{ - SecretKeyRef: &feedsv1alpha1.SecretKeyReference{ - Name: getFeedSecret().Name, - Key: "test-secret-key", - }, - }} - return feed -} - -func getFeedFailingWithMissingEventSource() *feedsv1alpha1.Feed { - feed := getNewFeed() - feed.Status.InitializeConditions() - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionDependenciesSatisfied, - Status: corev1.ConditionFalse, - Reason: "TestGenerated", - Message: "test generated", - }) - return feed -} - -func getReadyUnknownFeed() *feedsv1alpha1.Feed { - feed := getNewFeed() - - feed.Status.InitializeConditions() - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionReady, - Status: corev1.ConditionUnknown, - }) - - return feed -} - -func getNewFeedWithFinalizer() *feedsv1alpha1.Feed { - feed := getNewFeed() - feed.AddFinalizer(finalizerName) - return feed -} - -func getStartInProgressFeed() *feedsv1alpha1.Feed { - feed := getNewFeedWithFinalizer() - - feed.Status.InitializeConditions() - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionReady, - Status: corev1.ConditionUnknown, - Reason: "StartJob", - Message: "start job in progress", - }) - - return feed -} - -func getSecretStartInProgressFeed() *feedsv1alpha1.Feed { - feed := getStartInProgressFeed() - feed.Spec.Trigger.ParametersFrom = []feedsv1alpha1.ParametersFromSource{{ - SecretKeyRef: &feedsv1alpha1.SecretKeyReference{ - Name: getFeedSecret().Name, - Key: "test-secret-key", - }, - }} - return feed -} - -func getStartedFeed() *feedsv1alpha1.Feed { - feed := getStartInProgressFeed() - marshalledContext, err := json.Marshal(getFeedContext().Context) - if err != nil { - panic(err) - } - feed.Status.FeedContext = &runtime.RawExtension{ - Raw: marshalledContext, - } - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionReady, - Status: corev1.ConditionTrue, - Reason: "FeedSuccess", - Message: "start job succeeded", - }) - return feed -} - -func getStartFailedFeed() *feedsv1alpha1.Feed { - feed := getStartInProgressFeed() - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionReady, - Status: corev1.ConditionFalse, - Reason: "FeedFailed", - Message: "Job failed with [] ", - }) - return feed -} - -func getDeletedStartedFeed() *feedsv1alpha1.Feed { - feed := getStartedFeed() - feed.SetDeletionTimestamp(&deletionTime) - return feed -} - -func getDeletedStopInProgressFeed() *feedsv1alpha1.Feed { - feed := getDeletedStartedFeed() - - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionReady, - Status: corev1.ConditionUnknown, - Reason: "StopJob", - Message: "stop job in progress", - }) - return feed -} - -func getDeletedStoppedFeed() *feedsv1alpha1.Feed { - feed := getDeletedStopInProgressFeed() - feed.RemoveFinalizer(finalizerName) - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionReady, - Status: corev1.ConditionTrue, - Reason: "FeedSuccess", - Message: "stop job succeeded", - }) - return feed -} - -func getFinalizerRemovedStopJobFailedFeed() *feedsv1alpha1.Feed { - feed := getDeletedStopInProgressFeed() - feed.RemoveFinalizer(finalizerName) - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionReady, - Status: corev1.ConditionFalse, - Reason: "FeedFailed", - Message: fmt.Sprintf("Job failed with [%s] %s", jobFailedReason, jobFailedMessage), - }) - return feed -} - -func getNewStartJob() *batchv1.Job { - jobName := resources.StartJobName(getNewFeed()) - return &batchv1.Job{ - TypeMeta: jobType(), - ObjectMeta: metav1.ObjectMeta{ - Namespace: "test", - Name: jobName, - Labels: map[string]string{"app": "feedpod"}, - OwnerReferences: []metav1.OwnerReference{{ - APIVersion: feedsv1alpha1.SchemeGroupVersion.String(), - Kind: "Feed", - Name: getNewFeed().Name, - Controller: &trueVal, - BlockOwnerDeletion: &trueVal, - }}, - }, - Spec: batchv1.JobSpec{ - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{"sidecar.istio.io/inject": "false"}, - }, - Spec: corev1.PodSpec{ - Containers: []corev1.Container{{ - Name: "feedlet", - Image: "example.com/test-es-feeder", - Env: []corev1.EnvVar{{ - Name: string(resources.EnvVarOperation), - Value: string(resources.OperationStartFeed), - }, { - Name: string(resources.EnvVarTarget), - Value: targetDNS, - }, { - Name: string(resources.EnvVarTrigger), - Value: base64.StdEncoding.EncodeToString(bytesOrDie(json.Marshal( - sources.EventTrigger{ - EventType: "test-et", - Parameters: map[string]interface{}{}, - }, - ))), - }, { - Name: string(resources.EnvVarContext), - Value: base64.StdEncoding.EncodeToString(bytesOrDie(json.Marshal( - sources.FeedContext{}, - ))), - }, { - Name: string(resources.EnvVarEventSourceParameters), - Value: "", - }, { - Name: string(resources.EnvVarNamespace), - ValueFrom: &corev1.EnvVarSource{ - FieldRef: &corev1.ObjectFieldSelector{ - FieldPath: "metadata.namespace", - }, - }, - }, { - Name: string(resources.EnvVarServiceAccount), - ValueFrom: &corev1.EnvVarSource{ - FieldRef: &corev1.ObjectFieldSelector{ - FieldPath: "spec.serviceAccountName", - }, - }, - }}, - ImagePullPolicy: corev1.PullIfNotPresent, - }}, - RestartPolicy: corev1.RestartPolicyNever, - }, - }, - BackoffLimit: &resources.DefaultBackoffLimit, - ActiveDeadlineSeconds: &resources.DefaultActiveDeadlineSeconds, - }, - Status: batchv1.JobStatus{}, - } -} - -func getNewSecretStartJob() *batchv1.Job { - job := getNewStartJob() - envVars := job.Spec.Template.Spec.Containers[0].Env - var newEnvVars []corev1.EnvVar - for _, envVar := range envVars { - if envVar.Name == string(resources.EnvVarTrigger) { - newEnvVars = append(newEnvVars, corev1.EnvVar{ - Name: string(resources.EnvVarTrigger), - Value: base64.StdEncoding.EncodeToString(bytesOrDie(json.Marshal( - sources.EventTrigger{ - EventType: "test-et", - Parameters: map[string]interface{}{"foo": "bar"}, - }, - ))), - }) - } else { - newEnvVars = append(newEnvVars, envVar) - } - } - job.Spec.Template.Spec.Containers[0].Env = newEnvVars - return job -} - -func getInProgressStartFeedJob() *batchv1.Job { - job := getNewStartJob() - // This is normally set by a webhook. Set it here - // to simulate. TODO use a reactor when that's - // supported. - job.Spec.Selector = &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "job": job.Name, - }, - } - return job -} - -func getCompletedStartFeedJob() *batchv1.Job { - job := getInProgressStartFeedJob() - job.Status = batchv1.JobStatus{ - Conditions: []batchv1.JobCondition{{ - Type: batchv1.JobComplete, - Status: corev1.ConditionTrue, - }}, - } - return job -} - -func getFailedStartFeedJob() *batchv1.Job { - job := getInProgressStartFeedJob() - job.Status = batchv1.JobStatus{ - Conditions: []batchv1.JobCondition{{ - Type: batchv1.JobFailed, - Status: corev1.ConditionTrue, - }}, - } - return job -} - -func getCompletedStartFeedJobPod() *corev1.Pod { - job := getCompletedStartFeedJob() - outputContext, err := json.Marshal(getFeedContext()) - if err != nil { - panic(err) - } - - return &corev1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "test", - Name: job.Name, - Labels: map[string]string{"job": job.Name}, - }, - Status: corev1.PodStatus{ - Phase: corev1.PodSucceeded, - ContainerStatuses: []corev1.ContainerStatus{{ - State: corev1.ContainerState{ - Terminated: &corev1.ContainerStateTerminated{ - Message: base64.StdEncoding.EncodeToString(outputContext), - }, - }, - }}, - }, - } -} - -func getNewStopJob() *batchv1.Job { - job := getNewStartJob() - job.Name = resources.StopJobName(getDeletedStartedFeed()) - - job.Spec.Template.Spec.Containers[0].Env = []corev1.EnvVar{{ - Name: string(resources.EnvVarOperation), - Value: string(resources.OperationStopFeed), - }, { - Name: string(resources.EnvVarTarget), - Value: targetDNS, - }, { - Name: string(resources.EnvVarTrigger), - Value: base64.StdEncoding.EncodeToString(bytesOrDie(json.Marshal( - sources.EventTrigger{ - EventType: "test-et", - Parameters: map[string]interface{}{}, - }, - ))), - }, { - Name: string(resources.EnvVarContext), - Value: base64.StdEncoding.EncodeToString(bytesOrDie(json.Marshal(getFeedContext()))), - }, { - Name: string(resources.EnvVarEventSourceParameters), - Value: "", - }, { - Name: string(resources.EnvVarNamespace), - ValueFrom: &corev1.EnvVarSource{ - FieldRef: &corev1.ObjectFieldSelector{ - FieldPath: "metadata.namespace", - }, - }, - }, { - Name: string(resources.EnvVarServiceAccount), - ValueFrom: &corev1.EnvVarSource{ - FieldRef: &corev1.ObjectFieldSelector{ - FieldPath: "spec.serviceAccountName", - }, - }, - }} - return job -} - -func getInProgressStopJob() *batchv1.Job { - job := getNewStopJob() - // This is normally set by a webhook. Set it here - // to simulate. TODO use a reactor when that's - // supported. - job.Spec.Selector = &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "job": job.Name, - }, - } - return job -} - -func getCompletedStopJob() *batchv1.Job { - job := getInProgressStopJob() - job.Status = batchv1.JobStatus{ - Conditions: []batchv1.JobCondition{{ - Type: batchv1.JobComplete, - Status: corev1.ConditionTrue, - }}, - } - return job -} - -func getFailedStopJob() *batchv1.Job { - job := getInProgressStopJob() - job.Status.Conditions = append(job.Status.Conditions, batchv1.JobCondition{ - Type: batchv1.JobFailed, - Status: corev1.ConditionTrue, - Reason: jobFailedReason, - Message: jobFailedMessage, - }) - return job -} - -func getEventTypeMissing() *feedsv1alpha1.Feed { - feed := getNewFeed() - feed.Status.InitializeConditions() - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionDependenciesSatisfied, - Status: corev1.ConditionFalse, - Reason: EventTypeDoesNotExist, - Message: "EventType test/test-et does not exist", - }) - - return feed -} - -func getEventTypeDeleting() *feedsv1alpha1.Feed { - feed := getNewFeed() - feed.Status.InitializeConditions() - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionDependenciesSatisfied, - Status: corev1.ConditionFalse, - Reason: EventTypeDeleting, - Message: "EventType test/test-et is being deleted", - }) - - return feed -} - -func getEventSourceMissing() *feedsv1alpha1.Feed { - feed := getNewFeed() - feed.Status.InitializeConditions() - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionDependenciesSatisfied, - Status: corev1.ConditionFalse, - Reason: EventSourceDoesNotExist, - Message: "EventSource test/ does not exist", - }) - - return feed -} - -func getEventSourceDeleting() *feedsv1alpha1.Feed { - feed := getNewFeed() - feed.Status.InitializeConditions() - feed.Status.SetCondition(&feedsv1alpha1.FeedCondition{ - Type: feedsv1alpha1.FeedConditionDependenciesSatisfied, - Status: corev1.ConditionFalse, - Reason: EventSourceDeleting, - Message: "EventSource test/ is being deleted", - }) - - return feed -} - -func om(namespace, name string) metav1.ObjectMeta { - return metav1.ObjectMeta{ - Namespace: namespace, - Name: name, - SelfLink: fmt.Sprintf("/apis/eventing/v1alpha1/namespaces/%s/object/%s", namespace, name), - } -} - -func omDeleting(namespace, name string) metav1.ObjectMeta { - return metav1.ObjectMeta{ - Namespace: namespace, - Name: name, - SelfLink: fmt.Sprintf("/apis/eventing/v1alpha1/namespaces/%s/object/%s", namespace, name), - DeletionTimestamp: &deletionTime, - } -} - -func bytesOrDie(v []byte, err error) []byte { - if err != nil { - panic(err) - } - return v -} - -func feedType() metav1.TypeMeta { - return metav1.TypeMeta{ - APIVersion: feedsv1alpha1.SchemeGroupVersion.String(), - Kind: "Feed", - } -} - -func jobType() metav1.TypeMeta { - return metav1.TypeMeta{ - APIVersion: batchv1.SchemeGroupVersion.String(), - Kind: "Job", - } -} diff --git a/pkg/controller/feed/resources/job.go b/pkg/controller/feed/resources/job.go deleted file mode 100644 index ec127956cbd..00000000000 --- a/pkg/controller/feed/resources/job.go +++ /dev/null @@ -1,254 +0,0 @@ -/* -Copyright 2018 The Knative 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 resources - -import ( - "encoding/base64" - "encoding/json" - - feedsv1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - "github.com/knative/eventing/pkg/sources" - - "fmt" - - batchv1 "k8s.io/api/batch/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// Operation specifies the operation for the feed container to perform. -type Operation string - -const ( - // OperationStartFeed specifies a feed should be started - OperationStartFeed Operation = "START" - // OperationStopFeed specifies a feed should be stopped - OperationStopFeed = "STOP" - // istio side car injection annotation - sidecarIstioInjectAnnotation = "sidecar.istio.io/inject" -) - -// EnvVar specifies the names of the environment variables passed to the -// feed container. -type EnvVar string - -const ( - // EnvVarOperation is the Env variable that gets set to requested Operation - EnvVarOperation EnvVar = "FEED_OPERATION" - // EnvVarTrigger is the Env variable that gets set to serialized trigger configuration - EnvVarTrigger = "FEED_TRIGGER" - // EnvVarTarget is the Env variable that gets set to target of the feed operation - EnvVarTarget = "FEED_TARGET" - // EnvVarContext is the Env variable that gets set to serialized FeedContext if stopping - EnvVarContext = "FEED_CONTEXT" - // EnvVarEventSourceParameters is the Env variable that gets set to serialized EventSourceSpec - EnvVarEventSourceParameters = "EVENT_SOURCE_PARAMETERS" - // EnvVarNamespace is the Env variable that gets set to namespace of the container doing - // the Feed (aka, namespace of the feed). Uses downward api - EnvVarNamespace = "FEED_NAMESPACE" - // EnvVarServiceAccount is the Env variable that gets set to serviceaccount of the - // container doing the feed. Uses downward api - //TODO is this useful? Wouldn't this already be the implicit service Account - // for the container? - EnvVarServiceAccount = "FEED_SERVICE_ACCOUNT" -) - -var ( - // DefaultBackoffLimit is the default BackoffLimit value for feedlet jobs. - // No more than this number of retry pods will be created before the job is - // considered failed. The total number of tries is this number + 1. - DefaultBackoffLimit int32 = 2 - // DefaultActiveDeadlineSeconds is the default ActiveDeadlineSeconds value for - // feedlet jobs. The job cannot be active for more than this number of - // seconds before it is considered failed. - DefaultActiveDeadlineSeconds int64 = 30 -) - -// MakeJob creates a Job to start or stop a Feed. -func MakeJob(feed *feedsv1alpha1.Feed, source *feedsv1alpha1.EventSource, trigger sources.EventTrigger, target string) (*batchv1.Job, error) { - labels := map[string]string{ - "app": "feedpod", - } - - podTemplate, err := makePodTemplate(feed, source, trigger, target) - if err != nil { - return nil, err - } - - return &batchv1.Job{ - ObjectMeta: metav1.ObjectMeta{ - Name: JobName(feed), - Namespace: feed.Namespace, - Labels: labels, - OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(feed, feedsv1alpha1.SchemeGroupVersion.WithKind("Feed"))}, - }, - Spec: batchv1.JobSpec{ - Template: *podTemplate, - BackoffLimit: &DefaultBackoffLimit, - ActiveDeadlineSeconds: &DefaultActiveDeadlineSeconds, - }, - }, nil -} - -// IsJobComplete returns true if the Job has completed successfully, or false if -// the Job is in progress or failed. -func IsJobComplete(job *batchv1.Job) bool { - for _, c := range job.Status.Conditions { - if c.Type == batchv1.JobComplete && c.Status == corev1.ConditionTrue { - return true - } - } - return false -} - -// IsJobFailed returns true if the Job has failed, or false if -// the Job is in progress or completed successfully. -func IsJobFailed(job *batchv1.Job) bool { - for _, c := range job.Status.Conditions { - if c.Type == batchv1.JobFailed && c.Status == corev1.ConditionTrue { - return true - } - } - return false -} - -// JobFailedMessage returns a string containing the job's failure reason -// and message for use in a Condition. -func JobFailedMessage(job *batchv1.Job) string { - for _, c := range job.Status.Conditions { - if c.Type == batchv1.JobFailed && c.Status == corev1.ConditionTrue { - return fmt.Sprintf("[%s] %s", c.Reason, c.Message) - } - } - return "" -} - -// makePodTemplate creates a pod template for a feed stop or start Job. -func makePodTemplate(feed *feedsv1alpha1.Feed, source *feedsv1alpha1.EventSource, trigger sources.EventTrigger, target string) (*corev1.PodTemplateSpec, error) { - var op Operation - if feed.GetDeletionTimestamp() == nil { - op = OperationStartFeed - } else { - op = OperationStopFeed - } - - var marshaledFeedContext []byte - var err error - // Check for an existing RawExtension object in the Feed status - if rawExt := feed.Status.FeedContext; rawExt != nil && rawExt.Raw != nil && len(rawExt.Raw) > 0 { - var ctx sources.FeedContext - if err = json.Unmarshal(rawExt.Raw, &ctx.Context); err != nil { - return nil, err - } - marshaledFeedContext, err = json.Marshal(ctx) - if err != nil { - return nil, err - } - } - // If no context was present, marshal an empty context because the event - // source wrapper expects it to be valid json. - if len(marshaledFeedContext) == 0 { - marshaledFeedContext, err = json.Marshal(sources.FeedContext{}) - if err != nil { - return nil, err - } - } - encodedFeedContext := base64.StdEncoding.EncodeToString(marshaledFeedContext) - - marshalledTrigger, err := json.Marshal(trigger) - if err != nil { - return nil, err - } - encodedTrigger := base64.StdEncoding.EncodeToString(marshalledTrigger) - - var encodedSourceParameters string - if source.Spec.Parameters != nil { - marshalledSourceParameters, err := json.Marshal(source.Spec.Parameters) - if err != nil { - return nil, err - } - encodedSourceParameters = base64.StdEncoding.EncodeToString(marshalledSourceParameters) - } - - return &corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - // don't inject Istio sidecar - // so if the feed can to access external services during StartFeed/StopFeed - Annotations: map[string]string{sidecarIstioInjectAnnotation: "false"}, - }, - Spec: corev1.PodSpec{ - ServiceAccountName: feed.Spec.ServiceAccountName, - RestartPolicy: corev1.RestartPolicyNever, - Containers: []corev1.Container{ - { - Name: "feedlet", - Image: source.Spec.Image, - ImagePullPolicy: corev1.PullIfNotPresent, - Env: []corev1.EnvVar{ - { - Name: string(EnvVarOperation), - Value: string(op), - }, - { - Name: string(EnvVarTarget), - Value: target, - }, - { - Name: string(EnvVarTrigger), - Value: encodedTrigger, - }, - { - Name: string(EnvVarContext), - Value: encodedFeedContext, - }, - { - Name: string(EnvVarEventSourceParameters), - Value: encodedSourceParameters, - }, - { - Name: string(EnvVarNamespace), - ValueFrom: &corev1.EnvVarSource{ - FieldRef: &corev1.ObjectFieldSelector{ - FieldPath: "metadata.namespace", - }, - }, - }, - { - Name: string(EnvVarServiceAccount), - ValueFrom: &corev1.EnvVarSource{ - FieldRef: &corev1.ObjectFieldSelector{ - FieldPath: "spec.serviceAccountName", - }, - }, - }, - }, - }, - }, - }, - }, nil -} - -// GetFirstTerminationMessage returns the termination message of the first -// terminated container in the given Pod. -func GetFirstTerminationMessage(pod *corev1.Pod) string { - for _, cs := range pod.Status.ContainerStatuses { - if cs.State.Terminated != nil && cs.State.Terminated.Message != "" { - return cs.State.Terminated.Message - } - } - return "" -} diff --git a/pkg/controller/feed/resources/job_test.go b/pkg/controller/feed/resources/job_test.go deleted file mode 100644 index 4b3ad41d2ea..00000000000 --- a/pkg/controller/feed/resources/job_test.go +++ /dev/null @@ -1,430 +0,0 @@ -/* -Copyright 2018 The Knative 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 resources - -import ( - "fmt" - "github.com/google/go-cmp/cmp" - feedsv1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - "github.com/knative/eventing/pkg/sources" - batchv1 "k8s.io/api/batch/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "strings" - "testing" -) - -const ( - feedName = "feed-name" - feedNamespace = "feed-namespace" - feedUid = "feed-uid" - feedTarget = "feed-target" -) - -func TestIsJobComplete(t *testing.T) { - testCases := []struct { - name string - conditions []batchv1.JobCondition - want bool - }{ - { - name: "no conditions: false", - want: false, - }, - { - name: "no job complete status: false", - conditions: []batchv1.JobCondition{ - { - Type: batchv1.JobFailed, - Status: corev1.ConditionTrue, - }, - }, - want: false, - }, - { - name: "job complete false: false", - conditions: []batchv1.JobCondition{ - { - Type: batchv1.JobComplete, - Status: corev1.ConditionFalse, - }, - }, - want: false, - }, - { - name: "job complete true: true", - conditions: []batchv1.JobCondition{ - { - Type: batchv1.JobComplete, - Status: corev1.ConditionTrue, - }, - }, - want: true, - }, - { - name: "multiple conditions, job complete true: true", - conditions: []batchv1.JobCondition{ - { - Type: batchv1.JobFailed, - Status: corev1.ConditionFalse, - }, - { - Type: batchv1.JobComplete, - Status: corev1.ConditionTrue, - }, - }, - want: true, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - job := makeJobWithConditions(tc.conditions) - actual := IsJobComplete(job) - if actual != tc.want { - t.Errorf("Expected %v, actual %v", tc.want, actual) - } - }) - } -} - -func TestIsJobFailed(t *testing.T) { - testCases := []struct { - name string - conditions []batchv1.JobCondition - want bool - }{ - { - name: "no conditions: false", - want: false, - }, - { - name: "no job failed status: false", - conditions: []batchv1.JobCondition{ - { - Type: batchv1.JobComplete, - Status: corev1.ConditionTrue, - }, - }, - want: false, - }, - { - name: "job failed false: false", - conditions: []batchv1.JobCondition{ - { - Type: batchv1.JobFailed, - Status: corev1.ConditionFalse, - }, - }, - want: false, - }, - { - name: "job failed true: true", - conditions: []batchv1.JobCondition{ - { - Type: batchv1.JobFailed, - Status: corev1.ConditionTrue, - }, - }, - want: true, - }, - { - name: "multiple conditions, job failed true: true", - conditions: []batchv1.JobCondition{ - { - Type: batchv1.JobComplete, - Status: corev1.ConditionFalse, - }, - { - Type: batchv1.JobFailed, - Status: corev1.ConditionTrue, - }, - }, - want: true, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - job := makeJobWithConditions(tc.conditions) - actual := IsJobFailed(job) - if actual != tc.want { - t.Errorf("Expected %v, actual %v", tc.want, actual) - } - }) - } -} - -func TestJobFailedMessage(t *testing.T) { - jobFailedReason := "test induced job failed reason" - jobFailedMessage := "test induced job failed message" - - testCases := []struct { - name string - conditions []batchv1.JobCondition - want string - }{ - { - name: "no conditions: empty string", - want: "", - }, - { - name: "no job failed status: empty string", - conditions: []batchv1.JobCondition{ - { - Type: batchv1.JobComplete, - Status: corev1.ConditionTrue, - }, - }, - want: "", - }, - { - name: "job failed false: empty string", - conditions: []batchv1.JobCondition{ - { - Type: batchv1.JobFailed, - Status: corev1.ConditionFalse, - }, - }, - want: "", - }, - { - name: "job failed true: message", - conditions: []batchv1.JobCondition{ - { - Type: batchv1.JobFailed, - Status: corev1.ConditionTrue, - Reason: jobFailedReason, - Message: jobFailedMessage, - }, - }, - want: fmt.Sprintf("[%s] %s", jobFailedReason, jobFailedMessage), - }, - { - name: "multiple conditions, job failed true: message", - conditions: []batchv1.JobCondition{ - { - Type: batchv1.JobComplete, - Status: corev1.ConditionFalse, - }, - { - Type: batchv1.JobFailed, - Status: corev1.ConditionTrue, - Reason: jobFailedReason, - Message: jobFailedMessage, - }, - }, - want: fmt.Sprintf("[%s] %s", jobFailedReason, jobFailedMessage), - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - job := makeJobWithConditions(tc.conditions) - actual := JobFailedMessage(job) - if actual != tc.want { - t.Errorf("Expected '%v', actual '%v'", tc.want, actual) - } - }) - } -} - -func TestGetFirstTerminationMessage(t *testing.T) { - message := "test induced terminal status message" - testCases := []struct { - name string - status []corev1.ContainerStatus - want string - }{ - { - name: "no status: empty string", - want: "", - }, - { - name: "no terminated status: empty string", - status: []corev1.ContainerStatus{ - { - State: corev1.ContainerState{ - Running: &corev1.ContainerStateRunning{ - StartedAt: metav1.Now(), - }, - }, - }, - }, - want: "", - }, - { - name: "no terminated status message: empty string", - status: []corev1.ContainerStatus{ - { - State: corev1.ContainerState{ - Terminated: &corev1.ContainerStateTerminated{}, - }, - }, - }, - want: "", - }, - { - name: "terminated status message: message", - status: []corev1.ContainerStatus{ - { - State: corev1.ContainerState{ - Terminated: &corev1.ContainerStateTerminated{ - Message: message, - }, - }, - }, - }, - want: message, - }, - { - name: "multiple terminated status message: first message", - status: []corev1.ContainerStatus{ - { - State: corev1.ContainerState{ - Terminated: &corev1.ContainerStateTerminated{ - Message: message, - }, - }, - }, - { - State: corev1.ContainerState{ - Terminated: &corev1.ContainerStateTerminated{ - Message: "some other message that won't be used", - }, - }, - }, - }, - want: message, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - pod := makePodWithStatus(tc.status) - actual := GetFirstTerminationMessage(pod) - if actual != tc.want { - t.Errorf("Expected '%v', actual '%v'", tc.want, actual) - } - }) - } -} - -func TestMakeJob(t *testing.T) { - type jobVerification func(t *testing.T, job *batchv1.Job) - - testCases := []struct { - name string - feed *feedsv1alpha1.Feed - source *feedsv1alpha1.EventSource - trigger sources.EventTrigger - target string - wantErr error - jobVerification []jobVerification - }{ - { - name: "", - feed: &feedsv1alpha1.Feed{ - ObjectMeta: metav1.ObjectMeta{ - Name: feedName, - Namespace: feedNamespace, - UID: feedUid, - }, - Spec: feedsv1alpha1.FeedSpec{ - ServiceAccountName: "feed-service-account", - }, - }, - source: &feedsv1alpha1.EventSource{}, - trigger: sources.EventTrigger{ - EventType: "test-event-type", - }, - target: feedTarget, - jobVerification: []jobVerification{ - jobObjectMetaVerification, - jobObjectSpecVerification, - }, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - actual, actualErr := MakeJob(tc.feed, tc.source, tc.trigger, tc.target) - if cmp.Diff(tc.wantErr, actualErr) != "" { - t.Errorf("Incorrect error (-want, +got): %v", cmp.Diff(tc.wantErr, actualErr)) - } - for _, jv := range tc.jobVerification { - jv(t, actual) - } - }) - } -} - -func makeJobWithConditions(conditions []batchv1.JobCondition) *batchv1.Job { - return &batchv1.Job{ - Status: batchv1.JobStatus{ - Conditions: conditions, - }, - } -} - -func makePodWithStatus(status []corev1.ContainerStatus) *corev1.Pod { - return &corev1.Pod{ - Status: corev1.PodStatus{ - ContainerStatuses: status, - }, - } -} - -func jobObjectMetaVerification(t *testing.T, job *batchv1.Job) { - if job.Namespace != feedNamespace { - t.Errorf("Expected namespace '%v', actual '%v'", feedNamespace, job.Namespace) - } - if !strings.Contains(job.Name, feedName) { - t.Errorf("Expected job name to include the Feed's name, '%v'. Actual: '%v'", feedName, job.Name) - } - if job.Labels["app"] != "feedpod" { - t.Errorf("Missing app=feedpod label. Actual: %v", job.Labels) - } - // TODO: Verify the entire owner reference. - if len(job.OwnerReferences) != 1 || job.OwnerReferences[0].UID != feedUid { - t.Errorf("Expected exactly one owner reference that points to the Feed. Actual: %+v", job.OwnerReferences) - } -} - -func jobObjectSpecVerification(t *testing.T, job *batchv1.Job) { - pt := job.Spec.Template - if pt.Annotations[sidecarIstioInjectAnnotation] != "false" { - t.Errorf("Expected Istio sidecar injection disabled. Actually: %v", pt.Labels[sidecarIstioInjectAnnotation]) - } - if len(pt.Spec.Containers) != 1 { - t.Errorf("Expected exactly one container, the feedlet. Actually: %+v", pt.Spec.Containers) - } - c := pt.Spec.Containers[0] - if getEnvVar(c.Env, "FEED_TARGET") != feedTarget { - t.Errorf("Expected FEED_TARGET to be '%v'. Actually: %+v", feedTarget, getEnvVar(c.Env, "FEED_TARGET")) - } - // TODO: Verify the other fields. -} - -func getEnvVar(env []corev1.EnvVar, name string) string { - for _, ev := range env { - if ev.Name == name { - return ev.Value - } - } - return "" -} diff --git a/pkg/controller/feed/resources/names.go b/pkg/controller/feed/resources/names.go deleted file mode 100644 index 111e09ec604..00000000000 --- a/pkg/controller/feed/resources/names.go +++ /dev/null @@ -1,42 +0,0 @@ -/* -Copyright 2018 The Knative 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 resources - -import ( - "fmt" - - feedsv1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" -) - -// JobName returns the name of the job for the feed, taking into account whether -// it's been deleted. -func JobName(feed *feedsv1alpha1.Feed) string { - if feed.GetDeletionTimestamp() != nil { - return StopJobName(feed) - } - return StartJobName(feed) -} - -// StartJobName returns the name of the job for the start operation. -func StartJobName(feed *feedsv1alpha1.Feed) string { - return fmt.Sprintf("%s-start", feed.Name) -} - -// StopJobName returns the name of the job for the stop operation. -func StopJobName(feed *feedsv1alpha1.Feed) string { - return fmt.Sprintf("%s-stop", feed.Name) -} diff --git a/pkg/controller/flow/dyn_client.go b/pkg/controller/flow/dyn_client.go deleted file mode 100644 index aa3dcf3aaee..00000000000 --- a/pkg/controller/flow/dyn_client.go +++ /dev/null @@ -1,74 +0,0 @@ -/* -Copyright 2018 The Knative 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 flow - -import ( - "fmt" - "strings" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/client-go/dynamic" - "k8s.io/client-go/rest" -) - -// CreateDynamicClient creates a dynamic client for the Group Version for the -// ObjectReference. It can only be used for that APIVersion / Group -func CreateDynamicClient(config *rest.Config, ref *corev1.ObjectReference) (dynamic.Interface, error) { - // We need to tweak the configuration so that it points to the right - // resources under the ThirdPartyResources that Istio uses. - gvk := ref.GroupVersionKind() - - config.ContentConfig.GroupVersion = &schema.GroupVersion{ - Group: gvk.Group, - Version: gvk.Version, - } - config.APIPath = "apis" - return dynamic.NewForConfig(config) -} - -func CreateResourceInterface(config *rest.Config, ref *corev1.ObjectReference, namespace string) (dynamic.ResourceInterface, error) { - c, err := CreateDynamicClient(config, ref) - if err != nil { - return nil, err - } - - gvk := ref.GroupVersionKind() - - r := c.Resource(schema.GroupVersionResource{ - Group: gvk.Group, - Version: gvk.Version, - Resource: pluralizeKind(gvk.Kind), - }) - if r == nil { - return nil, fmt.Errorf("failed to create dynamic client resource") - } - return r.Namespace(namespace), nil -} - -// takes a kind and pluralizes it. This is super terrible, but I am -// not aware of a generic way to do this. -// I am not alone in thinking this and I haven't found a better solution: -// This seems relevant: -// https://github.com/kubernetes/kubernetes/issues/18622 -func pluralizeKind(kind string) string { - ret := strings.ToLower(kind) - if strings.HasSuffix(ret, "s") { - return fmt.Sprintf("%ses", ret) - } - return fmt.Sprintf("%ss", ret) -} diff --git a/pkg/controller/flow/provider.go b/pkg/controller/flow/provider.go deleted file mode 100644 index b916006f7aa..00000000000 --- a/pkg/controller/flow/provider.go +++ /dev/null @@ -1,91 +0,0 @@ -/* -Copyright 2018 The Knative 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 flow - -import ( - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - feedsv1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - "github.com/knative/eventing/pkg/apis/flows/v1alpha1" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/record" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/controller" - "sigs.k8s.io/controller-runtime/pkg/handler" - "sigs.k8s.io/controller-runtime/pkg/manager" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - "sigs.k8s.io/controller-runtime/pkg/source" -) - -const ( - // controllerAgentName is the string used by this controller to identify - // itself when creating events. - controllerAgentName = "flow-controller" -) - -type reconciler struct { - client client.Client - restConfig *rest.Config - recorder record.EventRecorder -} - -// Verify the struct implements reconcile.Reconciler -var _ reconcile.Reconciler = &reconciler{} - -// ProvideController returns a flow controller. -func ProvideController(mgr manager.Manager) (controller.Controller, error) { - // Setup a new controller to Reconcile Flows. - c, err := controller.New(controllerAgentName, mgr, controller.Options{ - Reconciler: &reconciler{ - recorder: mgr.GetRecorder(controllerAgentName), - }, - }) - if err != nil { - return nil, err - } - - // Watch Flow events and enqueue Flow object key. - if err := c.Watch(&source.Kind{Type: &v1alpha1.Flow{}}, &handler.EnqueueRequestForObject{}); err != nil { - return nil, err - } - - // In addition to watching Flow objects, watch for objects that a Flow creates and own and when changes - // are made to them, enqueue owning Flow object for reconcile loop. - if err := c.Watch(&source.Kind{Type: &channelsv1alpha1.Channel{}}, - &handler.EnqueueRequestForOwner{OwnerType: &v1alpha1.Flow{}, IsController: true}); err != nil { - return nil, err - } - if err := c.Watch(&source.Kind{Type: &channelsv1alpha1.Subscription{}}, - &handler.EnqueueRequestForOwner{OwnerType: &v1alpha1.Flow{}, IsController: true}); err != nil { - return nil, err - } - if err := c.Watch(&source.Kind{Type: &feedsv1alpha1.Feed{}}, - &handler.EnqueueRequestForOwner{OwnerType: &v1alpha1.Flow{}, IsController: true}); err != nil { - return nil, err - } - - return c, nil -} - -func (r *reconciler) InjectClient(c client.Client) error { - r.client = c - return nil -} - -func (r *reconciler) InjectConfig(c *rest.Config) error { - r.restConfig = c - return nil -} diff --git a/pkg/controller/flow/reconcile.go b/pkg/controller/flow/reconcile.go deleted file mode 100644 index cb4c3696bed..00000000000 --- a/pkg/controller/flow/reconcile.go +++ /dev/null @@ -1,355 +0,0 @@ -/* -Copyright 2018 The Knative 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 flow - -import ( - "context" - "fmt" - "log" - - "github.com/golang/glog" - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - feedsv1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - "github.com/knative/eventing/pkg/apis/flows/v1alpha1" - "github.com/knative/eventing/pkg/controller/flow/resources" - "github.com/knative/eventing/pkg/system" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/api/meta" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime/schema" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/reconcile" -) - -// What field do we assume Object Reference exports as a resolvable target -const targetFieldName = "domainInternal" - -// Reconcile compares the actual state with the desired, and attempts to -// converge the two. It then updates the Status block of the Flow resource -// with the current status of the resource. -func (r *reconciler) Reconcile(request reconcile.Request) (reconcile.Result, error) { - glog.Infof("Reconciling flow %v", request) - flow := &v1alpha1.Flow{} - err := r.client.Get(context.TODO(), request.NamespacedName, flow) - - if errors.IsNotFound(err) { - glog.Errorf("could not find flow %v\n", request) - return reconcile.Result{}, nil - } - - if err != nil { - glog.Errorf("could not fetch Flow %v for %+v\n", err, request) - return reconcile.Result{}, err - } - - original := flow.DeepCopy() - - flow.Status.InitializeConditions() - - // Reconcile this copy of the Flow and then write back any status - // updates regardless of whether the reconcile error out. - err = r.reconcile(flow) - if equality.Semantic.DeepEqual(original.Status, flow.Status) { - // If we didn't change anything then don't call updateStatus. - // This is important because the copy we loaded from the informer's - // cache may be stale and we don't want to overwrite a prior update - // to status with this stale state. - } else if _, err := r.updateStatus(flow); err != nil { - glog.Warningf("Failed to update flow status: %v", err) - return reconcile.Result{}, err - } - - // Requeue if the resource is not ready: - return reconcile.Result{}, err -} - -func (r *reconciler) reconcile(flow *v1alpha1.Flow) error { - // See if the flow has been deleted - accessor, err := meta.Accessor(flow) - if err != nil { - log.Fatalf("Failed to get metadata: %s", err) - } - deletionTimestamp := accessor.GetDeletionTimestamp() - glog.Infof("DeletionTimestamp: %v", deletionTimestamp) - - target, err := r.resolveActionTarget(flow.Namespace, flow.Spec.Action) - if err != nil { - glog.Warningf("Failed to resolve target %v : %v", flow.Spec.Action, err) - flow.Status.PropagateActionTargetResolved(corev1.ConditionFalse, "ActionTargetNotResolved", err.Error()) - return err - } - - flow.Status.PropagateActionTargetResolved(corev1.ConditionTrue, "ActionTargetResolved", fmt.Sprintf("Resolved to: %q", target)) - - // Ok, so target is the underlying k8s service (or URI if so specified) that we want to target - glog.Infof("Resolved Target to: %q", target) - - // Reconcile the Channel. Creates a channel that is the target that the Feed will use. - // TODO: We should reuse channels possibly. By this I mean that instead of creating a - // channel for each subscription, we could look at existing channels and reuse one - // and only create a subscription to a channel instead. - channel, err := r.reconcileChannel(flow) - if err != nil { - glog.Warningf("Failed to reconcile channel : %v", err) - return err - } - flow.Status.PropagateChannelStatus(channel.Status) - - subscription, err := r.reconcileSubscription(channel.Name, target, flow) - if err != nil { - glog.Warningf("Failed to reconcile subscription : %v", err) - return err - } - flow.Status.PropagateSubscriptionStatus(subscription.Status) - - channelDNS := channel.Status.DomainInternal - if channelDNS != "" { - glog.Infof("Reconciling feed for flow %q targeting %q", flow.Name, channelDNS) - feed, err := r.reconcileFeed(channelDNS, flow) - if err != nil { - glog.Warningf("Failed to reconcile feed: %v", err) - return err - } - glog.Infof("Reconciled feed status for flow %q targeting %q : %+v", flow.Name, channelDNS, feed.Status) - flow.Status.PropagateFeedStatus(feed.Status) - } - return nil -} - -func (r *reconciler) updateStatus(flow *v1alpha1.Flow) (*v1alpha1.Flow, error) { - newFlow := &v1alpha1.Flow{} - err := r.client.Get(context.TODO(), client.ObjectKey{Namespace: flow.Namespace, Name: flow.Name}, newFlow) - - if err != nil { - return nil, err - } - newFlow.Status = flow.Status - - // Until #38113 is merged, we must use Update instead of UpdateStatus to - // update the Status block of the Flow resource. UpdateStatus will not - // allow changes to the Spec of the resource, which is ideal for ensuring - // nothing other than resource status has been updated. - if err = r.client.Update(context.TODO(), newFlow); err != nil { - return nil, err - } - return newFlow, nil -} - -// resolveActionTarget resolves the Action.Target. If it's an ObjectReference -// will resolve it, and if it's an TargetURI will just return it. -func (r *reconciler) resolveActionTarget(namespace string, action v1alpha1.FlowAction) (string, error) { - glog.Infof("Resolving target: %+v", action) - - if action.Target != nil { - return r.resolveObjectReference(namespace, action.Target) - } - if action.TargetURI != nil { - return *action.TargetURI, nil - } - - return "", fmt.Errorf("no resolvable action target: %+v", action) -} - -// resolveObjectReference fetches an object based on ObjectReference. It assumes the -// object has a status["domainInternal"] string in it and returns it. -func (r *reconciler) resolveObjectReference(namespace string, ref *corev1.ObjectReference) (string, error) { - resourceClient, err := CreateResourceInterface(r.restConfig, ref, namespace) - if err != nil { - glog.Warningf("failed to create dynamic client resource: %v", err) - return "", err - } - - obj, err := resourceClient.Get(ref.Name, metav1.GetOptions{}) - if err != nil { - glog.Warningf("failed to get object: %v", err) - return "", err - } - status, ok := obj.Object["status"] - if !ok { - return "", fmt.Errorf("%q does not contain status", ref.Name) - } - statusMap := status.(map[string]interface{}) - serviceName, ok := statusMap[targetFieldName] - if !ok { - return "", fmt.Errorf("%q does not contain field %q in status", targetFieldName, ref.Name) - } - serviceNameStr, ok := serviceName.(string) - if !ok { - return "", fmt.Errorf("%q status field %q is not a string", targetFieldName, ref.Name) - } - return serviceNameStr, nil -} - -func (r *reconciler) reconcileChannel(flow *v1alpha1.Flow) (*channelsv1alpha1.Channel, error) { - channelName := flow.Name - - channel := &channelsv1alpha1.Channel{} - err := r.client.Get(context.TODO(), client.ObjectKey{Namespace: flow.Namespace, Name: channelName}, channel) - if errors.IsNotFound(err) { - channel, err = r.createChannel(flow) - if err != nil { - glog.Errorf("Failed to create channel %q : %v", channelName, err) - return nil, err - } - } else if err != nil { - glog.Errorf("Failed to reconcile channel %q failed to get channels : %v", channelName, err) - return nil, err - } - - // TODO: Make sure channel is what it should be. For now, just assume it's fine - // if it exists. - return channel, nil -} - -func (r *reconciler) createChannel(flow *v1alpha1.Flow) (*channelsv1alpha1.Channel, error) { - clusterBusName, err := r.getDefaultClusterBusName() - if err != nil { - return nil, err - } - - channel := resources.MakeChannel(clusterBusName, flow) - if err := r.client.Create(context.TODO(), channel); err != nil { - return nil, err - } - return channel, nil -} - -func (r *reconciler) reconcileSubscription(channelName string, target string, flow *v1alpha1.Flow) (*channelsv1alpha1.Subscription, error) { - subscriptionName := flow.Name - - subscription := &channelsv1alpha1.Subscription{} - err := r.client.Get(context.TODO(), client.ObjectKey{Namespace: flow.Namespace, Name: subscriptionName}, subscription) - if errors.IsNotFound(err) { - subscription, err = r.createSubscription(channelName, target, flow) - if err != nil { - glog.Errorf("Failed to create subscription %q : %v", subscriptionName, err) - return nil, err - } - } else if err != nil { - glog.Errorf("Failed to reconcile subscription %q failed to get subscriptions : %v", subscriptionName, err) - return nil, err - } - - // TODO: Make sure subscription is what it should be. For now, just assume it's fine - // if it exists. - return subscription, nil -} - -func (r *reconciler) createSubscription(channelName string, target string, flow *v1alpha1.Flow) (*channelsv1alpha1.Subscription, error) { - subscription := resources.MakeSubscription(channelName, target, flow) - if err := r.client.Create(context.TODO(), subscription); err != nil { - return nil, err - } - return subscription, nil -} - -func (r *reconciler) reconcileFeed(channelDNS string, flow *v1alpha1.Flow) (*feedsv1alpha1.Feed, error) { - feed, err := r.getFeed(context.TODO(), flow) - if errors.IsNotFound(err) { - feed, err = r.createFeed(channelDNS, flow) - if err != nil { - glog.Errorf("Failed to create feed for flow %q: %v", flow.Name, err) - return nil, err - } - } else if err != nil { - glog.Errorf("Failed to reconcile feed for flow %q failed to get feeds : %v", flow.Name, err) - return nil, err - } - - glog.Infof("Reconciled feed: %+v", feed) - // TODO: Make sure feed is what it should be. For now, just assume it's fine - // if it exists. - return feed, nil -} - -func (r *reconciler) createFeed(channelDNS string, flow *v1alpha1.Flow) (*feedsv1alpha1.Feed, error) { - feed := resources.MakeFeed(channelDNS, flow) - if err := r.client.Create(context.TODO(), feed); err != nil { - return nil, err - } - return feed, nil -} - -const ( - // controllerConfigMapName is the name of the configmap in the eventing - // namespace that holds the configuration for this controller. - controllerConfigMapName = "flow-controller-config" - - // defaultClusterBusConfigMapKey is the name of the key in this controller's - // ConfigMap that contains the name of the default cluster bus for the flow - // controller to use. - defaultClusterBusConfigMapKey = "default-cluster-bus" - - // fallbackClusterBusName is the name of the cluster bus that will be used - // for flows if the controller's configmap does not exist or does not - // contain the 'default-cluster-bus' key. - fallbackClusterBusName = "stub" -) - -// getDefaultClusterBusName returns the value of the 'default-cluster-bus' key in -// the knative-eventing/flow-controller-config configmap or an error. If the -// 'default-cluster-bus' key is not set, it returns the default value "stub". -func (r *reconciler) getDefaultClusterBusName() (string, error) { - configMapKey := client.ObjectKey{ - Namespace: system.Namespace, - Name: controllerConfigMapName, - } - - configMap := &corev1.ConfigMap{} - if err := r.client.Get(context.TODO(), configMapKey, configMap); err != nil { - // return the fallback value if there's an error loading the configmap - return fallbackClusterBusName, nil - } - - if value, ok := configMap.Data[defaultClusterBusConfigMapKey]; ok { - return value, nil - } - - return fallbackClusterBusName, nil // return the fallback value -} - -func (r *reconciler) getFeed(ctx context.Context, flow *v1alpha1.Flow) (*feedsv1alpha1.Feed, error) { - feedList := &feedsv1alpha1.FeedList{} - err := r.client.List( - ctx, - &client.ListOptions{ - Namespace: flow.Namespace, - LabelSelector: labels.Everything(), - // TODO this is here because the fake client needs it. Remove this when it's no longer - // needed. - Raw: &metav1.ListOptions{ - TypeMeta: metav1.TypeMeta{ - APIVersion: feedsv1alpha1.SchemeGroupVersion.String(), - Kind: "Feed", - }, - }, - }, - feedList) - if err != nil { - glog.Errorf("Unable to list feeds: %v", err) - return nil, err - } - for _, feed := range feedList.Items { - if metav1.IsControlledBy(&feed, flow) { - return &feed, nil - } - } - return nil, errors.NewNotFound(schema.GroupResource{}, "") -} diff --git a/pkg/controller/flow/reconcile_test.go b/pkg/controller/flow/reconcile_test.go deleted file mode 100644 index cb7feefc6dd..00000000000 --- a/pkg/controller/flow/reconcile_test.go +++ /dev/null @@ -1,270 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Veroute.on 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 flow - -import ( - "context" - "fmt" - "sigs.k8s.io/controller-runtime/pkg/client" - "testing" - - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - feedsv1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - flowsv1alpha1 "github.com/knative/eventing/pkg/apis/flows/v1alpha1" - controllertesting "github.com/knative/eventing/pkg/controller/testing" - "github.com/knative/eventing/pkg/system" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/tools/record" -) - -var ( - trueVal = true - targetURI = "http://target.example.com" -) - -const ( - targetDNS = "myservice.mynamespace.svc.cluster.local" - eventType = "myeventtype" - flowName = "test-flow" -) - -func init() { - // Add types to scheme - feedsv1alpha1.AddToScheme(scheme.Scheme) - flowsv1alpha1.AddToScheme(scheme.Scheme) - channelsv1alpha1.AddToScheme(scheme.Scheme) -} - -var injectDomainInternalMocks = controllertesting.Mocks{ - MockCreates: []controllertesting.MockCreate{ - func(innerClient client.Client, ctx context.Context, obj runtime.Object) (controllertesting.MockHandled, error) { - // If we are creating a Channel, then fill in the status, in particular the DomainInternal as - // it used to control whether the Feed is created. - if channel, ok := obj.(*channelsv1alpha1.Channel); ok { - err := innerClient.Create(ctx, obj) - channel.Status.DomainInternal = targetDNS - return controllertesting.Handled, err - } - return controllertesting.Unhandled, nil - }, - }, -} - -var testCases = []controllertesting.TestCase{ - { - Name: "new flow: adds status, action target resolved", - InitialState: []runtime.Object{ - getNewFlow(), - getFlowControllerConfigMap(), - }, - ReconcileKey: "test/test-flow", - WantResult: reconcile.Result{}, - WantPresent: []runtime.Object{ - getActionTargetResolvedFlow(), - func() *channelsv1alpha1.Channel { - c := getNewChannel() - c.Spec.ClusterBus = "special-bus" - return c - }(), - getNewSubscription(), - getNewFeed(), - }, - Mocks: injectDomainInternalMocks, - }, - { - Name: "new flow: adds status, action target resolved, no flow controller config map, use default 'stub' bus", - InitialState: []runtime.Object{ - getNewFlow(), - }, - ReconcileKey: "test/test-flow", - WantResult: reconcile.Result{}, - WantPresent: []runtime.Object{ - getActionTargetResolvedFlow(), - getNewChannel(), - getNewSubscription(), - getNewFeed(), - }, - Mocks: injectDomainInternalMocks, - }, -} - -func TestAllCases(t *testing.T) { - recorder := record.NewBroadcaster().NewRecorder(scheme.Scheme, corev1.EventSource{Component: controllerAgentName}) - - for _, tc := range testCases { - c := tc.GetClient() - r := &reconciler{ - client: c, - recorder: recorder, - } - t.Run(tc.Name, tc.Runner(t, r, c)) - } -} - -func getActionTargetResolvedFlow() *flowsv1alpha1.Flow { - newFlow := getNewFlow() - newFlow.Status = flowsv1alpha1.FlowStatus{ - Conditions: []flowsv1alpha1.FlowCondition{{ - Type: flowsv1alpha1.FlowConditionReady, - Status: corev1.ConditionUnknown, - }, { - Type: flowsv1alpha1.FlowConditionActionTargetResolved, - Status: corev1.ConditionTrue, - Reason: "ActionTargetResolved", - Message: fmt.Sprintf("Resolved to: %q", targetURI), - }}, - } - return newFlow -} - -func getNewFlow() *flowsv1alpha1.Flow { - return &flowsv1alpha1.Flow{ - TypeMeta: flowType(), - ObjectMeta: om("test", flowName), - Spec: flowsv1alpha1.FlowSpec{ - Action: flowsv1alpha1.FlowAction{ - TargetURI: &targetURI, - }, - Trigger: flowsv1alpha1.EventTrigger{ - EventType: eventType, - Resource: "myresource", - Service: "", - Parameters: nil, - ParametersFrom: nil, - }, - }, - } -} - -func getNewChannel() *channelsv1alpha1.Channel { - channel := &channelsv1alpha1.Channel{ - TypeMeta: channelType(), - ObjectMeta: om("test", flowName), - Spec: channelsv1alpha1.ChannelSpec{ - ClusterBus: "stub", - }, - } - channel.ObjectMeta.OwnerReferences = append(channel.ObjectMeta.OwnerReferences, getOwnerReference(false)) - - // selflink is not filled in when we create the object, so clear it - channel.ObjectMeta.SelfLink = "" - return channel -} - -func getNewSubscription() *channelsv1alpha1.Subscription { - subscription := &channelsv1alpha1.Subscription{ - TypeMeta: subscriptionType(), - ObjectMeta: om("test", flowName), - Spec: channelsv1alpha1.SubscriptionSpec{ - Channel: flowName, - Subscriber: targetURI, - }, - } - subscription.ObjectMeta.OwnerReferences = append(subscription.ObjectMeta.OwnerReferences, getOwnerReference(false)) - - // selflink is not filled in when we create the object, so clear it - subscription.ObjectMeta.SelfLink = "" - return subscription -} - -func getNewFeed() *feedsv1alpha1.Feed { - return &feedsv1alpha1.Feed{ - TypeMeta: feedType(), - ObjectMeta: feedObjectMeta("test", "test-flow-"), - Spec: feedsv1alpha1.FeedSpec{ - Action: feedsv1alpha1.FeedAction{ - DNSName: targetDNS, - }, - Trigger: feedsv1alpha1.EventTrigger{ - EventType: eventType, - Resource: "myresource", - Service: "", - Parameters: nil, - ParametersFrom: nil, - }, - }, - } -} - -func getFlowControllerConfigMap() *corev1.ConfigMap { - return &corev1.ConfigMap{ - ObjectMeta: om(system.Namespace, controllerConfigMapName), - Data: map[string]string{ - defaultClusterBusConfigMapKey: "special-bus", - }, - } -} - -func flowType() metav1.TypeMeta { - return metav1.TypeMeta{ - APIVersion: flowsv1alpha1.SchemeGroupVersion.String(), - Kind: "Flow", - } -} - -func feedType() metav1.TypeMeta { - return metav1.TypeMeta{ - APIVersion: feedsv1alpha1.SchemeGroupVersion.String(), - Kind: "Feed", - } -} - -func channelType() metav1.TypeMeta { - return metav1.TypeMeta{ - APIVersion: channelsv1alpha1.SchemeGroupVersion.String(), - Kind: "Channel", - } -} - -func subscriptionType() metav1.TypeMeta { - return metav1.TypeMeta{ - APIVersion: channelsv1alpha1.SchemeGroupVersion.String(), - Kind: "Subscription", - } -} - -func om(namespace, name string) metav1.ObjectMeta { - return metav1.ObjectMeta{ - Namespace: namespace, - Name: name, - SelfLink: fmt.Sprintf("/apis/eventing/v1alpha1/namespaces/%s/object/%s", namespace, name), - } -} -func feedObjectMeta(namespace, generateName string) metav1.ObjectMeta { - return metav1.ObjectMeta{ - Namespace: namespace, - GenerateName: generateName, - OwnerReferences: []metav1.OwnerReference{ - getOwnerReference(true), - }, - } -} - -func getOwnerReference(blockOwnerDeletion bool) metav1.OwnerReference { - return metav1.OwnerReference{ - APIVersion: flowsv1alpha1.SchemeGroupVersion.String(), - Kind: "Flow", - Name: flowName, - Controller: &trueVal, - BlockOwnerDeletion: &blockOwnerDeletion, - } -} diff --git a/pkg/controller/flow/resources/channel.go b/pkg/controller/flow/resources/channel.go deleted file mode 100644 index f839732761e..00000000000 --- a/pkg/controller/flow/resources/channel.go +++ /dev/null @@ -1,42 +0,0 @@ -/* -Copyright 2018 The Knative 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 resources - -import ( - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - "github.com/knative/eventing/pkg/apis/flows/v1alpha1" - "github.com/knative/eventing/pkg/controller" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func MakeChannel(defaultBusName string, flow *v1alpha1.Flow) *channelsv1alpha1.Channel { - channelName := flow.Name - channel := &channelsv1alpha1.Channel{ - ObjectMeta: metav1.ObjectMeta{ - Name: channelName, - Namespace: flow.Namespace, - OwnerReferences: []metav1.OwnerReference{ - *controller.NewControllerRef(flow, false), - }, - }, - Spec: channelsv1alpha1.ChannelSpec{ - ClusterBus: defaultBusName, - }, - } - return channel -} diff --git a/pkg/controller/flow/resources/feed.go b/pkg/controller/flow/resources/feed.go deleted file mode 100644 index a0fdcf13d94..00000000000 --- a/pkg/controller/flow/resources/feed.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2018 The Knative 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 resources - -import ( - feedsv1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - - "github.com/knative/eventing/pkg/apis/flows/v1alpha1" - "github.com/knative/eventing/pkg/controller" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func MakeFeed(channelDNS string, flow *v1alpha1.Flow) *feedsv1alpha1.Feed { - feed := &feedsv1alpha1.Feed{ - ObjectMeta: metav1.ObjectMeta{ - GenerateName: flow.Name + "-", - Namespace: flow.Namespace, - OwnerReferences: []metav1.OwnerReference{ - *controller.NewControllerRef(flow, true), - }, - }, - Spec: feedsv1alpha1.FeedSpec{ - Action: feedsv1alpha1.FeedAction{DNSName: channelDNS}, - Trigger: feedsv1alpha1.EventTrigger{ - EventType: flow.Spec.Trigger.EventType, - Resource: flow.Spec.Trigger.Resource, - Service: flow.Spec.Trigger.Service, - }, - }, - } - if flow.Spec.ServiceAccountName != "" { - feed.Spec.ServiceAccountName = flow.Spec.ServiceAccountName - } - - if flow.Spec.Trigger.Parameters != nil { - feed.Spec.Trigger.Parameters = flow.Spec.Trigger.Parameters - } - if flow.Spec.Trigger.ParametersFrom != nil { - feed.Spec.Trigger.ParametersFrom = flow.Spec.Trigger.ParametersFrom - } - return feed -} diff --git a/pkg/controller/flow/resources/stub_test.go b/pkg/controller/flow/resources/stub_test.go deleted file mode 100644 index d4c244afe73..00000000000 --- a/pkg/controller/flow/resources/stub_test.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright 2018 The Knative 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 resources - -import "testing" - -func TestStub(t *testing.T) { - // TODO: Implement tests in this directory, please. - // This file is used to make code coverage on this directly count. -} diff --git a/pkg/controller/flow/resources/subscription.go b/pkg/controller/flow/resources/subscription.go deleted file mode 100644 index 7ff4cf1b3d7..00000000000 --- a/pkg/controller/flow/resources/subscription.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright 2018 The Knative 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 resources - -import ( - channelsv1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - "github.com/knative/eventing/pkg/apis/flows/v1alpha1" - "github.com/knative/eventing/pkg/controller" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func MakeSubscription(channelName string, target string, flow *v1alpha1.Flow) *channelsv1alpha1.Subscription { - subscriptionName := flow.Name - subscription := &channelsv1alpha1.Subscription{ - ObjectMeta: metav1.ObjectMeta{ - Name: subscriptionName, - Namespace: flow.Namespace, - OwnerReferences: []metav1.OwnerReference{ - *controller.NewControllerRef(flow, false), - }, - }, - Spec: channelsv1alpha1.SubscriptionSpec{ - Channel: channelName, - Subscriber: target, - }, - } - return subscription -} diff --git a/pkg/controller/names.go b/pkg/controller/names.go index 852481adc73..6026013e34b 100644 --- a/pkg/controller/names.go +++ b/pkg/controller/names.go @@ -18,26 +18,6 @@ package controller import "fmt" -func BusProvisionerDeploymentName(busName, namespace string) string { - return fmt.Sprintf("%s-%s-bus-provisioner", busName, namespace) -} - -func BusDispatcherDeploymentName(busName, namespace string) string { - return fmt.Sprintf("%s-%s-bus-dispatcher", busName, namespace) -} - -func BusDispatcherServiceName(busName, namespace string) string { - return fmt.Sprintf("%s-%s-bus", busName, namespace) -} - -func ClusterBusProvisionerDeploymentName(clusterBusName string) string { - return fmt.Sprintf("%s-clusterbus-provisioner", clusterBusName) -} - -func ClusterBusDispatcherDeploymentName(clusterBusName string) string { - return fmt.Sprintf("%s-clusterbus-dispatcher", clusterBusName) -} - func ClusterBusDispatcherServiceName(clusterBusName string) string { return fmt.Sprintf("%s-clusterbus", clusterBusName) } diff --git a/pkg/controller/names_test.go b/pkg/controller/names_test.go new file mode 100644 index 00000000000..ca0d3933a25 --- /dev/null +++ b/pkg/controller/names_test.go @@ -0,0 +1,67 @@ +/* + * Copyright 2018 The Knative 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 controller + +import ( + "testing" +) + +func TestNames(t *testing.T) { + testCases := []struct { + Name string + F func() string + Want string + }{{ + Name: "ClusterBusDispatcherServiceName", + F: func() string { + return ClusterBusDispatcherServiceName("foo") + }, + Want: "foo-clusterbus", + }, { + Name: "ChannelVirtualServiceName", + F: func() string { + return ChannelVirtualServiceName("foo") + }, + Want: "foo-channel", + }, { + Name: "ChannelServiceName", + F: func() string { + return ChannelServiceName("foo") + }, + Want: "foo-channel", + }, { + Name: "ChannelHostName", + F: func() string { + return ChannelHostName("foo", "namespace") + }, + Want: "foo.namespace.channels.cluster.local", + }, { + Name: "ServiceHostName", + F: func() string { + return ServiceHostName("foo", "namespace") + }, + Want: "foo.namespace.svc.cluster.local", + }} + + for _, tc := range testCases { + t.Run(tc.Name, func(t *testing.T) { + if got := tc.F(); got != tc.Want { + t.Errorf("want %v, got %v", tc.Want, got) + } + }) + } +} diff --git a/pkg/controller/owner_references.go b/pkg/controller/owner_references.go deleted file mode 100644 index 5780dca9af9..00000000000 --- a/pkg/controller/owner_references.go +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright 2018 The Knative 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 controller - -import ( - "fmt" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - - channelsv1alpha "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - eventingv1alpha "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" - feedsv1alpha "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - flowsv1alpha "github.com/knative/eventing/pkg/apis/flows/v1alpha1" -) - -func kind(obj metav1.Object) schema.GroupVersionKind { - switch obj.(type) { - // Channels - case *channelsv1alpha.Bus: - return channelsv1alpha.SchemeGroupVersion.WithKind("Bus") - case *channelsv1alpha.Channel: - return channelsv1alpha.SchemeGroupVersion.WithKind("Channel") - case *channelsv1alpha.ClusterBus: - return channelsv1alpha.SchemeGroupVersion.WithKind("ClusterBus") - - // Feeds - case *feedsv1alpha.ClusterEventType: - return feedsv1alpha.SchemeGroupVersion.WithKind("ClusterEventType") - case *feedsv1alpha.ClusterEventSource: - return feedsv1alpha.SchemeGroupVersion.WithKind("ClusterEventSource") - case *feedsv1alpha.EventType: - return feedsv1alpha.SchemeGroupVersion.WithKind("EventType") - case *feedsv1alpha.EventSource: - return feedsv1alpha.SchemeGroupVersion.WithKind("EventSource") - - // Flows - case *flowsv1alpha.Flow: - return flowsv1alpha.SchemeGroupVersion.WithKind("Flow") - - // Eventing - case *eventingv1alpha.Source: - return eventingv1alpha.SchemeGroupVersion.WithKind("Source") - case *eventingv1alpha.Channel: - return eventingv1alpha.SchemeGroupVersion.WithKind("Channel") - case *eventingv1alpha.ClusterProvisioner: - return eventingv1alpha.SchemeGroupVersion.WithKind("ClusterProvisioner") - case *eventingv1alpha.Subscription: - return eventingv1alpha.SchemeGroupVersion.WithKind("Subscription") - - default: - panic(fmt.Sprintf("Unsupported object type %T", obj)) - } -} - -// NewControllerRef creates an OwnerReference pointing to the given Resource. -func NewControllerRef(obj metav1.Object, blockOwnerDeletion bool) *metav1.OwnerReference { - ref := metav1.NewControllerRef(obj, kind(obj)) - ref.BlockOwnerDeletion = &blockOwnerDeletion - return ref -} diff --git a/pkg/controller/util/bus_util.go b/pkg/controller/util/bus_util.go deleted file mode 100644 index 0b6f72b9dbd..00000000000 --- a/pkg/controller/util/bus_util.go +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2018 The Knative 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 util - -import ( - "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - "k8s.io/api/core/v1" - meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// NewBusCondition creates a new bus condition with the provided values and both times set to now(). -func NewBusCondition(condType v1alpha1.BusConditionType, status v1.ConditionStatus, reason, message string) *v1alpha1.BusCondition { - return &v1alpha1.BusCondition{ - Type: condType, - Status: status, - LastUpdateTime: meta_v1.Now(), - LastTransitionTime: meta_v1.Now(), - Reason: reason, - Message: message, - } -} - -// GetBusCondition returns the bus condition with the provided type. -func GetBusCondition(status v1alpha1.BusStatus, condType v1alpha1.BusConditionType) *v1alpha1.BusCondition { - for i := range status.Conditions { - c := status.Conditions[i] - if c.Type == condType { - return &c - } - } - return nil -} - -// SetBusCondition updates the bus status to include the provided condition. If the condition that -// we are about to add already exists and has the same status and reason then no update happens. -func SetBusCondition(status *v1alpha1.BusStatus, condition v1alpha1.BusCondition) { - currentCond := GetBusCondition(*status, condition.Type) - if currentCond != nil && currentCond.Status == condition.Status && currentCond.Reason == condition.Reason { - return - } - // Do not update lastTransitionTime if the status of the condition doesn't change. - if currentCond != nil && currentCond.Status == condition.Status { - condition.LastTransitionTime = currentCond.LastTransitionTime - } - newConditions := filterOutBusCondition(status.Conditions, condition.Type) - status.Conditions = append(newConditions, condition) -} - -// RemoveBusCondition removes the bus condition with the provided type. -func RemoveBusCondition(status *v1alpha1.BusStatus, condType v1alpha1.BusConditionType) { - status.Conditions = filterOutBusCondition(status.Conditions, condType) -} - -// ConsolidateBusCondition computes and sets the overall "Ready" condition of the bus -// given all other sub-conditions. -func ConsolidateBusCondition(bus v1alpha1.GenericBus) { - dispatching := GetBusCondition(*bus.GetStatus(), v1alpha1.BusDispatching) - provisioning := GetBusCondition(*bus.GetStatus(), v1alpha1.BusProvisioning) - serviceable := GetBusCondition(*bus.GetStatus(), v1alpha1.BusServiceable) - needsProvitioner := bus.GetSpec().Provisioner != nil - - var cond *v1alpha1.BusCondition - - if dispatching != nil && dispatching.Status == v1.ConditionTrue && - serviceable != nil && serviceable.Status == v1.ConditionTrue && - ((provisioning != nil && provisioning.Status == v1.ConditionTrue) || !needsProvitioner) { - cond = NewBusCondition(v1alpha1.BusReady, v1.ConditionTrue, "", "") - } else { - cond = NewBusCondition(v1alpha1.BusReady, v1.ConditionFalse, "", "") - } - SetBusCondition(bus.GetStatus(), *cond) -} - -// IsBusReady returns whether all readiness conditions of a bus are met, as a boolean. -func IsBusReady(status *v1alpha1.BusStatus) bool { - c := GetBusCondition(*status, v1alpha1.BusReady) - return c != nil && c.Status == v1.ConditionTrue -} - -// filterOutBusCondition returns a new slice of bus conditions without conditions with the provided type. -func filterOutBusCondition(conditions []v1alpha1.BusCondition, condType v1alpha1.BusConditionType) []v1alpha1.BusCondition { - var newConditions []v1alpha1.BusCondition - for _, c := range conditions { - if c.Type == condType { - continue - } - newConditions = append(newConditions, c) - } - return newConditions -} diff --git a/pkg/controller/util/channel_util.go b/pkg/controller/util/channel_util.go deleted file mode 100644 index 2fbce0caca0..00000000000 --- a/pkg/controller/util/channel_util.go +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2018 The Knative 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 util - -import ( - "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - "k8s.io/api/core/v1" - meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// NewChannelCondition creates a new channel condition with the provided values and both times set to now(). -func NewChannelCondition(condType v1alpha1.ChannelConditionType, status v1.ConditionStatus, reason, message string) *v1alpha1.ChannelCondition { - return &v1alpha1.ChannelCondition{ - Type: condType, - Status: status, - LastUpdateTime: meta_v1.Now(), - LastTransitionTime: meta_v1.Now(), - Reason: reason, - Message: message, - } -} - -// GetChannelCondition returns the channel condition with the provided type. -func GetChannelCondition(status v1alpha1.ChannelStatus, condType v1alpha1.ChannelConditionType) *v1alpha1.ChannelCondition { - for i := range status.Conditions { - c := status.Conditions[i] - if c.Type == condType { - return &c - } - } - return nil -} - -// SetChannelCondition updates the channel status to include the provided condition. If the condition that -// we are about to add already exists and has the same status and reason then no update happens. -func SetChannelCondition(status *v1alpha1.ChannelStatus, condition v1alpha1.ChannelCondition) { - currentCond := GetChannelCondition(*status, condition.Type) - if currentCond != nil && currentCond.Status == condition.Status && currentCond.Reason == condition.Reason { - return - } - // Do not update lastTransitionTime if the status of the condition doesn't change. - if currentCond != nil && currentCond.Status == condition.Status { - condition.LastTransitionTime = currentCond.LastTransitionTime - } - newConditions := filterOutChannelCondition(status.Conditions, condition.Type) - status.Conditions = append(newConditions, condition) -} - -// RemoveChannelCondition removes the channel condition with the provided type. -func RemoveChannelCondition(status *v1alpha1.ChannelStatus, condType v1alpha1.ChannelConditionType) { - status.Conditions = filterOutChannelCondition(status.Conditions, condType) -} - -// ConsolidateChannelCondition computes and sets the overall "Ready" condition of the channel -// given all other sub-conditions. -func ConsolidateChannelCondition(status *v1alpha1.ChannelStatus) { - subConditionsTypes := []v1alpha1.ChannelConditionType{ - v1alpha1.ChannelProvisioned, - v1alpha1.ChannelRoutable, - v1alpha1.ChannelServiceable, - } - cond := NewChannelCondition(v1alpha1.ChannelReady, v1.ConditionTrue, "", "") - for _, t := range subConditionsTypes { - if c := GetChannelCondition(*status, t); c == nil || c.Status != v1.ConditionTrue { - cond.Status = v1.ConditionFalse - break - } - } - - SetChannelCondition(status, *cond) -} - -// IsChannelReady returns whether all readiness conditions of a channel are met, as a boolean. -func IsChannelReady(status *v1alpha1.ChannelStatus) bool { - c := GetChannelCondition(*status, v1alpha1.ChannelReady) - return c != nil && c.Status == v1.ConditionTrue -} - -// filterOutChannelCondition returns a new slice of channel conditions without conditions with the provided type. -func filterOutChannelCondition(conditions []v1alpha1.ChannelCondition, condType v1alpha1.ChannelConditionType) []v1alpha1.ChannelCondition { - var newConditions []v1alpha1.ChannelCondition - for _, c := range conditions { - if c.Type == condType { - continue - } - newConditions = append(newConditions, c) - } - return newConditions -} diff --git a/pkg/controller/util/stub_test.go b/pkg/controller/util/stub_test.go deleted file mode 100644 index 0fe9390462c..00000000000 --- a/pkg/controller/util/stub_test.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright 2018 The Knative 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 util - -import "testing" - -func TestStub(t *testing.T) { - // TODO: Implement tests in this directory, please. - // This file is used to make code coverage on this directly count. -} diff --git a/pkg/controller/util/subscription_util.go b/pkg/controller/util/subscription_util.go deleted file mode 100644 index d3db0ed6cc2..00000000000 --- a/pkg/controller/util/subscription_util.go +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2018 The Knative 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 util - -import ( - "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - "k8s.io/api/core/v1" - meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// NewSubscriptionCondition creates a new subscription condition with the provided values and both times set to now(). -func NewSubscriptionCondition(condType v1alpha1.SubscriptionConditionType, status v1.ConditionStatus, reason, message string) *v1alpha1.SubscriptionCondition { - return &v1alpha1.SubscriptionCondition{ - Type: condType, - Status: status, - LastUpdateTime: meta_v1.Now(), - LastTransitionTime: meta_v1.Now(), - Reason: reason, - Message: message, - } -} - -// GetSubscriptionCondition returns the subscription condition with the provided type. -func GetSubscriptionCondition(status v1alpha1.SubscriptionStatus, condType v1alpha1.SubscriptionConditionType) *v1alpha1.SubscriptionCondition { - for i := range status.Conditions { - c := status.Conditions[i] - if c.Type == condType { - return &c - } - } - return nil -} - -// SetSubscriptionCondition updates the subscription status to include the provided condition. If the condition that -// we are about to add already exists and has the same status and reason then no update happens. -func SetSubscriptionCondition(status *v1alpha1.SubscriptionStatus, condition v1alpha1.SubscriptionCondition) { - currentCond := GetSubscriptionCondition(*status, condition.Type) - if currentCond != nil && currentCond.Status == condition.Status && currentCond.Reason == condition.Reason { - return - } - // Do not update lastTransitionTime if the status of the condition doesn't change. - if currentCond != nil && currentCond.Status == condition.Status { - condition.LastTransitionTime = currentCond.LastTransitionTime - } - newConditions := filterOutSubscriptionCondition(status.Conditions, condition.Type) - status.Conditions = append(newConditions, condition) -} - -// RemoveSubscriptionCondition removes the subscription condition with the provided type. -func RemoveSubscriptionCondition(status *v1alpha1.SubscriptionStatus, condType v1alpha1.SubscriptionConditionType) { - status.Conditions = filterOutSubscriptionCondition(status.Conditions, condType) -} - -// filterOutSubscriptionCondition returns a new slice of subscription conditions without conditions with the provided type. -func filterOutSubscriptionCondition(conditions []v1alpha1.SubscriptionCondition, condType v1alpha1.SubscriptionConditionType) []v1alpha1.SubscriptionCondition { - var newConditions []v1alpha1.SubscriptionCondition - for _, c := range conditions { - if c.Type == condType { - continue - } - newConditions = append(newConditions, c) - } - return newConditions -} diff --git a/pkg/event/event_test.go b/pkg/event/event_test.go deleted file mode 100644 index 710fa1a7719..00000000000 --- a/pkg/event/event_test.go +++ /dev/null @@ -1,264 +0,0 @@ -/* -Copyright 2018 The Knative 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 event_test - -import ( - "encoding/json" - "encoding/xml" - "errors" - "fmt" - "io/ioutil" - "net/http" - "reflect" - "strings" - "testing" - "time" - - "github.com/knative/eventing/pkg/event" -) - -type FirestoreDocument struct { - Name string `json:"name"` - Fields map[string]interface{} `json:"fields"` - CreateTime time.Time `json:"createTime"` - UpdateTime time.Time `json:"updateTime"` -} - -var ( - webhook = "http://localhost/:sendEvent" -) - -// Wrap the global functions in an HTTPMarshaller interface for table-driven testing: -type defaultMarshaller int - -var Default defaultMarshaller = 0 - -func (defaultMarshaller) FromRequest(data interface{}, r *http.Request) (*event.EventContext, error) { - return event.FromRequest(data, r) -} -func (defaultMarshaller) NewRequest(urlString string, data interface{}, context event.EventContext) (*http.Request, error) { - return event.NewRequest(urlString, data, context) -} - -func TestValidRoundTrips(t *testing.T) { - doc := FirestoreDocument{ - Name: "projects/demo/databases/default/documents/users/inlined", - Fields: map[string]interface{}{ - "project": "eventing", - "handle": "@inlined", - }, - CreateTime: time.Date(1985, 6, 5, 12, 0, 0, 0, time.UTC), - UpdateTime: time.Now().UTC(), - } - - service := "firestore.googleapis.com" - - context := &event.EventContext{ - CloudEventsVersion: "0.1", - EventID: "eventid-123", - EventTime: doc.UpdateTime, - EventType: "google.firestore.document.create", - EventTypeVersion: "v1beta2", - SchemaURL: "http://type.googleapis.com/google.firestore.v1beta1.Document", - ContentType: "application/json", - Source: fmt.Sprintf("//%s/%s", service, doc.Name), - Extensions: map[string]interface{}{ - "purpose": "tbd", - }, - } - for _, test := range []struct { - name string - encoder event.HTTPMarshaller - decoder event.HTTPMarshaller - }{ - { - name: "binary -> binary", - encoder: event.Binary, - decoder: event.Binary, - }, - { - name: "binary -> default", - encoder: event.Binary, - decoder: Default, - }, - { - name: "structured -> structured", - encoder: event.Structured, - decoder: event.Structured, - }, - { - name: "structured -> default", - encoder: event.Structured, - decoder: Default, - }, - } { - t.Run(test.name, func(t *testing.T) { - req, err := test.encoder.NewRequest(webhook, doc, *context) - if err != nil { - t.Fatalf("Failed to encode event %s", err) - } - - var foundData FirestoreDocument - foundContext, err := test.decoder.FromRequest(&foundData, req) - if err != nil { - t.Fatalf("Failed to decode event %s", err) - } - - if !reflect.DeepEqual(context, foundContext) { - t.Fatalf("Context was transcoded lossily: expected=%+v got=%+v", context, foundContext) - } - if !reflect.DeepEqual(doc, foundData) { - t.Fatalf("Data was transcoded lossily: expected=%+v got=%+v", doc, foundData) - } - }) - } -} - -type Address struct { - City, State string -} -type Person struct { - XMLName xml.Name `xml:"person"` - Id int `xml:"id,attr"` - FirstName string `xml:"name>first"` - LastName string `xml:"name>last"` - Age int `xml:"age"` - Height float32 `xml:"height,omitempty"` - Married bool - Address - Comment string `xml:",comment"` -} - -func (Person) MarshalJSON() ([]byte, error) { - return nil, errors.New("Person cannot be JSON encoded") -} - -func (*Person) UnmarshalJSON([]byte) error { - return errors.New("Person cannot be JSON decoded") -} - -func TestXmlStructuredDecoding(t *testing.T) { - person := &Person{ - XMLName: xml.Name{ - Local: "person", - }, - Id: 13, - FirstName: "John", - LastName: "Doe", - Age: 42, - Comment: " Need more details. ", - Address: Address{"Hanga Roa", "Easter Island"}, - } - - xmlPerson := ` - - - John - Doe - - 42 - false - Hanga Roa - Easter Island - - ` - xmlJsonSafe, err := json.Marshal(xmlPerson) - if err != nil { - t.Fatalf("Failed to create JSON encoded XML string: %s", err) - } - - eventText := ` - { - "eventID": "1234", - "eventType": "dev.eventing.test", - "source": "tests://TextXmlStructuredEncoding", - "contentType": "application/xml", - "data": ` + string(xmlJsonSafe) + ` - }` - - h := http.Header{} - h.Set(event.HeaderContentType, event.ContentTypeStructuredJSON) - req := &http.Request{ - Header: h, - Body: ioutil.NopCloser(strings.NewReader(eventText)), - } - - var foundPerson Person - _, err = event.FromRequest(&foundPerson, req) - if err != nil { - t.Fatalf("Failed to parse cross-encoded request: %s", err) - } - - if !reflect.DeepEqual(person, &foundPerson) { - t.Fatalf("Failed to parse xml-encoded data; wanted=%+v; got=%+v", person, foundPerson) - } -} - -func TestExtensionsAreNeverNil(t *testing.T) { - r := &http.Request{ - Header: http.Header{ - event.HeaderContentType: []string{event.ContentTypeStructuredJSON}, - }, - Body: ioutil.NopCloser(strings.NewReader(` - { - "eventID": "1234", - "eventType": "dev.eventing.test", - "source": "tests://TextXmlStructuredEncoding", - "data": "hello, world" - }`)), - } - - var data interface{} - ctx, err := event.FromRequest(&data, r) - if err != nil { - t.Fatal("Failed to parse request", err) - } - if ctx.Extensions == nil { - t.Fatal("Extensions should never be nil") - } -} - -func TestExtensionExtraction(t *testing.T) { - h := http.Header{} - h.Set(event.HeaderContentType, event.ContentTypeBinaryJSON) - h.Set(event.HeaderEventID, "1234") - h.Set(event.HeaderEventType, "dev.eventing.test") - h.Set(event.HeaderSource, "tests://TestExtensionExtraction") - h.Set("CE-X-Prop1", "value1") - h.Set("CE-X-Prop2", `{"nestedProp":"nestedValue"}`) - b := strings.NewReader(`{"hello": "world"}`) - - r := &http.Request{ - Header: h, - Body: ioutil.NopCloser(b), - } - var data interface{} - ctx, err := event.FromRequest(&data, r) - if err != nil { - t.Fatal("Failed to parse request", err) - } - - expectedExtensions := map[string]interface{}{ - "Prop1": "value1", - "Prop2": map[string]interface{}{ - "nestedProp": "nestedValue", - }, - } - if !reflect.DeepEqual(expectedExtensions, ctx.Extensions) { - t.Fatalf("Did not parse expected extensions. Wanted=%v; got=%v", expectedExtensions, ctx.Extensions) - } -} diff --git a/pkg/event/handler_test.go b/pkg/event/handler_test.go deleted file mode 100644 index 994c3e83cbc..00000000000 --- a/pkg/event/handler_test.go +++ /dev/null @@ -1,461 +0,0 @@ -/* -Copyright 2018 The Knative 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 event_test - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "reflect" - "strings" - "testing" - "time" - - "github.com/davecgh/go-spew/spew" - "github.com/knative/eventing/pkg/event" -) - -func TestHandlerTypeErrors(t *testing.T) { - for _, test := range []struct { - name string - param interface{} - err string - }{ - { - name: "non-func", - param: 5, - err: "Must pass a function to handle events", - }, - { - name: "wrong param count", - param: func(context.Context, interface{}, interface{}) {}, - err: "Expected a function taking either no parameters, a context.Context, or (context.Context, any); function has too many parameters (3)", - }, - { - name: "wrong first parameter type", - param: func(int) {}, - err: "Expected a function taking either no parameters, a context.Context, or (context.Context, any); cannot convert parameter 0 from int to context.Context", - }, - { - name: "wrong return count", - param: func() (interface{}, error, interface{}) { return nil, nil, nil }, - err: "Expected a function returning either nothing, an error, or (any, error); function has too many return types (3)", - }, - { - name: "invalid return type", - param: func() interface{} { return nil }, - err: "Expected a function returning either nothing, an error, or (any, error); cannot convert return type 0 from interface {} to error", - }, - } { - t.Run(test.name, func(t *testing.T) { - h := event.Handler(test.param) - err, ok := h.(error) - if !ok { - t.Fatalf("Expected Handler() to fail with %v, passed", test.err) - } - if !strings.Contains(err.Error(), test.err) { - t.Errorf("Expected Handler() to fail. want %q, got %v", test.err, err) - } - - // Attempt to call the returned Handler to verify it fails. - srv := httptest.NewServer(h) - defer srv.Close() - type E struct{} - req, err := event.NewRequest(srv.URL, E{}, event.EventContext{ - EventID: "1", EventType: "a", Source: "one"}) - if err != nil { - t.Errorf("Couldn't construct request: %v", err) - } - if resp, err := srv.Client().Do(req); err != nil { - t.Errorf("Failed to Post event: %v", resp) - } else if resp.StatusCode != http.StatusNotImplemented { - t.Errorf("Expected error status. got %d, got %d", resp.StatusCode, http.StatusNotImplemented) - } - }) - } -} - -func TestHandlerValidTypes(t *testing.T) { - for _, test := range []struct { - name string - f interface{} - }{ - { - name: "no in, no out", - f: func() {}, - }, { - name: "one in, no out", - f: func(context.Context) {}, - }, { - name: "interface in, no out", - f: func(context.Context, io.Reader) {}, - }, { - name: "value-type in, no out", - f: func(context.Context, int) {}, - }, { - name: "pointer-type in, no out", - f: func(context.Context, *int) {}, - }, { - name: "no in, one out", - f: func() error { return nil }, - }, { - name: "one in, one out", - f: func(context.Context) error { return nil }, - }, { - name: "two in, one out", - f: func(context.Context, string) error { return nil }, - }, { - name: "no in, two out", - f: func() (string, error) { return "", nil }, - }, { - name: "one in, two out", - f: func(context.Context) (map[string]interface{}, error) { return nil, nil }, - }, { - name: "two in, two out", - f: func(context.Context, io.Reader) (interface{}, error) { return nil, nil }, - }, - } { - t.Run(test.name, func(t *testing.T) { - if err, ok := event.Handler(test.f).(error); ok { - t.Errorf("%q failed: %v", test.name, err) - } - }) - } -} - -func TestParameterMarsahlling(t *testing.T) { - type Data struct { - Message string - } - expectedData := Data{Message: "Hello, world!"} - expectedContext := &event.EventContext{ - CloudEventsVersion: event.CloudEventsVersion, - EventID: "1234", - Source: "tests:TestUndtypedHandling", - EventType: "dev.eventing.test", - EventTime: time.Now().UTC(), - ContentType: "application/json", - Extensions: map[string]interface{}{}, - } - var wasCalled = false - for _, marshaller := range []struct { - name string - val event.HTTPMarshaller - }{ - { - name: "structured", - val: event.Structured, - }, { - name: "binary", - val: event.Binary, - }, - } { - for _, test := range []struct { - name string - generator func(t *testing.T) http.Handler - }{ - { - name: "no parameters", - generator: func(t *testing.T) http.Handler { - return event.Handler(func() { - wasCalled = true - }) - }, - }, - { - name: "one parameter", - generator: func(t *testing.T) http.Handler { - return event.Handler(func(ctx context.Context) { - eventContext := event.FromContext(ctx) - if !reflect.DeepEqual(expectedContext, eventContext) { - t.Fatalf("Did not get expected context; wanted=%s; got=%s", spew.Sdump(expectedContext), spew.Sdump(eventContext)) - } - wasCalled = true - }) - }, - }, { - name: "two parameters (struct type)", - generator: func(t *testing.T) http.Handler { - return event.Handler(func(ctx context.Context, data Data) { - eventContext := event.FromContext(ctx) - if !reflect.DeepEqual(expectedContext, eventContext) { - t.Fatalf("Did not get expected context; wanted=%s; got=%s", spew.Sdump(expectedContext), spew.Sdump(eventContext)) - } - if !reflect.DeepEqual(expectedData, data) { - t.Fatalf("Did not get expected data; wanted=%s; got=%s", spew.Sdump(expectedData), spew.Sdump(data)) - } - wasCalled = true - }) - }, - }, { - name: "two parameters (pointer type)", - generator: func(t *testing.T) http.Handler { - return event.Handler(func(ctx context.Context, data *Data) { - eventContext := event.FromContext(ctx) - if !reflect.DeepEqual(expectedContext, eventContext) { - t.Fatalf("Did not get expected context; wanted=%s; got=%s", spew.Sdump(expectedContext), spew.Sdump(eventContext)) - } - if !reflect.DeepEqual(expectedData, *data) { - t.Fatalf("Did not get expected data; wanted=%s; got=%s", spew.Sdump(&expectedData), spew.Sdump(data)) - } - wasCalled = true - }) - }, - }, { - name: "two parameters (untyped)", - generator: func(t *testing.T) http.Handler { - return event.Handler(func(ctx context.Context, data map[string]interface{}) { - eventContext := event.FromContext(ctx) - if !reflect.DeepEqual(expectedContext, eventContext) { - t.Fatalf("Did not get expected context; wanted=%s; got=%s", spew.Sdump(expectedContext), spew.Sdump(eventContext)) - } - b, err := json.Marshal(expectedData) - if err != nil { - t.Fatal("Failed to serialize expected data", err) - } - var expectedUntyped map[string]interface{} - err = json.Unmarshal(b, &expectedUntyped) - if err != nil { - t.Fatal("Failed to deserialize expected data", err) - } - if !reflect.DeepEqual(expectedUntyped, data) { - t.Fatalf("Did not get expected data; wanted=%s; got=%s", spew.Sdump(expectedUntyped), spew.Sdump(data)) - } - wasCalled = true - }) - }, - }, - } { - t.Run(fmt.Sprintf("%s: %s", marshaller.name, test.name), func(t *testing.T) { - wasCalled = false - handler := test.generator(t) - if err, ok := handler.(error); ok { - t.Errorf("Handler() failed: %v", err) - return - } - srv := httptest.NewServer(handler) - defer srv.Close() - req, err := marshaller.val.NewRequest(srv.URL, expectedData, *expectedContext) - if err != nil { - t.Fatal("Failed to marshal request ", err) - } - res, err := srv.Client().Do(req) - if err != nil { - t.Fatal("Failed to send request") - } - if res.StatusCode/100 != 2 { - t.Fatal("Got non-successful response: ", res.StatusCode) - } - if !wasCalled { - t.Fatal("Handler was never called") - } - }) - } - } -} - -func TestReturnTypeRendering(t *testing.T) { - eventData := map[string]interface{}{ - "unused": "data", - } - type RetVal struct { - ID interface{} - } - eventContext := event.EventContext{ - CloudEventsVersion: event.CloudEventsVersion, - EventID: "1234", - Source: "tests:TestUndtypedHandling", - EventType: "dev.eventing.test", - Extensions: map[string]interface{}{}, - } - for _, test := range []struct { - name string - expectedStatus int - expectedResponse string - handler http.Handler - }{ - { - name: "no return", - expectedStatus: http.StatusNoContent, - handler: event.Handler(func() {}), - }, { - name: "nil error return", - expectedStatus: http.StatusNoContent, - handler: event.Handler(func() error { - return nil - }), - }, { - name: "non-nil error return (one return type)", - expectedStatus: http.StatusInternalServerError, - handler: event.Handler(func() error { - return errors.New("Some error") - }), - expectedResponse: "Internal server error", - }, { - name: "successful return", - expectedStatus: http.StatusOK, - handler: event.Handler(func() (map[string]interface{}, error) { - return map[string]interface{}{"hello": "world"}, nil - }), - expectedResponse: `{"hello":"world"}`, - }, { - name: "non-nil error return (two return types)", - expectedStatus: http.StatusInternalServerError, - handler: event.Handler(func() (map[string]interface{}, error) { - return map[string]interface{}{"hello": "world"}, errors.New("Errors take precedence") - }), - expectedResponse: "Internal server error", - }, - { - name: "non-nil content return", - expectedStatus: http.StatusOK, - handler: event.Handler(func() (map[string]interface{}, error) { - return map[string]interface{}{"hello": "world"}, nil - }), - expectedResponse: `{"hello":"world"}`, - }, - { - name: "bad JSON content", - expectedStatus: http.StatusInternalServerError, - handler: event.Handler(func() (RetVal, error) { - return RetVal{ID: func() {}}, nil - }), - }, - } { - t.Run(test.name, func(t *testing.T) { - if err, ok := test.handler.(error); ok { - t.Errorf("Handler() failed: %v", err) - return - } - srv := httptest.NewServer(test.handler) - defer srv.Close() - req, err := event.NewRequest(srv.URL, eventData, eventContext) - if err != nil { - t.Fatal("Failed to marshal request ", err) - } - res, err := srv.Client().Do(req) - if err != nil { - t.Fatal("Failed to send request") - } - defer res.Body.Close() - if test.expectedStatus != res.StatusCode { - t.Fatalf("Wrong status code from event handler; wanted=%d; got=%d", test.expectedStatus, res.StatusCode) - } - if test.expectedResponse != "" { - b, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Fatal("Failed to read response body:", err) - } - resBody := string(b) - if test.expectedResponse != resBody { - t.Fatalf("Got unexpected respnose string; wanted=%q; got=%q", test.expectedResponse, resBody) - } - } - }) - } -} - -func TestMux(t *testing.T) { - type TypeA struct { - Greeting string - } - type TypeB struct { - Farewell string - } - - eventA := TypeA{ - Greeting: "Hello, world!", - } - eventB := TypeB{ - Farewell: "Hasta la vista", - } - - contextA := &event.EventContext{ - EventID: "1234", - EventType: "org.A.test", - Source: "test:TestMux", - ContentType: "application/json", - Extensions: map[string]interface{}{}, - } - contextB := &event.EventContext{ - EventID: "5678", - EventType: "org.B.test", - Source: "test:TestMux", - ContentType: "application/json", - Extensions: map[string]interface{}{}, - } - sawA, sawB := false, false - - mux := event.NewMux() - err := mux.Handle("org.A.test", func(ctx context.Context, data TypeA) error { - sawA = true - context := event.FromContext(ctx) - if !reflect.DeepEqual(eventA, data) { - t.Fatalf("Got wrong data for event A; wanted=%s; got=%s", eventA, data) - } - if !reflect.DeepEqual(contextA, context) { - t.Fatalf("Got wrong context for event A; wanted=%s; got=%s", contextA, context) - } - return nil - }) - if err != nil { - t.Fatalf("mux.Handle('org.A.test') failed: %v", err) - } - err = mux.Handle("org.B.test", func(ctx context.Context, data TypeB) error { - sawB = true - context := event.FromContext(ctx) - if !reflect.DeepEqual(eventB, data) { - t.Fatalf("Got wrong data for event A; wanted=%s; got=%s", eventB, data) - } - if !reflect.DeepEqual(contextB, context) { - t.Fatalf("Got wrong context for event A; wanted=%s; got=%s", contextB, context) - } - return nil - }) - if err != nil { - t.Fatalf("mux.Handle('org.B.test') failed: %v", err) - } - - srv := httptest.NewServer(mux) - defer srv.Close() - req, err := event.NewRequest(srv.URL, eventA, *contextA) - if err != nil { - t.Fatal("Failed to marshal request for eventA", err) - } - if _, err := srv.Client().Do(req); err != nil { - t.Fatal("Failed to send eventA", err) - } - req, err = event.NewRequest(srv.URL, eventB, *contextB) - if err != nil { - t.Fatal("Failed to marshal request for eventB", err) - } - if _, err := srv.Client().Do(req); err != nil { - t.Fatal("Failed to send eventB", err) - } - - if !sawA { - t.Fatal("Handler for eventA never called") - } - if !sawB { - t.Fatal("Handler for eventB never called") - } -} diff --git a/pkg/provisioners/channel_util.go b/pkg/provisioners/channel_util.go new file mode 100644 index 00000000000..165ed49cea4 --- /dev/null +++ b/pkg/provisioners/channel_util.go @@ -0,0 +1,191 @@ +package provisioners + +import ( + "context" + + istiov1alpha3 "github.com/knative/pkg/apis/istio/v1alpha3" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/sets" + runtimeClient "sigs.k8s.io/controller-runtime/pkg/client" + + eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + "github.com/knative/eventing/pkg/controller" + "github.com/knative/eventing/pkg/system" + "k8s.io/apimachinery/pkg/api/equality" +) + +const ( + PortName = "http" + PortNumber = 80 +) + +func AddFinalizer(c *eventingv1alpha1.Channel, finalizerName string) { + finalizers := sets.NewString(c.Finalizers...) + finalizers.Insert(finalizerName) + c.Finalizers = finalizers.List() +} + +func RemoveFinalizer(c *eventingv1alpha1.Channel, finalizerName string) { + finalizers := sets.NewString(c.Finalizers...) + finalizers.Delete(finalizerName) + c.Finalizers = finalizers.List() +} + +func getK8sService(ctx context.Context, client runtimeClient.Client, c *eventingv1alpha1.Channel) (*corev1.Service, error) { + svcKey := types.NamespacedName{ + Namespace: c.Namespace, + Name: controller.ChannelServiceName(c.Name), + } + svc := &corev1.Service{} + err := client.Get(ctx, svcKey, svc) + return svc, err +} + +func CreateK8sService(ctx context.Context, client runtimeClient.Client, c *eventingv1alpha1.Channel) (*corev1.Service, error) { + svc, err := getK8sService(ctx, client, c) + + if errors.IsNotFound(err) { + svc = newK8sService(c) + err = client.Create(ctx, svc) + } + + // If an error occurred in either Get or Create, we need to reconcile again. + if err != nil { + return nil, err + } + + return svc, nil +} + +func getVirtualService(ctx context.Context, client runtimeClient.Client, c *eventingv1alpha1.Channel) (*istiov1alpha3.VirtualService, error) { + vsk := runtimeClient.ObjectKey{ + Namespace: c.Namespace, + Name: controller.ChannelVirtualServiceName(c.ObjectMeta.Name), + } + vs := &istiov1alpha3.VirtualService{} + err := client.Get(ctx, vsk, vs) + return vs, err +} + +func CreateVirtualService(ctx context.Context, client runtimeClient.Client, c *eventingv1alpha1.Channel) (*istiov1alpha3.VirtualService, error) { + virtualService, err := getVirtualService(ctx, client, c) + + // If the resource doesn't exist, we'll create it + if errors.IsNotFound(err) { + virtualService = newVirtualService(c) + err = client.Create(ctx, virtualService) + } + + // If an error occurs during Get/Create, we'll requeue the item so we can + // attempt processing again later. This could have been caused by a + // temporary network failure, or any other transient reason. + if err != nil { + return nil, err + } + + return virtualService, nil +} + +func UpdateChannel(ctx context.Context, client runtimeClient.Client, u *eventingv1alpha1.Channel) error { + channel := &eventingv1alpha1.Channel{} + err := client.Get(ctx, runtimeClient.ObjectKey{Namespace: u.Namespace, Name: u.Name}, channel) + if err != nil { + return err + } + + updated := false + if !equality.Semantic.DeepEqual(channel.Finalizers, u.Finalizers) { + channel.SetFinalizers(u.ObjectMeta.Finalizers) + updated = true + } + + if !equality.Semantic.DeepEqual(channel.Status, u.Status) { + channel.Status = u.Status + updated = true + } + + if updated { + return client.Update(ctx, channel) + } + return nil +} + +// newK8sService creates a new Service for a Channel resource. It also sets the appropriate +// OwnerReferences on the resource so handleObject can discover the Channel resource that 'owns' it. +// As well as being garbage collected when the Channel is deleted. +func newK8sService(c *eventingv1alpha1.Channel) *corev1.Service { + labels := map[string]string{ + "channel": c.Name, + "provisioner": c.Spec.Provisioner.Name, + } + return &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{ + Name: controller.ChannelServiceName(c.ObjectMeta.Name), + Namespace: c.Namespace, + Labels: labels, + OwnerReferences: []metav1.OwnerReference{ + *metav1.NewControllerRef(c, schema.GroupVersionKind{ + Group: eventingv1alpha1.SchemeGroupVersion.Group, + Version: eventingv1alpha1.SchemeGroupVersion.Version, + Kind: "Channel", + }), + }, + }, + Spec: corev1.ServiceSpec{ + Ports: []corev1.ServicePort{ + { + Name: PortName, + Port: PortNumber, + }, + }, + }, + } +} + +// newVirtualService creates a new VirtualService for a Channel resource. It also sets the +// appropriate OwnerReferences on the resource so handleObject can discover the Channel resource +// that 'owns' it. As well as being garbage collected when the Channel is deleted. +func newVirtualService(channel *eventingv1alpha1.Channel) *istiov1alpha3.VirtualService { + labels := map[string]string{ + "channel": channel.Name, + "provisioner": channel.Spec.Provisioner.Name, + } + destinationHost := controller.ServiceHostName(controller.ClusterBusDispatcherServiceName(channel.Spec.Provisioner.Name), system.Namespace) + return &istiov1alpha3.VirtualService{ + ObjectMeta: metav1.ObjectMeta{ + Name: controller.ChannelVirtualServiceName(channel.Name), + Namespace: channel.Namespace, + Labels: labels, + OwnerReferences: []metav1.OwnerReference{ + *metav1.NewControllerRef(channel, schema.GroupVersionKind{ + Group: eventingv1alpha1.SchemeGroupVersion.Group, + Version: eventingv1alpha1.SchemeGroupVersion.Version, + Kind: "Channel", + }), + }, + }, + Spec: istiov1alpha3.VirtualServiceSpec{ + Hosts: []string{ + controller.ServiceHostName(controller.ChannelServiceName(channel.Name), channel.Namespace), + controller.ChannelHostName(channel.Name, channel.Namespace), + }, + Http: []istiov1alpha3.HTTPRoute{{ + Rewrite: &istiov1alpha3.HTTPRewrite{ + Authority: controller.ChannelHostName(channel.Name, channel.Namespace), + }, + Route: []istiov1alpha3.DestinationWeight{{ + Destination: istiov1alpha3.Destination{ + Host: destinationHost, + Port: istiov1alpha3.PortSelector{ + Number: PortNumber, + }, + }}, + }}, + }, + }, + } +} diff --git a/pkg/provisioners/channel_util_test.go b/pkg/provisioners/channel_util_test.go new file mode 100644 index 00000000000..0503ee778ec --- /dev/null +++ b/pkg/provisioners/channel_util_test.go @@ -0,0 +1,198 @@ +package provisioners + +import ( + "context" + "fmt" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/knative/pkg/apis" + istiov1alpha3 "github.com/knative/pkg/apis/istio/v1alpha3" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes/scheme" + runtimeClient "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" +) + +const ( + channelName = "test-channel" + testNS = "test-namespace" +) + +var ( + truePointer = true +) + +func init() { + // Add types to scheme. + istiov1alpha3.AddToScheme(scheme.Scheme) + eventingv1alpha1.AddToScheme(scheme.Scheme) +} + +func TestCreateK8sService(t *testing.T) { + want := makeK8sService() + client := fake.NewFakeClient() + got, _ := CreateK8sService(context.TODO(), client, getNewChannel()) + + ignore := cmpopts.IgnoreTypes(apis.VolatileTime{}) + if diff := cmp.Diff(want, got, ignore); diff != "" { + t.Errorf("Service (-want, +got) = %v", diff) + } +} + +func TestCreateK8sService_Existing(t *testing.T) { + want := makeK8sService() + client := fake.NewFakeClient(want) + got, _ := CreateK8sService(context.TODO(), client, getNewChannel()) + + ignore := cmpopts.IgnoreTypes(apis.VolatileTime{}) + if diff := cmp.Diff(want, got, ignore); diff != "" { + t.Errorf("Service (-want, +got) = %v", diff) + } +} + +func TestCreateVirtualService(t *testing.T) { + want := makeVirtualService() + client := fake.NewFakeClient() + got, _ := CreateVirtualService(context.TODO(), client, getNewChannel()) + + ignore := cmpopts.IgnoreTypes(apis.VolatileTime{}) + if diff := cmp.Diff(want, got, ignore); diff != "" { + t.Errorf("VirtualService (-want, +got) = %v", diff) + } +} + +func TestCreateVirtualService_Existing(t *testing.T) { + want := makeVirtualService() + client := fake.NewFakeClient(want) + got, _ := CreateVirtualService(context.TODO(), client, getNewChannel()) + + ignore := cmpopts.IgnoreTypes(apis.VolatileTime{}) + if diff := cmp.Diff(want, got, ignore); diff != "" { + t.Errorf("VirtualService (-want, +got) = %v", diff) + } +} + +func TestUpdateChannel(t *testing.T) { + oldChannel := getNewChannel() + client := fake.NewFakeClient(oldChannel) + + want := getNewChannel() + AddFinalizer(want, "test-finalizer") + want.Status.SetAddress("test-domain") + UpdateChannel(context.TODO(), client, want) + + got := &eventingv1alpha1.Channel{} + client.Get(context.TODO(), runtimeClient.ObjectKey{Namespace: testNS, Name: channelName}, got) + + ignore := cmpopts.IgnoreTypes(apis.VolatileTime{}) + if diff := cmp.Diff(want, got, ignore); diff != "" { + t.Errorf("Channel (-want, +got) = %v", diff) + } +} + +func getNewChannel() *eventingv1alpha1.Channel { + channel := &eventingv1alpha1.Channel{ + TypeMeta: channelType(), + ObjectMeta: om(testNS, channelName), + Spec: eventingv1alpha1.ChannelSpec{ + Provisioner: &corev1.ObjectReference{ + Name: clusterChannelProvisionerName, + Kind: "ClusterChannelProvisioner", + APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), + }, + }, + } + // selflink is not filled in when we create the object, so clear it + channel.ObjectMeta.SelfLink = "" + return channel +} + +func channelType() metav1.TypeMeta { + return metav1.TypeMeta{ + APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), + Kind: "Channel", + } +} +func om(namespace, name string) metav1.ObjectMeta { + return metav1.ObjectMeta{ + Namespace: namespace, + Name: name, + SelfLink: fmt.Sprintf("/apis/eventing/v1alpha1/namespaces/%s/object/%s", namespace, name), + } +} + +func makeK8sService() *corev1.Service { + return &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{ + Name: fmt.Sprintf("%s-channel", channelName), + Namespace: testNS, + Labels: map[string]string{ + "channel": channelName, + "provisioner": clusterChannelProvisionerName, + }, + OwnerReferences: []metav1.OwnerReference{ + { + APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), + Kind: "Channel", + Name: channelName, + Controller: &truePointer, + BlockOwnerDeletion: &truePointer, + }, + }, + }, + Spec: corev1.ServiceSpec{ + Ports: []corev1.ServicePort{ + { + Name: PortName, + Port: PortNumber, + }, + }, + }, + } +} + +func makeVirtualService() *istiov1alpha3.VirtualService { + return &istiov1alpha3.VirtualService{ + ObjectMeta: metav1.ObjectMeta{ + Name: fmt.Sprintf("%s-channel", channelName), + Namespace: testNS, + Labels: map[string]string{ + "channel": channelName, + "provisioner": clusterChannelProvisionerName, + }, + OwnerReferences: []metav1.OwnerReference{ + { + APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), + Kind: "Channel", + Name: channelName, + Controller: &truePointer, + BlockOwnerDeletion: &truePointer, + }, + }, + }, + Spec: istiov1alpha3.VirtualServiceSpec{ + Hosts: []string{ + fmt.Sprintf("%s-channel.%s.svc.cluster.local", channelName, testNS), + fmt.Sprintf("%s.%s.channels.cluster.local", channelName, testNS), + }, + Http: []istiov1alpha3.HTTPRoute{{ + Rewrite: &istiov1alpha3.HTTPRewrite{ + Authority: fmt.Sprintf("%s.%s.channels.cluster.local", channelName, testNS), + }, + Route: []istiov1alpha3.DestinationWeight{{ + Destination: istiov1alpha3.Destination{ + Host: fmt.Sprintf("%s-clusterbus.knative-eventing.svc.cluster.local", clusterChannelProvisionerName), + Port: istiov1alpha3.PortSelector{ + Number: PortNumber, + }, + }}, + }}, + }, + }, + } +} diff --git a/pkg/provisioners/kafka/cmd/controller/main.go b/pkg/provisioners/kafka/cmd/controller/main.go new file mode 100644 index 00000000000..9fceebdefb0 --- /dev/null +++ b/pkg/provisioners/kafka/cmd/controller/main.go @@ -0,0 +1,79 @@ +package main + +import ( + "flag" + "os" + + istiov1alpha3 "github.com/knative/pkg/apis/istio/v1alpha3" + "go.uber.org/zap" + "k8s.io/apimachinery/pkg/runtime" + _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" + "sigs.k8s.io/controller-runtime/pkg/client/config" + "sigs.k8s.io/controller-runtime/pkg/controller" + "sigs.k8s.io/controller-runtime/pkg/manager" + logf "sigs.k8s.io/controller-runtime/pkg/runtime/log" + "sigs.k8s.io/controller-runtime/pkg/runtime/signals" + + eventingv1alpha "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + "github.com/knative/eventing/pkg/provisioners" + provisionerController "github.com/knative/eventing/pkg/provisioners/kafka/controller" + "github.com/knative/eventing/pkg/provisioners/kafka/controller/channel" +) + +// SchemeFunc adds types to a Scheme. +type SchemeFunc func(*runtime.Scheme) error + +// ProvideFunc adds a controller to a Manager. +type ProvideFunc func(mgr manager.Manager, config *provisionerController.KafkaProvisionerConfig, logger *zap.Logger) (controller.Controller, error) + +func main() { + flag.Parse() + logf.SetLogger(logf.ZapLogger(false)) + + logger := provisioners.NewProvisionerLoggerFromConfig(provisioners.NewLoggingConfig()) + defer logger.Sync() + + // Setup a Manager + mgr, err := manager.New(config.GetConfigOrDie(), manager.Options{}) + if err != nil { + logger.Error(err, "unable to run controller manager") + os.Exit(1) + } + + // Add custom types to this array to get them into the manager's scheme. + schemeFuncs := []SchemeFunc{ + eventingv1alpha.AddToScheme, + istiov1alpha3.AddToScheme, + } + for _, schemeFunc := range schemeFuncs { + schemeFunc(mgr.GetScheme()) + } + + // Add each controller's ProvideController func to this list to have the + // manager run it. + providers := []ProvideFunc{ + provisionerController.ProvideController, + channel.ProvideController, + } + + // TODO the underlying config map needs to be watched and the config should be reloaded if there is a change. + provisionerConfig, err := provisionerController.GetProvisionerConfig("/etc/config-provisioner") + + if err != nil { + logger.Error(err, "unable to run controller manager") + os.Exit(1) + } + + for _, provider := range providers { + if _, err := provider(mgr, provisionerConfig, logger.Desugar()); err != nil { + logger.Error(err, "unable to run controller manager") + os.Exit(1) + } + } + + // Start blocks forever. + err = mgr.Start(signals.SetupSignalHandler()) + if err != nil { + logger.Fatal("Manager.Start() returned an error", zap.Error(err)) + } +} diff --git a/pkg/provisioners/kafka/cmd/dispatcher/main.go b/pkg/provisioners/kafka/cmd/dispatcher/main.go new file mode 100644 index 00000000000..b9a2ea866ef --- /dev/null +++ b/pkg/provisioners/kafka/cmd/dispatcher/main.go @@ -0,0 +1,99 @@ +/* +Copyright 2018 The Knative 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 + + https://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 main + +import ( + "fmt" + "log" + "os" + + "go.uber.org/zap" + "golang.org/x/sync/errgroup" + "k8s.io/client-go/kubernetes" + "sigs.k8s.io/controller-runtime/pkg/client/config" + "sigs.k8s.io/controller-runtime/pkg/manager" + "sigs.k8s.io/controller-runtime/pkg/runtime/signals" + + provisionerController "github.com/knative/eventing/pkg/provisioners/kafka/controller" + "github.com/knative/eventing/pkg/provisioners/kafka/dispatcher" + "github.com/knative/eventing/pkg/sidecar/configmap/watcher" + "github.com/knative/eventing/pkg/system" +) + +func main() { + + configMapName := os.Getenv("DISPATCHER_CONFIGMAP_NAME") + if configMapName == "" { + configMapName = provisionerController.DispatcherConfigMapName + } + configMapNamespace := os.Getenv("DISPATCHER_CONFIGMAP_NAMESPACE") + if configMapNamespace == "" { + configMapNamespace = system.Namespace + } + + logger, err := zap.NewProduction() + if err != nil { + log.Fatalf("unable to create logger: %v", err) + } + + provisionerConfig, err := provisionerController.GetProvisionerConfig("/etc/config-provisioner") + if err != nil { + logger.Fatal("unable to load provisioner config", zap.Error(err)) + } + + mgr, err := manager.New(config.GetConfigOrDie(), manager.Options{}) + if err != nil { + logger.Fatal("unable to create manager.", zap.Error(err)) + } + + kafkaDispatcher, err := dispatcher.NewDispatcher(provisionerConfig.Brokers, logger) + if err != nil { + logger.Fatal("unable to create kafka dispatcher.", zap.Error(err)) + } + + kc, err := kubernetes.NewForConfig(mgr.GetConfig()) + if err != nil { + logger.Fatal("unable to create kubernetes client.", zap.Error(err)) + } + + cmw, err := watcher.NewWatcher(logger, kc, configMapNamespace, configMapName, kafkaDispatcher.UpdateConfig) + if err != nil { + logger.Fatal("unable to create configmap watcher", zap.String("configmap", fmt.Sprintf("%s/%s", configMapNamespace, configMapName))) + } + mgr.Add(cmw) + + // set up signals so we handle the first shutdown signal gracefully + stopCh := signals.SetupSignalHandler() + + // Start both the manager (which notices ConfigMap changes) and the HTTP server. + var g errgroup.Group + g.Go(func() error { + // Start blocks forever, so run it in a goroutine. + return mgr.Start(stopCh) + }) + + g.Go(func() error { + // Setups message receiver and blocks + return kafkaDispatcher.Start(stopCh) + }) + + err = g.Wait() + if err != nil { + logger.Error("Either the kafka message receiver or the ConfigMap noticer failed.", zap.Error(err)) + } + +} diff --git a/pkg/provisioners/kafka/controller/channel/provider.go b/pkg/provisioners/kafka/controller/channel/provider.go new file mode 100644 index 00000000000..a5a220c1ad4 --- /dev/null +++ b/pkg/provisioners/kafka/controller/channel/provider.go @@ -0,0 +1,105 @@ +/* +Copyright 2018 The Knative 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 channel + +import ( + "github.com/Shopify/sarama" + istiov1alpha3 "github.com/knative/pkg/apis/istio/v1alpha3" + "go.uber.org/zap" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/tools/record" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/manager" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + "sigs.k8s.io/controller-runtime/pkg/source" + + eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + common "github.com/knative/eventing/pkg/provisioners/kafka/controller" + "github.com/knative/eventing/pkg/system" +) + +const ( + // controllerAgentName is the string used by this controller to identify + // itself when creating events. + controllerAgentName = "kafka-provisioner-channel-controller" +) + +var ( + defaultConfigMapKey = types.NamespacedName{ + Namespace: system.Namespace, + Name: common.DispatcherConfigMapName, + } +) + +type reconciler struct { + client client.Client + recorder record.EventRecorder + logger *zap.Logger + config *common.KafkaProvisionerConfig + configMapKey client.ObjectKey + // Using a shared kafkaClusterAdmin does not work currently because of an issue with + // Shopify/sarama, see https://github.com/Shopify/sarama/issues/1162. + kafkaClusterAdmin sarama.ClusterAdmin +} + +// Verify the struct implements reconcile.Reconciler +var _ reconcile.Reconciler = &reconciler{} + +// ProvideController returns a Channel controller. +func ProvideController(mgr manager.Manager, config *common.KafkaProvisionerConfig, logger *zap.Logger) (controller.Controller, error) { + // Setup a new controller to Reconcile Channel. + c, err := controller.New(controllerAgentName, mgr, controller.Options{ + Reconciler: &reconciler{ + recorder: mgr.GetRecorder(controllerAgentName), + logger: logger, + config: config, + configMapKey: defaultConfigMapKey, + }, + }) + if err != nil { + return nil, err + } + + // Watch Channel events and enqueue Channel object key. + if err := c.Watch(&source.Kind{Type: &eventingv1alpha1.Channel{}}, &handler.EnqueueRequestForObject{}); err != nil { + return nil, err + } + + // Watch the K8s Services that are owned by Channels. + err = c.Watch(&source.Kind{Type: &corev1.Service{}}, &handler.EnqueueRequestForOwner{OwnerType: &eventingv1alpha1.Channel{}, IsController: true}) + if err != nil { + logger.Error("unable to watch K8s Services.", zap.Error(err)) + return nil, err + } + + // Watch the VirtualServices that are owned by Channels. + err = c.Watch(&source.Kind{Type: &istiov1alpha3.VirtualService{}}, &handler.EnqueueRequestForOwner{OwnerType: &eventingv1alpha1.Channel{}, IsController: true}) + if err != nil { + logger.Error("unable to watch VirtualServices.", zap.Error(err)) + return nil, err + } + + return c, nil +} + +func (r *reconciler) InjectClient(c client.Client) error { + r.client = c + return nil +} diff --git a/pkg/controller/channel/stub_test.go b/pkg/provisioners/kafka/controller/channel/provider_test.go similarity index 55% rename from pkg/controller/channel/stub_test.go rename to pkg/provisioners/kafka/controller/channel/provider_test.go index a2b614a1a3b..43d7eb88cc2 100644 --- a/pkg/controller/channel/stub_test.go +++ b/pkg/provisioners/kafka/controller/channel/provider_test.go @@ -16,9 +16,24 @@ limitations under the License. package channel -import "testing" +import ( + "testing" -func TestStub(t *testing.T) { - // TODO: Implement tests in this directory, please. - // This file is used to make code coverage on this directly count. + "sigs.k8s.io/controller-runtime/pkg/client/fake" +) + +func TestInjectClient(t *testing.T) { + r := &reconciler{} + orig := r.client + n := fake.NewFakeClient() + if orig == n { + t.Errorf("Original and new clients are identical: %v", orig) + } + err := r.InjectClient(n) + if err != nil { + t.Errorf("Unexpected error injecting the client: %v", err) + } + if n != r.client { + t.Errorf("Unexpected client. Expected: '%v'. Actual: '%v'", n, r.client) + } } diff --git a/pkg/provisioners/kafka/controller/channel/reconcile.go b/pkg/provisioners/kafka/controller/channel/reconcile.go new file mode 100644 index 00000000000..c6065f13772 --- /dev/null +++ b/pkg/provisioners/kafka/controller/channel/reconcile.go @@ -0,0 +1,383 @@ +/* +Copyright 2018 The Knative 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 channel + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/Shopify/sarama" + "go.uber.org/zap" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + eventingController "github.com/knative/eventing/pkg/controller" + util "github.com/knative/eventing/pkg/provisioners" + "github.com/knative/eventing/pkg/provisioners/kafka/controller" + "github.com/knative/eventing/pkg/sidecar/configmap" + "github.com/knative/eventing/pkg/sidecar/fanout" + "github.com/knative/eventing/pkg/sidecar/multichannelfanout" + "k8s.io/apimachinery/pkg/api/equality" +) + +const ( + finalizerName = controllerAgentName + + DefaultNumPartitions = 1 +) + +type channelArgs struct { + NumPartitions int32 +} + +// Reconcile compares the actual state with the desired, and attempts to +// converge the two. It then updates the Status block of the Channel resource +// with the current status of the resource. +func (r *reconciler) Reconcile(request reconcile.Request) (reconcile.Result, error) { + ctx := context.TODO() + r.logger.Info("Reconciling channel", zap.Any("request", request)) + channel := &eventingv1alpha1.Channel{} + err := r.client.Get(context.TODO(), request.NamespacedName, channel) + + // The Channel may have been deleted since it was added to the workqueue. If so, there is + // nothing to be done since the dependent resources would have been deleted as well. + if errors.IsNotFound(err) { + r.logger.Info("could not find channel", zap.Any("request", request)) + return reconcile.Result{}, nil + } + + // Any other error should be retried in another reconciliation. + if err != nil { + r.logger.Error("could not fetch channel", zap.Error(err)) + return reconcile.Result{}, err + } + + // Skip Channel as it is not targeting any provisioner + if channel.Spec.Provisioner == nil { + return reconcile.Result{}, nil + } + + // Skip channel not managed by this provisioner + clusterChannelProvisioner, err := r.getClusterChannelProvisioner() + if err != nil { + return reconcile.Result{}, err + } + + if !r.shouldReconcile(channel, clusterChannelProvisioner) { + return reconcile.Result{}, nil + } + + newChannel := channel.DeepCopy() + + newChannel.Status.InitializeConditions() + + if clusterChannelProvisioner.Status.IsReady() { + // Reconcile this copy of the Channel and then write back any status + // updates regardless of whether the reconcile error out. + err = r.reconcile(ctx, newChannel) + } else { + newChannel.Status.MarkNotProvisioned("NotProvisioned", "ClusterChannelProvisioner %s is not ready", clusterChannelProvisioner.Name) + err = fmt.Errorf("ClusterChannelProvisioner %s is not ready", clusterChannelProvisioner.Name) + } + + if updateChannelErr := util.UpdateChannel(ctx, r.client, newChannel); updateChannelErr != nil { + r.logger.Info("failed to update channel status", zap.Error(updateChannelErr)) + return reconcile.Result{}, updateChannelErr + } + + // Requeue if the resource is not ready: + return reconcile.Result{}, err +} + +func (r *reconciler) reconcile(ctx context.Context, channel *eventingv1alpha1.Channel) error { + + // We always need to sync the Channel config, so do it first. + if err := r.syncChannelConfig(ctx); err != nil { + r.logger.Info("error updating syncing the Channel config", zap.Error(err)) + return err + } + + // We don't currently initialize r.kafkaClusterAdmin, hence we end up creating the cluster admin client every time. + // This is because of an issue with Shopify/sarama. See https://github.com/Shopify/sarama/issues/1162. + // Once the issue is fixed we should use a shared cluster admin client. Also, r.kafkaClusterAdmin is currently + // used to pass a fake admin client in the tests. + kafkaClusterAdmin := r.kafkaClusterAdmin + if kafkaClusterAdmin == nil { + var err error + kafkaClusterAdmin, err = createKafkaAdminClient(r.config) + if err != nil { + r.logger.Fatal("unable to build kafka admin client", zap.Error(err)) + return err + } + } + + // See if the channel has been deleted + accessor, err := meta.Accessor(channel) + if err != nil { + r.logger.Info("failed to get metadata", zap.Error(err)) + return err + } + deletionTimestamp := accessor.GetDeletionTimestamp() + if deletionTimestamp != nil { + r.logger.Info(fmt.Sprintf("DeletionTimestamp: %v", deletionTimestamp)) + if err := r.deprovisionChannel(channel, kafkaClusterAdmin); err != nil { + return err + } + util.RemoveFinalizer(channel, finalizerName) + return nil + } + + util.AddFinalizer(channel, finalizerName) + + if err := r.provisionChannel(channel, kafkaClusterAdmin); err != nil { + channel.Status.MarkNotProvisioned("NotProvisioned", "error while provisioning: %s", err) + return err + } + + svc, err := util.CreateK8sService(ctx, r.client, channel) + + if err != nil { + r.logger.Info("error creating the Channel's K8s Service", zap.Error(err)) + return err + } + + // Check if this Channel is the owner of the K8s service. + if !metav1.IsControlledBy(svc, channel) { + r.logger.Warn("Channel's K8s Service is not owned by the Channel", zap.Any("channel", channel), zap.Any("service", svc)) + } + + channel.Status.SetAddress(eventingController.ServiceHostName(svc.Name, svc.Namespace)) + + virtualService, err := util.CreateVirtualService(ctx, r.client, channel) + + if err != nil { + r.logger.Info("error creating the Virtual Service for the Channel", zap.Error(err)) + return err + } + + // If the Virtual Service is not controlled by this Channel, we should log a warning, but don't + // consider it an error. + if !metav1.IsControlledBy(virtualService, channel) { + r.logger.Warn("VirtualService not owned by Channel", zap.Any("channel", channel), zap.Any("virtualService", virtualService)) + } + + channel.Status.MarkProvisioned() + + // close the connection + kafkaClusterAdmin.Close() + + return nil +} + +func (r *reconciler) shouldReconcile(channel *eventingv1alpha1.Channel, clusterChannelProvisioner *eventingv1alpha1.ClusterChannelProvisioner) bool { + return channel.Spec.Provisioner.Name == clusterChannelProvisioner.Name +} + +func (r *reconciler) provisionChannel(channel *eventingv1alpha1.Channel, kafkaClusterAdmin sarama.ClusterAdmin) error { + topicName := topicName(channel) + r.logger.Info("creating topic on kafka cluster", zap.String("topic", topicName)) + + var arguments channelArgs + + if channel.Spec.Arguments != nil { + var err error + arguments, err = unmarshalArguments(channel.Spec.Arguments.Raw) + if err != nil { + return err + } + } + + if arguments.NumPartitions == 0 { + arguments.NumPartitions = DefaultNumPartitions + } + + err := kafkaClusterAdmin.CreateTopic(topicName, &sarama.TopicDetail{ + ReplicationFactor: 1, + NumPartitions: arguments.NumPartitions, + }, false) + if err == sarama.ErrTopicAlreadyExists { + return nil + } else if err != nil { + r.logger.Error("error creating topic", zap.String("topic", topicName), zap.Error(err)) + } else { + r.logger.Info("successfully created topic", zap.String("topic", topicName)) + } + return err +} + +func (r *reconciler) deprovisionChannel(channel *eventingv1alpha1.Channel, kafkaClusterAdmin sarama.ClusterAdmin) error { + topicName := topicName(channel) + r.logger.Info("deleting topic on kafka cluster", zap.String("topic", topicName)) + + err := kafkaClusterAdmin.DeleteTopic(topicName) + if err == sarama.ErrUnknownTopicOrPartition { + return nil + } else if err != nil { + r.logger.Error("error deleting topic", zap.String("topic", topicName), zap.Error(err)) + } else { + r.logger.Info("successfully deleted topic %s", zap.String("topic", topicName)) + } + return err +} + +func (r *reconciler) getClusterChannelProvisioner() (*eventingv1alpha1.ClusterChannelProvisioner, error) { + clusterChannelProvisioner := &eventingv1alpha1.ClusterChannelProvisioner{} + objKey := client.ObjectKey{ + Name: controller.Name, + } + if err := r.client.Get(context.Background(), objKey, clusterChannelProvisioner); err != nil { + return nil, err + } + return clusterChannelProvisioner, nil +} + +func (r *reconciler) syncChannelConfig(ctx context.Context) error { + channels, err := r.listAllChannels(ctx) + if err != nil { + r.logger.Info("Unable to list channels", zap.Error(err)) + return err + } + config := multiChannelFanoutConfig(channels) + return r.writeConfigMap(ctx, config) +} + +func (r *reconciler) writeConfigMap(ctx context.Context, config *multichannelfanout.Config) error { + logger := r.logger.With(zap.Any("configMap", r.configMapKey)) + + updated, err := configmap.SerializeConfig(*config) + if err != nil { + r.logger.Error("Unable to serialize config", zap.Error(err), zap.Any("config", config)) + return err + } + + cm := &corev1.ConfigMap{} + err = r.client.Get(ctx, r.configMapKey, cm) + if errors.IsNotFound(err) { + cm = r.createNewConfigMap(updated) + err = r.client.Create(ctx, cm) + if err != nil { + logger.Info("Unable to create ConfigMap", zap.Error(err)) + return err + } + } + if err != nil { + logger.Info("Unable to get ConfigMap", zap.Error(err)) + return err + } + + if equality.Semantic.DeepEqual(cm.Data, updated) { + // Nothing to update. + return nil + } + + cm.Data = updated + return r.client.Update(ctx, cm) +} + +func (r *reconciler) createNewConfigMap(data map[string]string) *corev1.ConfigMap { + return &corev1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: r.configMapKey.Namespace, + Name: r.configMapKey.Name, + }, + Data: data, + } +} + +func multiChannelFanoutConfig(channels []eventingv1alpha1.Channel) *multichannelfanout.Config { + cc := make([]multichannelfanout.ChannelConfig, 0) + for _, c := range channels { + channelConfig := multichannelfanout.ChannelConfig{ + Namespace: c.Namespace, + Name: c.Name, + } + if c.Spec.Subscribable != nil { + channelConfig.FanoutConfig = fanout.Config{ + Subscriptions: c.Spec.Subscribable.Subscribers, + } + } + cc = append(cc, channelConfig) + } + return &multichannelfanout.Config{ + ChannelConfigs: cc, + } +} + +func (r *reconciler) listAllChannels(ctx context.Context) ([]eventingv1alpha1.Channel, error) { + clusterChannelProvisioner, err := r.getClusterChannelProvisioner() + if err != nil { + return nil, err + } + + channels := make([]eventingv1alpha1.Channel, 0) + + opts := &client.ListOptions{ + // TODO this is here because the fake client needs it. Remove this when it's no longer + // needed. + Raw: &metav1.ListOptions{ + TypeMeta: metav1.TypeMeta{ + APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), + Kind: "Channel", + }, + }, + } + for { + cl := &eventingv1alpha1.ChannelList{} + if err := r.client.List(ctx, opts, cl); err != nil { + return nil, err + } + + for _, c := range cl.Items { + if r.shouldReconcile(&c, clusterChannelProvisioner) { + channels = append(channels, c) + } + } + if cl.Continue != "" { + opts.Raw.Continue = cl.Continue + } else { + return channels, nil + } + } +} + +func createKafkaAdminClient(config *controller.KafkaProvisionerConfig) (sarama.ClusterAdmin, error) { + saramaConf := sarama.NewConfig() + saramaConf.Version = sarama.V1_1_0_0 + saramaConf.ClientID = controllerAgentName + return sarama.NewClusterAdmin(config.Brokers, saramaConf) +} + +func topicName(channel *eventingv1alpha1.Channel) string { + return fmt.Sprintf("%s.%s", channel.Namespace, channel.Name) +} + +// unmarshalArguments unmarshal's a json/yaml serialized input and returns channelArgs +func unmarshalArguments(bytes []byte) (channelArgs, error) { + var arguments channelArgs + if len(bytes) > 0 { + if err := json.Unmarshal(bytes, &arguments); err != nil { + return arguments, fmt.Errorf("error unmarshalling arguments: %s", err) + } + } + return arguments, nil +} diff --git a/pkg/provisioners/kafka/controller/channel/reconcile_test.go b/pkg/provisioners/kafka/controller/channel/reconcile_test.go new file mode 100644 index 00000000000..fd2422f87ab --- /dev/null +++ b/pkg/provisioners/kafka/controller/channel/reconcile_test.go @@ -0,0 +1,547 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Veroute.on 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 channel + +import ( + "context" + "encoding/json" + "fmt" + "testing" + + "github.com/Shopify/sarama" + "github.com/google/go-cmp/cmp" + duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" + istiov1alpha3 "github.com/knative/pkg/apis/istio/v1alpha3" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/tools/record" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + controllertesting "github.com/knative/eventing/pkg/controller/testing" + "github.com/knative/eventing/pkg/provisioners" + util "github.com/knative/eventing/pkg/provisioners" + "github.com/knative/eventing/pkg/provisioners/kafka/controller" +) + +const ( + channelName = "test-channel" + clusterChannelProvisionerName = "kafka-channel" + testNS = "test-namespace" + testUID = "test-uid" + argumentNumPartitions = "NumPartitions" +) + +var ( + truePointer = true + + deletedTs = metav1.Now().Rfc3339Copy() +) + +func init() { + // Add types to scheme + eventingv1alpha1.AddToScheme(scheme.Scheme) + istiov1alpha3.AddToScheme(scheme.Scheme) +} + +var mockFetchError = controllertesting.Mocks{ + MockGets: []controllertesting.MockGet{ + func(innerClient client.Client, ctx context.Context, key client.ObjectKey, obj runtime.Object) (controllertesting.MockHandled, error) { + if _, ok := obj.(*eventingv1alpha1.Channel); ok { + err := fmt.Errorf("error fetching") + return controllertesting.Handled, err + } + return controllertesting.Unhandled, nil + }, + }, +} + +type mockClusterAdmin struct { + mockCreateTopicFunc func(topic string, detail *sarama.TopicDetail, validateOnly bool) error + mockDeleteTopicFunc func(topic string) error +} + +func (ca *mockClusterAdmin) CreateTopic(topic string, detail *sarama.TopicDetail, validateOnly bool) error { + if ca.mockCreateTopicFunc != nil { + return ca.mockCreateTopicFunc(topic, detail, validateOnly) + } + return nil +} + +func (ca *mockClusterAdmin) Close() error { + return nil +} + +func (ca *mockClusterAdmin) DeleteTopic(topic string) error { + if ca.mockDeleteTopicFunc != nil { + return ca.mockDeleteTopicFunc(topic) + } + return nil +} + +func (ca *mockClusterAdmin) CreatePartitions(topic string, count int32, assignment [][]int32, validateOnly bool) error { + return nil +} + +func (ca *mockClusterAdmin) DeleteRecords(topic string, partitionOffsets map[int32]int64) error { + return nil +} + +func (ca *mockClusterAdmin) DescribeConfig(resource sarama.ConfigResource) ([]sarama.ConfigEntry, error) { + return nil, nil +} + +func (ca *mockClusterAdmin) AlterConfig(resourceType sarama.ConfigResourceType, name string, entries map[string]*string, validateOnly bool) error { + return nil +} + +func (ca *mockClusterAdmin) CreateACL(resource sarama.Resource, acl sarama.Acl) error { + return nil +} + +func (ca *mockClusterAdmin) ListAcls(filter sarama.AclFilter) ([]sarama.ResourceAcls, error) { + return nil, nil +} + +func (ca *mockClusterAdmin) DeleteACL(filter sarama.AclFilter, validateOnly bool) ([]sarama.MatchingAcl, error) { + return nil, nil +} + +var testCases = []controllertesting.TestCase{ + { + Name: "new channel with valid provisioner: adds provisioned status", + InitialState: []runtime.Object{ + getNewClusterChannelProvisioner(clusterChannelProvisionerName, true), + getNewChannel(channelName, clusterChannelProvisionerName), + makeVirtualService(), + }, + ReconcileKey: fmt.Sprintf("%s/%s", testNS, channelName), + WantResult: reconcile.Result{}, + WantPresent: []runtime.Object{ + getNewChannelProvisionedStatus(channelName, clusterChannelProvisionerName), + }, + IgnoreTimes: true, + }, + { + Name: "new channel with provisioner not ready: error", + InitialState: []runtime.Object{ + getNewClusterChannelProvisioner(clusterChannelProvisionerName, false), + getNewChannel(channelName, clusterChannelProvisionerName), + }, + ReconcileKey: fmt.Sprintf("%s/%s", testNS, channelName), + WantResult: reconcile.Result{}, + WantErrMsg: "ClusterChannelProvisioner " + clusterChannelProvisionerName + " is not ready", + WantPresent: []runtime.Object{ + getNewChannelNotProvisionedStatus(channelName, clusterChannelProvisionerName, + "ClusterChannelProvisioner "+clusterChannelProvisionerName+" is not ready"), + }, + IgnoreTimes: true, + }, + { + Name: "new channel with missing provisioner: error", + InitialState: []runtime.Object{ + getNewChannel(channelName, clusterChannelProvisionerName), + }, + ReconcileKey: fmt.Sprintf("%s/%s", testNS, channelName), + WantResult: reconcile.Result{}, + WantErrMsg: "clusterchannelprovisioners.eventing.knative.dev \"" + clusterChannelProvisionerName + "\" not found", + IgnoreTimes: true, + }, + { + Name: "new channel with provisioner not managed by this controller: skips channel", + InitialState: []runtime.Object{ + getNewChannel(channelName, "not-our-provisioner"), + getNewClusterChannelProvisioner("not-our-provisioner", true), + getNewClusterChannelProvisioner(clusterChannelProvisionerName, true), + }, + ReconcileKey: fmt.Sprintf("%s/%s", testNS, channelName), + WantResult: reconcile.Result{}, + WantPresent: []runtime.Object{ + getNewChannel(channelName, "not-our-provisioner"), + }, + IgnoreTimes: true, + }, + { + Name: "new channel with missing provisioner reference: skips channel", + InitialState: []runtime.Object{ + getNewChannelNoProvisioner(channelName), + }, + ReconcileKey: fmt.Sprintf("%s/%s", testNS, channelName), + WantResult: reconcile.Result{}, + WantPresent: []runtime.Object{ + getNewChannelNoProvisioner(channelName), + }, + IgnoreTimes: true, + }, + { + Name: "channel not found", + InitialState: []runtime.Object{}, + ReconcileKey: fmt.Sprintf("%s/%s", testNS, channelName), + WantResult: reconcile.Result{}, + WantPresent: []runtime.Object{}, + IgnoreTimes: true, + }, + { + Name: "error fetching channel", + InitialState: []runtime.Object{ + getNewClusterChannelProvisioner(clusterChannelProvisionerName, true), + getNewChannel(channelName, clusterChannelProvisionerName), + }, + Mocks: mockFetchError, + ReconcileKey: fmt.Sprintf("%s/%s", testNS, channelName), + WantErrMsg: "error fetching", + WantPresent: []runtime.Object{ + getNewClusterChannelProvisioner(clusterChannelProvisionerName, true), + getNewChannel(channelName, clusterChannelProvisionerName), + }, + }, + { + Name: "deleted channel", + InitialState: []runtime.Object{ + getNewClusterChannelProvisioner(clusterChannelProvisionerName, true), + getNewChannelDeleted(channelName, clusterChannelProvisionerName), + }, + ReconcileKey: fmt.Sprintf("%s/%s", testNS, channelName), + WantResult: reconcile.Result{}, + WantPresent: []runtime.Object{}, + IgnoreTimes: true, + }, +} + +func TestAllCases(t *testing.T) { + recorder := record.NewBroadcaster().NewRecorder(scheme.Scheme, corev1.EventSource{Component: controllerAgentName}) + + for _, tc := range testCases { + c := tc.GetClient() + logger := provisioners.NewProvisionerLoggerFromConfig(provisioners.NewLoggingConfig()) + r := &reconciler{ + client: c, + recorder: recorder, + logger: logger.Desugar(), + config: getControllerConfig(), + kafkaClusterAdmin: &mockClusterAdmin{}, + } + t.Logf("Running test %s", tc.Name) + t.Run(tc.Name, tc.Runner(t, r, c)) + } +} + +func TestProvisionChannel(t *testing.T) { + provisionTestCases := []struct { + name string + c *eventingv1alpha1.Channel + wantTopicName string + wantTopicDetail *sarama.TopicDetail + mockError error + wantError string + }{ + { + name: "provision with no channel arguments - uses default", + c: getNewChannel(channelName, clusterChannelProvisionerName), + wantTopicName: fmt.Sprintf("%s.%s", testNS, channelName), + wantTopicDetail: &sarama.TopicDetail{ + ReplicationFactor: 1, + NumPartitions: 1, + }, + }, + { + name: "provision with unknown channel arguments - uses default", + c: getNewChannelWithArgs(channelName, map[string]interface{}{"testing": "testing"}), + wantTopicName: fmt.Sprintf("%s.%s", testNS, channelName), + wantTopicDetail: &sarama.TopicDetail{ + ReplicationFactor: 1, + NumPartitions: 1, + }, + }, + { + name: "provision with invalid channel arguments - errors", + c: getNewChannelWithArgs(channelName, map[string]interface{}{argumentNumPartitions: "invalid"}), + wantError: fmt.Sprintf("error unmarshalling arguments: json: cannot unmarshal string into Go struct field channelArgs.%s of type int32", argumentNumPartitions), + }, + { + name: "provision with unmarshallable channel arguments - errors", + c: func() *eventingv1alpha1.Channel { + channel := getNewChannel(channelName, clusterChannelProvisionerName) + channel.Spec.Arguments = &runtime.RawExtension{ + Raw: []byte("invalid"), + } + return channel + }(), + wantError: "error unmarshalling arguments: invalid character 'i' looking for beginning of value", + }, + { + name: "provision with valid channel arguments", + c: getNewChannelWithArgs(channelName, map[string]interface{}{argumentNumPartitions: 2}), + wantTopicName: fmt.Sprintf("%s.%s", testNS, channelName), + wantTopicDetail: &sarama.TopicDetail{ + ReplicationFactor: 1, + NumPartitions: 2, + }, + }, + { + name: "provision but topic already exists - no error", + c: getNewChannelWithArgs(channelName, map[string]interface{}{argumentNumPartitions: 2}), + wantTopicName: fmt.Sprintf("%s.%s", testNS, channelName), + wantTopicDetail: &sarama.TopicDetail{ + ReplicationFactor: 1, + NumPartitions: 2, + }, + mockError: sarama.ErrTopicAlreadyExists, + }, + { + name: "provision but error creating topic", + c: getNewChannelWithArgs(channelName, map[string]interface{}{argumentNumPartitions: 2}), + wantTopicName: fmt.Sprintf("%s.%s", testNS, channelName), + wantTopicDetail: &sarama.TopicDetail{ + ReplicationFactor: 1, + NumPartitions: 2, + }, + mockError: fmt.Errorf("unknown sarama error"), + wantError: "unknown sarama error", + }} + + for _, tc := range provisionTestCases { + t.Logf("running test %s", tc.name) + logger := provisioners.NewProvisionerLoggerFromConfig(provisioners.NewLoggingConfig()) + r := &reconciler{ + logger: logger.Desugar(), + } + kafkaClusterAdmin := &mockClusterAdmin{ + mockCreateTopicFunc: func(topic string, detail *sarama.TopicDetail, validateOnly bool) error { + if topic != tc.wantTopicName { + t.Errorf("expected topic name: %+v got: %+v", tc.wantTopicName, topic) + } + return tc.mockError + }} + err := r.provisionChannel(tc.c, kafkaClusterAdmin) + var got string + if err != nil { + got = err.Error() + } + if diff := cmp.Diff(tc.wantError, got); diff != "" { + t.Errorf("unexpected error (-want, +got) = %v", diff) + } + } +} + +func TestDeprovisionChannel(t *testing.T) { + deprovisionTestCases := []struct { + name string + c *eventingv1alpha1.Channel + wantTopicName string + mockError error + wantError string + }{ + { + name: "deprovision channel - unknown error", + c: getNewChannel(channelName, clusterChannelProvisionerName), + wantTopicName: fmt.Sprintf("%s.%s", testNS, channelName), + mockError: fmt.Errorf("unknown sarama error"), + wantError: "unknown sarama error", + }, + { + name: "deprovision channel - topic already deleted", + c: getNewChannel(channelName, clusterChannelProvisionerName), + wantTopicName: fmt.Sprintf("%s.%s", testNS, channelName), + mockError: sarama.ErrUnknownTopicOrPartition, + }, + { + name: "deprovision channel - success", + c: getNewChannel(channelName, clusterChannelProvisionerName), + wantTopicName: fmt.Sprintf("%s.%s", testNS, channelName), + }} + + for _, tc := range deprovisionTestCases { + t.Logf("running test %s", tc.name) + logger := provisioners.NewProvisionerLoggerFromConfig(provisioners.NewLoggingConfig()) + r := &reconciler{ + logger: logger.Desugar()} + kafkaClusterAdmin := &mockClusterAdmin{ + mockDeleteTopicFunc: func(topic string) error { + if topic != tc.wantTopicName { + t.Errorf("expected topic name: %+v got: %+v", tc.wantTopicName, topic) + } + return tc.mockError + }} + + err := r.deprovisionChannel(tc.c, kafkaClusterAdmin) + var got string + if err != nil { + got = err.Error() + } + if diff := cmp.Diff(tc.wantError, got); diff != "" { + t.Errorf("unexpected error (-want, +got) = %v", diff) + } + } +} + +func getNewChannelNoProvisioner(name string) *eventingv1alpha1.Channel { + channel := &eventingv1alpha1.Channel{ + TypeMeta: channelType(), + ObjectMeta: om(testNS, name), + Spec: eventingv1alpha1.ChannelSpec{}, + } + // selflink is not filled in when we create the object, so clear it + channel.ObjectMeta.SelfLink = "" + return channel +} + +func getNewChannel(name, provisioner string) *eventingv1alpha1.Channel { + channel := &eventingv1alpha1.Channel{ + TypeMeta: channelType(), + ObjectMeta: om(testNS, name), + Spec: eventingv1alpha1.ChannelSpec{ + Provisioner: &corev1.ObjectReference{ + Name: provisioner, + Kind: "ClusterChannelProvisioner", + APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), + }, + }, + } + // selflink is not filled in when we create the object, so clear it + channel.ObjectMeta.SelfLink = "" + return channel +} + +func getNewChannelWithArgs(name string, args map[string]interface{}) *eventingv1alpha1.Channel { + c := getNewChannelNoProvisioner(name) + bytes, _ := json.Marshal(args) + c.Spec.Arguments = &runtime.RawExtension{ + Raw: bytes, + } + return c +} + +func getNewChannelProvisionedStatus(name, provisioner string) *eventingv1alpha1.Channel { + c := getNewChannel(name, provisioner) + c.Status.InitializeConditions() + c.Status.SetAddress(fmt.Sprintf("%s-channel.%s.svc.cluster.local", c.Name, c.Namespace)) + c.Status.MarkProvisioned() + c.Finalizers = []string{finalizerName} + return c +} + +func getNewChannelDeleted(name, provisioner string) *eventingv1alpha1.Channel { + c := getNewChannelProvisionedStatus(name, provisioner) + c.DeletionTimestamp = &deletedTs + return c +} + +func getNewChannelNotProvisionedStatus(name, provisioner, msg string) *eventingv1alpha1.Channel { + c := getNewChannel(name, provisioner) + c.Status.InitializeConditions() + c.Status.MarkNotProvisioned("NotProvisioned", msg) + return c +} + +func channelType() metav1.TypeMeta { + return metav1.TypeMeta{ + APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), + Kind: "Channel", + } +} + +func getNewClusterChannelProvisioner(name string, isReady bool) *eventingv1alpha1.ClusterChannelProvisioner { + var condStatus corev1.ConditionStatus + if isReady { + condStatus = corev1.ConditionTrue + } else { + condStatus = corev1.ConditionFalse + } + clusterChannelProvisioner := &eventingv1alpha1.ClusterChannelProvisioner{ + TypeMeta: metav1.TypeMeta{ + APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), + Kind: "ClusterChannelProvisioner", + }, + ObjectMeta: om("", name), + Spec: eventingv1alpha1.ClusterChannelProvisionerSpec{}, + Status: eventingv1alpha1.ClusterChannelProvisionerStatus{ + Conditions: []duckv1alpha1.Condition{ + { + Type: eventingv1alpha1.ClusterChannelProvisionerConditionReady, + Status: condStatus, + }, + }, + }, + } + // selflink is not filled in when we create the object, so clear it + clusterChannelProvisioner.ObjectMeta.SelfLink = "" + return clusterChannelProvisioner +} + +func makeVirtualService() *istiov1alpha3.VirtualService { + return &istiov1alpha3.VirtualService{ + TypeMeta: metav1.TypeMeta{ + APIVersion: istiov1alpha3.SchemeGroupVersion.String(), + Kind: "VirtualService", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: fmt.Sprintf("%s-channel", testNS), + Namespace: testNS, + Labels: map[string]string{ + "channel": channelName, + "provisioner": clusterChannelProvisionerName, + }, + OwnerReferences: []metav1.OwnerReference{ + { + APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), + Kind: "Channel", + Name: channelName, + UID: testUID, + Controller: &truePointer, + BlockOwnerDeletion: &truePointer, + }, + }, + }, + Spec: istiov1alpha3.VirtualServiceSpec{ + Hosts: []string{ + fmt.Sprintf("%s-channel.%s.svc.cluster.local", channelName, testNS), + fmt.Sprintf("%s.%s.channels.cluster.local", channelName, testNS), + }, + Http: []istiov1alpha3.HTTPRoute{{ + Rewrite: &istiov1alpha3.HTTPRewrite{ + Authority: fmt.Sprintf("%s.%s.channels.cluster.local", channelName, testNS), + }, + Route: []istiov1alpha3.DestinationWeight{{ + Destination: istiov1alpha3.Destination{ + Host: "kafka-provisioner.knative-eventing.svc.cluster.local", + Port: istiov1alpha3.PortSelector{ + Number: util.PortNumber, + }, + }}, + }}, + }, + }, + } +} + +func om(namespace, name string) metav1.ObjectMeta { + return metav1.ObjectMeta{ + Namespace: namespace, + Name: name, + SelfLink: fmt.Sprintf("/apis/eventing/v1alpha1/namespaces/%s/object/%s", namespace, name), + } +} + +func getControllerConfig() *controller.KafkaProvisionerConfig { + return &controller.KafkaProvisionerConfig{ + Brokers: []string{"test-broker"}, + } +} diff --git a/pkg/controller/eventtype/provider.go b/pkg/provisioners/kafka/controller/provider.go similarity index 51% rename from pkg/controller/eventtype/provider.go rename to pkg/provisioners/kafka/controller/provider.go index 04adfdfca2b..0f6ca5631f2 100644 --- a/pkg/controller/eventtype/provider.go +++ b/pkg/provisioners/kafka/controller/provider.go @@ -14,13 +14,11 @@ See the License for the specific language governing permissions and limitations under the License. */ -package eventtype +package controller import ( - feedsv1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" "go.uber.org/zap" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/rest" + corev1 "k8s.io/api/core/v1" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller" @@ -28,54 +26,54 @@ import ( "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" + + "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" ) const ( // controllerAgentName is the string used by this controller to identify // itself when creating events. - controllerAgentName = "event-type-controller" + controllerAgentName = "kafka-provisioner-controller" + // ConfigMapName is the name of the ConfigMap in the knative-eventing namespace that contains + // the subscription information for all kafka Channels. The Provisioner writes to it and the + // Dispatcher reads from it. + DispatcherConfigMapName = "kafka-channel-dispatcher" ) type reconciler struct { - client client.Client - restConfig *rest.Config - recorder record.EventRecorder - logger *zap.Logger + client client.Client + recorder record.EventRecorder + logger *zap.Logger + config *KafkaProvisionerConfig } // Verify the struct implements reconcile.Reconciler var _ reconcile.Reconciler = &reconciler{} -// ProvideController returns a flow controller. -func ProvideController(mgr manager.Manager) (controller.Controller, error) { - logger, err := zap.NewProduction() - if err != nil { - return nil, err - } - logger.With(zap.String("controller", controllerAgentName)) - - // Setup a new controller to Reconcile Flows. +// ProvideController returns a Provisioner controller. +func ProvideController(mgr manager.Manager, config *KafkaProvisionerConfig, logger *zap.Logger) (controller.Controller, error) { + // Setup a new controller to Reconcile Provisioners. c, err := controller.New(controllerAgentName, mgr, controller.Options{ Reconciler: &reconciler{ recorder: mgr.GetRecorder(controllerAgentName), - logger: logger, + logger: logger, + config: config, }, }) if err != nil { return nil, err } - // Watch EventType events and enqueue EventType object key. - if err := c.Watch(&source.Kind{ - Type: &feedsv1alpha1.EventType{}}, - &handler.EnqueueRequestForObject{}); err != nil { + // Watch ClusterChannelProvisioner events and enqueue ClusterChannelProvisioner object key. + if err := c.Watch(&source.Kind{Type: &v1alpha1.ClusterChannelProvisioner{}}, &handler.EnqueueRequestForObject{}); err != nil { return nil, err } - // In addition to watching EventType objects, watch for Feeds, which use and 'pin' EventTypes. - err = c.Watch(&source.Kind{Type: &feedsv1alpha1.Feed{}}, - &handler.EnqueueRequestsFromMapFunc{ToRequests: feedToEventType{}}) + // Watch the K8s Services that are owned by ClusterChannelProvisioners. + err = c.Watch(&source.Kind{Type: &corev1.Service{}}, &handler.EnqueueRequestForOwner{OwnerType: &eventingv1alpha1.ClusterChannelProvisioner{}, IsController: true}) if err != nil { + logger.Error("unable to watch K8s Services.", zap.Error(err)) return nil, err } @@ -86,23 +84,3 @@ func (r *reconciler) InjectClient(c client.Client) error { r.client = c return nil } - -type feedToEventType struct{} - -func (_ feedToEventType) Map(obj handler.MapObject) []reconcile.Request { - feed, ok := obj.Object.(*feedsv1alpha1.Feed) - if !ok { - // This wasn't a Feed. - return []reconcile.Request{} - } - etName := feed.Spec.Trigger.EventType - - return []reconcile.Request{ - { - NamespacedName: types.NamespacedName{ - Namespace: obj.Meta.GetNamespace(), - Name: etName, - }, - }, - } -} diff --git a/pkg/apis/channels/v1alpha1/clusterbus_validation.go b/pkg/provisioners/kafka/controller/provider_test.go similarity index 55% rename from pkg/apis/channels/v1alpha1/clusterbus_validation.go rename to pkg/provisioners/kafka/controller/provider_test.go index 2d95941948b..9b648acba67 100644 --- a/pkg/apis/channels/v1alpha1/clusterbus_validation.go +++ b/pkg/provisioners/kafka/controller/provider_test.go @@ -14,17 +14,26 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1alpha1 +package controller import ( - "github.com/knative/pkg/apis" -) + "testing" -func (b *ClusterBus) Validate() *apis.FieldError { - return b.Spec.Validate().ViaField("spec") -} + "sigs.k8s.io/controller-runtime/pkg/client/fake" +) -func (current *ClusterBus) CheckImmutableFields(og apis.Immutable) *apis.FieldError { - // TODO(n3wscott): Anything to check? - return nil +func TestInjectClient(t *testing.T) { + r := &reconciler{} + orig := r.client + n := fake.NewFakeClient() + if orig == n { + t.Errorf("Original and new clients are identical: %v", orig) + } + err := r.InjectClient(n) + if err != nil { + t.Errorf("Unexpected error injecting the client: %v", err) + } + if n != r.client { + t.Errorf("Unexpected client. Expected: '%v'. Actual: '%v'", n, r.client) + } } diff --git a/pkg/provisioners/kafka/controller/reconcile.go b/pkg/provisioners/kafka/controller/reconcile.go new file mode 100644 index 00000000000..ff7be5c9fda --- /dev/null +++ b/pkg/provisioners/kafka/controller/reconcile.go @@ -0,0 +1,113 @@ +/* +Copyright 2018 The Knative 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 controller + +import ( + "context" + "fmt" + + "go.uber.org/zap" + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + util "github.com/knative/eventing/pkg/provisioners" +) + +const ( + // Name is the name of the kafka ClusterChannelProvisioner. + Name = "kafka-channel" +) + +// Reconcile compares the actual state with the desired, and attempts to +// converge the two. It then updates the Status block of the Provisioner resource +// with the current status of the resource. +func (r *reconciler) Reconcile(request reconcile.Request) (reconcile.Result, error) { + ctx := context.TODO() + r.logger.Info("reconciling ClusterChannelProvisioner", zap.Any("request", request)) + provisioner := &v1alpha1.ClusterChannelProvisioner{} + err := r.client.Get(context.TODO(), request.NamespacedName, provisioner) + + if errors.IsNotFound(err) { + r.logger.Info("could not find ClusterChannelProvisioner", zap.Any("request", request)) + return reconcile.Result{}, nil + } + + if err != nil { + r.logger.Error("could not fetch ClusterChannelProvisioner", zap.Error(err)) + return reconcile.Result{}, err + } + + // Skip channel provisioners that we don't manage + if provisioner.Name != Name { + r.logger.Info("not reconciling ClusterChannelProvisioner, it is not controlled by this Controller", zap.Any("request", request)) + return reconcile.Result{}, nil + } + + newProvisioner := provisioner.DeepCopy() + + // Reconcile this copy of the Provisioner and then write back any status + // updates regardless of whether the reconcile error out. + err = r.reconcile(ctx, newProvisioner) + if err != nil { + r.logger.Info("error reconciling ClusterProvisioner", zap.Error(err)) + // Note that we do not return the error here, because we want to update the Status + // regardless of the error. + } + if updateStatusErr := util.UpdateClusterChannelProvisionerStatus(ctx, r.client, newProvisioner); updateStatusErr != nil { + r.logger.Info("error updating ClusterChannelProvisioner Status", zap.Error(updateStatusErr)) + return reconcile.Result{}, updateStatusErr + } + + // Requeue if the resource is not ready: + return reconcile.Result{}, err +} + +func (r *reconciler) reconcile(ctx context.Context, provisioner *v1alpha1.ClusterChannelProvisioner) error { + // See if the provisioner has been deleted + accessor, err := meta.Accessor(provisioner) + if err != nil { + r.logger.Info("failed to get metadata", zap.Error(err)) + return err + } + deletionTimestamp := accessor.GetDeletionTimestamp() + if deletionTimestamp != nil { + r.logger.Info(fmt.Sprintf("DeletionTimestamp: %v", deletionTimestamp)) + return nil + } + + provisioner.Status.InitializeConditions() + + svc, err := util.CreateDispatcherService(ctx, r.client, provisioner) + if err != nil { + r.logger.Info("error creating the ClusterProvisioner's K8s Service", zap.Error(err)) + return err + } + + // Check if this ClusterChannelProvisioner is the owner of the K8s service. + if !metav1.IsControlledBy(svc, provisioner) { + r.logger.Warn("ClusterChannelProvisioner's K8s Service is not owned by the ClusterChannelProvisioner", zap.Any("clusterChannelProvisioner", provisioner), zap.Any("service", svc)) + } + + // Update Status as Ready + provisioner.Status.MarkReady() + + return nil +} diff --git a/pkg/provisioners/kafka/controller/reconcile_test.go b/pkg/provisioners/kafka/controller/reconcile_test.go new file mode 100644 index 00000000000..ebe66418b1d --- /dev/null +++ b/pkg/provisioners/kafka/controller/reconcile_test.go @@ -0,0 +1,189 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Veroute.on 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 controller + +import ( + "context" + "fmt" + "testing" + + eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + controllertesting "github.com/knative/eventing/pkg/controller/testing" + "github.com/knative/eventing/pkg/provisioners" + duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/tools/record" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/reconcile" +) + +const ( + clusterChannelProvisionerName = "kafka-channel" + testNS = "" +) + +func init() { + // Add types to scheme + eventingv1alpha1.AddToScheme(scheme.Scheme) +} + +var ClusterChannelProvisionerConditionReady = duckv1alpha1.Condition{ + Type: eventingv1alpha1.ClusterChannelProvisionerConditionReady, + Status: corev1.ConditionTrue, + Severity: duckv1alpha1.ConditionSeverityError, +} + +var mockFetchError = controllertesting.Mocks{ + MockGets: []controllertesting.MockGet{ + func(innerClient client.Client, ctx context.Context, key client.ObjectKey, obj runtime.Object) (controllertesting.MockHandled, error) { + if _, ok := obj.(*eventingv1alpha1.ClusterChannelProvisioner); ok { + err := fmt.Errorf("error fetching") + return controllertesting.Handled, err + } + return controllertesting.Unhandled, nil + }, + }, +} + +var testCases = []controllertesting.TestCase{ + { + Name: "new channel clusterChannelProvisioner: adds status", + InitialState: []runtime.Object{ + GetNewChannelClusterChannelProvisioner(clusterChannelProvisionerName), + }, + ReconcileKey: fmt.Sprintf("%s/%s", testNS, clusterChannelProvisionerName), + WantResult: reconcile.Result{}, + WantPresent: []runtime.Object{ + GetNewChannelClusterChannelProvisionerReady(clusterChannelProvisionerName), + }, + IgnoreTimes: true, + }, + { + Name: "reconciles only associated provisioner", + InitialState: []runtime.Object{ + GetNewChannelClusterChannelProvisioner("not-default-provisioner"), + }, + ReconcileKey: fmt.Sprintf("%s/%s", testNS, "not-default-provisioner"), + WantResult: reconcile.Result{}, + WantPresent: []runtime.Object{ + GetNewChannelClusterChannelProvisioner("not-default-provisioner"), + }, + }, + { + Name: "clusterChannelProvisioner not found", + InitialState: []runtime.Object{}, + ReconcileKey: fmt.Sprintf("%s/%s", testNS, clusterChannelProvisionerName), + WantResult: reconcile.Result{}, + WantPresent: []runtime.Object{}, + }, + { + Name: "error fetching clusterChannelProvisioner", + InitialState: []runtime.Object{ + GetNewChannelClusterChannelProvisioner(clusterChannelProvisionerName), + }, + Mocks: mockFetchError, + ReconcileKey: fmt.Sprintf("%s/%s", testNS, clusterChannelProvisionerName), + WantErrMsg: "error fetching", + WantPresent: []runtime.Object{ + GetNewChannelClusterChannelProvisioner(clusterChannelProvisionerName), + }, + }, + { + Name: "deleted clusterChannelProvisioner", + InitialState: []runtime.Object{ + GetNewChannelClusterChannelProvisionerDeleted(clusterChannelProvisionerName), + }, + ReconcileKey: fmt.Sprintf("%s/%s", testNS, clusterChannelProvisionerName), + WantResult: reconcile.Result{}, + WantPresent: []runtime.Object{ + GetNewChannelClusterChannelProvisionerDeleted(clusterChannelProvisionerName), + }, + }, +} + +func TestAllCases(t *testing.T) { + recorder := record.NewBroadcaster().NewRecorder(scheme.Scheme, corev1.EventSource{Component: controllerAgentName}) + + for _, tc := range testCases { + c := tc.GetClient() + logger := provisioners.NewProvisionerLoggerFromConfig(provisioners.NewLoggingConfig()) + r := &reconciler{ + client: c, + recorder: recorder, + logger: logger.Desugar(), + config: getControllerConfig(), + } + t.Logf("Running test %s", tc.Name) + t.Run(tc.Name, tc.Runner(t, r, c)) + } +} + +func GetNewChannelClusterChannelProvisioner(name string) *eventingv1alpha1.ClusterChannelProvisioner { + return getNewClusterChannelProvisioner(name, "Channel") +} + +func getNewClusterChannelProvisioner(name string, reconcileKind string) *eventingv1alpha1.ClusterChannelProvisioner { + clusterChannelProvisioner := &eventingv1alpha1.ClusterChannelProvisioner{ + TypeMeta: ClusterProvisonerType(), + ObjectMeta: om(testNS, name), + Spec: eventingv1alpha1.ClusterChannelProvisionerSpec{}, + } + // selflink is not filled in when we create the object, so clear it + clusterChannelProvisioner.ObjectMeta.SelfLink = "" + return clusterChannelProvisioner +} + +func GetNewChannelClusterChannelProvisionerReady(name string) *eventingv1alpha1.ClusterChannelProvisioner { + c := GetNewChannelClusterChannelProvisioner(name) + c.Status = eventingv1alpha1.ClusterChannelProvisionerStatus{ + Conditions: []duckv1alpha1.Condition{ + ClusterChannelProvisionerConditionReady, + }, + } + return c +} + +func GetNewChannelClusterChannelProvisionerDeleted(name string) *eventingv1alpha1.ClusterChannelProvisioner { + c := GetNewChannelClusterChannelProvisioner(name) + deletedTime := metav1.Now().Rfc3339Copy() + c.DeletionTimestamp = &deletedTime + return c +} + +func ClusterProvisonerType() metav1.TypeMeta { + return metav1.TypeMeta{ + APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), + Kind: "ClusterChannelProvisioner", + } +} + +func om(namespace, name string) metav1.ObjectMeta { + return metav1.ObjectMeta{ + Namespace: namespace, + Name: name, + SelfLink: fmt.Sprintf("/apis/eventing/v1alpha1/namespaces/%s/object/%s", namespace, name), + } +} + +func getControllerConfig() *KafkaProvisionerConfig { + return &KafkaProvisionerConfig{ + Brokers: []string{"test-broker"}, + } +} diff --git a/pkg/provisioners/kafka/controller/types.go b/pkg/provisioners/kafka/controller/types.go new file mode 100644 index 00000000000..46a85cea400 --- /dev/null +++ b/pkg/provisioners/kafka/controller/types.go @@ -0,0 +1,5 @@ +package controller + +type KafkaProvisionerConfig struct { + Brokers []string +} diff --git a/pkg/provisioners/kafka/controller/util.go b/pkg/provisioners/kafka/controller/util.go new file mode 100644 index 00000000000..7184e655b3f --- /dev/null +++ b/pkg/provisioners/kafka/controller/util.go @@ -0,0 +1,39 @@ +package controller + +import ( + "fmt" + "strings" + + "github.com/knative/pkg/configmap" +) + +const ( + BrokerConfigMapKey = "bootstrap_servers" +) + +// GetProvisionerConfig returns the details of the associated ClusterChannelProvisioner object +func GetProvisionerConfig(path string) (*KafkaProvisionerConfig, error) { + configMap, err := configmap.Load(path) + if err != nil { + return nil, fmt.Errorf("error loading provisioner configuration: %s", err) + } + + if len(configMap) == 0 { + return nil, fmt.Errorf("missing provisioner configuration") + } + + config := &KafkaProvisionerConfig{} + + if brokers, ok := configMap[BrokerConfigMapKey]; ok { + bootstrapServers := strings.Split(brokers, ",") + for _, s := range bootstrapServers { + if len(s) == 0 { + return nil, fmt.Errorf("empty %s value in provisioner configuration", BrokerConfigMapKey) + } + } + config.Brokers = bootstrapServers + return config, nil + } + + return nil, fmt.Errorf("missing key %s in provisioner configuration", BrokerConfigMapKey) +} diff --git a/pkg/provisioners/kafka/controller/util_test.go b/pkg/provisioners/kafka/controller/util_test.go new file mode 100644 index 00000000000..dfbd8d48f1f --- /dev/null +++ b/pkg/provisioners/kafka/controller/util_test.go @@ -0,0 +1,99 @@ +package controller + +import ( + "io/ioutil" + "os" + "path/filepath" + "testing" + + "github.com/google/go-cmp/cmp" +) + +func TestGetProvisionerConfigBrokers(t *testing.T) { + + testCases := []struct { + name string + data map[string]string + path string + getError string + expected *KafkaProvisionerConfig + }{ + { + name: "invalid config path", + path: "/tmp/does_not_exist", + getError: "error loading provisioner configuration: lstat /tmp/does_not_exist: no such file or directory", + }, + { + name: "configmap with no data", + data: map[string]string{}, + getError: "missing provisioner configuration", + }, + { + name: "configmap with no bootstrap_servers key", + data: map[string]string{"key": "value"}, + getError: "missing key bootstrap_servers in provisioner configuration", + }, + { + name: "configmap with empty bootstrap_servers value", + data: map[string]string{"bootstrap_servers": ""}, + getError: "empty bootstrap_servers value in provisioner configuration", + }, + { + name: "single bootstrap_servers", + data: map[string]string{"bootstrap_servers": "kafkabroker.kafka:9092"}, + expected: &KafkaProvisionerConfig{ + Brokers: []string{"kafkabroker.kafka:9092"}, + }, + }, + { + name: "multiple bootstrap_servers", + data: map[string]string{"bootstrap_servers": "kafkabroker1.kafka:9092,kafkabroker2.kafka:9092"}, + expected: &KafkaProvisionerConfig{ + Brokers: []string{"kafkabroker1.kafka:9092", "kafkabroker2.kafka:9092"}, + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Logf("Running %s", t.Name()) + + if tc.path == "" { + dir, err := ioutil.TempDir("", "util_test") + if err != nil { + t.Errorf("error creating tmp directory") + } + defer os.RemoveAll(dir) + + for k, v := range tc.data { + if k != "" { + path := filepath.Join(dir, k) + if err := ioutil.WriteFile(path, []byte(v), 0600); err != nil { + t.Errorf("error writing file %s: %s", path, err) + } + } + } + + tc.path = dir + } + got, err := GetProvisionerConfig(tc.path) + + if tc.getError != "" { + if err == nil { + t.Errorf("Expected Config error: '%v'. Actual nil", tc.getError) + } else if err.Error() != tc.getError { + t.Errorf("Unexpected Config error. Expected '%v'. Actual '%v'", tc.getError, err) + } + return + } else if err != nil { + t.Errorf("Unexpected Config error. Expected nil. Actual '%v'", err) + } + + if diff := cmp.Diff(tc.expected, got); diff != "" { + t.Errorf("unexpected Config (-want, +got) = %v", diff) + } + + }) + } + +} diff --git a/pkg/provisioners/kafka/dispatcher/dispatcher.go b/pkg/provisioners/kafka/dispatcher/dispatcher.go new file mode 100644 index 00000000000..7551edb5041 --- /dev/null +++ b/pkg/provisioners/kafka/dispatcher/dispatcher.go @@ -0,0 +1,300 @@ +/* +Copyright 2018 The Knative 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 dispatcher + +import ( + "errors" + "fmt" + "sync" + "sync/atomic" + + "github.com/Shopify/sarama" + "github.com/bsm/sarama-cluster" + "github.com/google/go-cmp/cmp" + "go.uber.org/zap" + + eventingduck "github.com/knative/eventing/pkg/apis/duck/v1alpha1" + "github.com/knative/eventing/pkg/buses" + "github.com/knative/eventing/pkg/provisioners/kafka/controller" + "github.com/knative/eventing/pkg/sidecar/multichannelfanout" +) + +type KafkaDispatcher struct { + config atomic.Value + updateLock sync.Mutex + + receiver *buses.MessageReceiver + dispatcher *buses.MessageDispatcher + + kafkaAsyncProducer sarama.AsyncProducer + kafkaConsumers map[buses.ChannelReference]map[subscription]KafkaConsumer + kafkaCluster KafkaCluster + + logger *zap.Logger +} + +type KafkaConsumer interface { + Messages() <-chan *sarama.ConsumerMessage + MarkOffset(msg *sarama.ConsumerMessage, metadata string) + Close() (err error) +} + +type KafkaCluster interface { + NewConsumer(groupID string, topics []string) (KafkaConsumer, error) +} + +type saramaCluster struct { + kafkaBrokers []string +} + +func (c *saramaCluster) NewConsumer(groupID string, topics []string) (KafkaConsumer, error) { + consumerConfig := cluster.NewConfig() + consumerConfig.Version = sarama.V1_1_0_0 + return cluster.NewConsumer(c.kafkaBrokers, groupID, topics, consumerConfig) +} + +type subscription struct { + Namespace string + Name string + SubscriberURI string + ReplyURI string +} + +// ConfigDiffs diffs the new config with the existing config. If there are no differences, then the +// empty string is returned. If there are differences, then a non-empty string is returned +// describing the differences. +func (d *KafkaDispatcher) ConfigDiff(updated *multichannelfanout.Config) string { + return cmp.Diff(d.getConfig(), updated) +} + +func (d *KafkaDispatcher) UpdateConfig(config *multichannelfanout.Config) error { + if config == nil { + return errors.New("nil config") + } + + d.updateLock.Lock() + defer d.updateLock.Unlock() + + if diff := d.ConfigDiff(config); diff != "" { + d.logger.Info("Updating config (-old +new)", zap.String("diff", diff)) + + newSubs := make(map[subscription]bool) + + // Subscribe to new subscriptions + for _, cc := range config.ChannelConfigs { + channelRef := buses.ChannelReference{ + Name: cc.Name, + Namespace: cc.Namespace, + } + for _, subSpec := range cc.FanoutConfig.Subscriptions { + sub := newSubscription(subSpec) + if _, ok := d.kafkaConsumers[channelRef][sub]; ok { + // subscribe can be called multiple times for the same subscription, + // unsubscribe before we resubscribe. + // TODO The behavior to unsubscribe and re-subscribe is retained from the older kafka bus + // implementation. It is not clear as to why this is needed instead of just re-using the same + // consumer. + err := d.unsubscribe(channelRef, sub) + if err != nil { + return err + } + } + d.subscribe(channelRef, sub) + newSubs[sub] = true + } + } + + // Unsubscribe and close consumer for any deleted subscriptions + for channelRef, subMap := range d.kafkaConsumers { + for sub, _ := range subMap { + if ok := newSubs[sub]; !ok { + d.unsubscribe(channelRef, sub) + } + } + } + + // Update the config so that it can be used for comparison during next sync + d.setConfig(config) + } + return nil +} + +// Run starts the kafka dispatcher's message processing. +func (d *KafkaDispatcher) Start(stopCh <-chan struct{}) error { + if d.receiver == nil { + return fmt.Errorf("message receiver is not set") + } + + if d.kafkaAsyncProducer == nil { + return fmt.Errorf("kafkaAsyncProducer is not set") + } + + go func() { + for { + select { + case e := <-d.kafkaAsyncProducer.Errors(): + d.logger.Warn("Got", zap.Error(e)) + case s := <-d.kafkaAsyncProducer.Successes(): + d.logger.Info("Sent", zap.Any("success", s)) + case <-stopCh: + return + } + } + }() + + d.receiver.Run(stopCh) + + return nil +} + +func (d *KafkaDispatcher) subscribe(channelRef buses.ChannelReference, sub subscription) error { + + d.logger.Info("Subscribing", zap.Any("channelRef", channelRef), zap.Any("subscription", sub)) + + topicName := topicName(channelRef) + + group := fmt.Sprintf("%s.%s.%s", controller.Name, sub.Namespace, sub.Name) + consumer, err := d.kafkaCluster.NewConsumer(group, []string{topicName}) + if err != nil { + // we can not create a consumer - logging that, with reason + d.logger.Info("Could not create proper consumer", zap.Error(err)) + return err + } + + channelMap, ok := d.kafkaConsumers[channelRef] + if !ok { + channelMap = make(map[subscription]KafkaConsumer) + d.kafkaConsumers[channelRef] = channelMap + } + channelMap[sub] = consumer + + go func() { + for { + msg, more := <-consumer.Messages() + if more { + d.logger.Info("Dispatching a message for subscription", zap.Any("channelRef", channelRef), zap.Any("subscription", sub)) + message := fromKafkaMessage(msg) + err := d.dispatchMessage(message, sub) + if err != nil { + d.logger.Warn("Got error trying to dispatch message", zap.Error(err)) + } + // TODO: handle errors with pluggable strategy + consumer.MarkOffset(msg, "") // Mark message as processed + } else { + break + } + } + d.logger.Info("Consumer for subscription stopped", zap.Any("channelRef", channelRef), zap.Any("subscription", sub)) + }() + + return nil +} + +func (d *KafkaDispatcher) unsubscribe(channel buses.ChannelReference, sub subscription) error { + d.logger.Info("Unsubscribing from channel", zap.Any("channel", channel), zap.Any("subscription", sub)) + if consumer, ok := d.kafkaConsumers[channel][sub]; ok { + delete(d.kafkaConsumers[channel], sub) + return consumer.Close() + } + return nil +} + +// dispatchMessage sends the request to exactly one subscription. It handles both the `call` and +// the `sink` portions of the subscription. +func (d *KafkaDispatcher) dispatchMessage(m *buses.Message, sub subscription) error { + return d.dispatcher.DispatchMessage(m, sub.SubscriberURI, sub.ReplyURI, buses.DispatchDefaults{}) +} + +func (d *KafkaDispatcher) getConfig() *multichannelfanout.Config { + return d.config.Load().(*multichannelfanout.Config) +} + +func (d *KafkaDispatcher) setConfig(config *multichannelfanout.Config) { + d.config.Store(config) +} + +func NewDispatcher(brokers []string, logger *zap.Logger) (*KafkaDispatcher, error) { + + conf := sarama.NewConfig() + conf.Version = sarama.V1_1_0_0 + conf.ClientID = controller.Name + "-dispatcher" + client, err := sarama.NewClient(brokers, conf) + if err != nil { + return nil, fmt.Errorf("unable to create kafka client: %v", err) + } + + producer, err := sarama.NewAsyncProducerFromClient(client) + if err != nil { + return nil, fmt.Errorf("unable to create kafka producer: %v", err) + } + + dispatcher := &KafkaDispatcher{ + dispatcher: buses.NewMessageDispatcher(logger.Sugar()), + + kafkaCluster: &saramaCluster{kafkaBrokers: brokers}, + kafkaConsumers: make(map[buses.ChannelReference]map[subscription]KafkaConsumer), + kafkaAsyncProducer: producer, + + logger: logger, + } + receiverFunc := buses.NewMessageReceiver( + func(channel buses.ChannelReference, message *buses.Message) error { + dispatcher.kafkaAsyncProducer.Input() <- toKafkaMessage(channel, message) + return nil + }, logger.Sugar()) + dispatcher.receiver = receiverFunc + dispatcher.setConfig(&multichannelfanout.Config{}) + return dispatcher, nil +} + +func fromKafkaMessage(kafkaMessage *sarama.ConsumerMessage) *buses.Message { + headers := make(map[string]string) + for _, header := range kafkaMessage.Headers { + headers[string(header.Key)] = string(header.Value) + } + message := buses.Message{ + Headers: headers, + Payload: kafkaMessage.Value, + } + return &message +} + +func toKafkaMessage(channel buses.ChannelReference, message *buses.Message) *sarama.ProducerMessage { + kafkaMessage := sarama.ProducerMessage{ + Topic: topicName(channel), + Value: sarama.ByteEncoder(message.Payload), + } + for h, v := range message.Headers { + kafkaMessage.Headers = append(kafkaMessage.Headers, sarama.RecordHeader{ + Key: []byte(h), + Value: []byte(v), + }) + } + return &kafkaMessage +} + +func topicName(channel buses.ChannelReference) string { + return fmt.Sprintf("%s.%s", channel.Namespace, channel.Name) +} + +func newSubscription(spec eventingduck.ChannelSubscriberSpec) subscription { + return subscription{ + Name: spec.Ref.Name, + Namespace: spec.Ref.Namespace, + SubscriberURI: spec.SubscriberURI, + ReplyURI: spec.ReplyURI, + } +} diff --git a/pkg/provisioners/kafka/dispatcher/dispatcher_test.go b/pkg/provisioners/kafka/dispatcher/dispatcher_test.go new file mode 100644 index 00000000000..3e2b6d39dc6 --- /dev/null +++ b/pkg/provisioners/kafka/dispatcher/dispatcher_test.go @@ -0,0 +1,476 @@ +package dispatcher + +import ( + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Shopify/sarama" + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "go.uber.org/zap" + "k8s.io/api/core/v1" + + eventingduck "github.com/knative/eventing/pkg/apis/duck/v1alpha1" + "github.com/knative/eventing/pkg/buses" + "github.com/knative/eventing/pkg/sidecar/fanout" + "github.com/knative/eventing/pkg/sidecar/multichannelfanout" +) + +type mockConsumer struct { + message chan *sarama.ConsumerMessage +} + +func (c *mockConsumer) Messages() <-chan *sarama.ConsumerMessage { + return c.message +} + +func (c *mockConsumer) Close() error { + return nil +} + +func (c *mockConsumer) MarkOffset(msg *sarama.ConsumerMessage, metadata string) { + return +} + +type mockSaramaCluster struct { + // closed closes the message channel so that it doesn't block during the test + closed bool + // Handle to the latest created consumer, useful to access underlying message chan + consumerChannel chan *sarama.ConsumerMessage + // createErr will return an error when creating a consumer + createErr bool +} + +func (c *mockSaramaCluster) NewConsumer(groupID string, topics []string) (KafkaConsumer, error) { + if c.createErr { + return nil, fmt.Errorf("error creating consumer") + } + consumer := &mockConsumer{ + message: make(chan *sarama.ConsumerMessage), + } + if c.closed { + close(consumer.message) + } + c.consumerChannel = consumer.message + return consumer, nil +} + +func TestDispatcher_UpdateConfig(t *testing.T) { + testCases := []struct { + name string + oldConfig *multichannelfanout.Config + newConfig *multichannelfanout.Config + subscribes []string + unsubscribes []string + createErr string + }{ + { + name: "nil config", + oldConfig: &multichannelfanout.Config{}, + newConfig: nil, + createErr: "nil config", + }, + { + name: "same config", + oldConfig: &multichannelfanout.Config{}, + newConfig: &multichannelfanout.Config{}, + }, + { + name: "config with no subscription", + oldConfig: &multichannelfanout.Config{}, + newConfig: &multichannelfanout.Config{ + ChannelConfigs: []multichannelfanout.ChannelConfig{ + { + Namespace: "default", + Name: "test-channel", + }, + }, + }, + }, + { + name: "single channel w/ new subscriptions", + oldConfig: &multichannelfanout.Config{}, + newConfig: &multichannelfanout.Config{ + ChannelConfigs: []multichannelfanout.ChannelConfig{ + { + Namespace: "default", + Name: "test-channel", + FanoutConfig: fanout.Config{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ + { + Ref: &v1.ObjectReference{ + Name: "subscription-1", + }, + SubscriberURI: "http://test/subscriber", + }, + { + Ref: &v1.ObjectReference{ + Name: "subscription-2", + }, + SubscriberURI: "http://test/subscriber", + }, + }, + }, + }, + }, + }, + subscribes: []string{"subscription-1", "subscription-2"}, + }, + { + name: "single channel w/ existing subscriptions", + oldConfig: &multichannelfanout.Config{ + ChannelConfigs: []multichannelfanout.ChannelConfig{ + { + Namespace: "default", + Name: "test-channel", + FanoutConfig: fanout.Config{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ + { + Ref: &v1.ObjectReference{ + Name: "subscription-1", + }, + SubscriberURI: "http://test/subscriber", + }, + { + Ref: &v1.ObjectReference{ + Name: "subscription-2", + }, + SubscriberURI: "http://test/subscriber", + }}}}}, + }, + newConfig: &multichannelfanout.Config{ + ChannelConfigs: []multichannelfanout.ChannelConfig{ + { + Namespace: "default", + Name: "test-channel", + FanoutConfig: fanout.Config{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ + { + Ref: &v1.ObjectReference{ + Name: "subscription-2", + }, + SubscriberURI: "http://test/subscriber", + }, + { + Ref: &v1.ObjectReference{ + Name: "subscription-3", + }, + SubscriberURI: "http://test/subscriber", + }, + }, + }, + }, + }, + }, + subscribes: []string{"subscription-2", "subscription-3"}, + unsubscribes: []string{"subscription-1"}, + }, + { + name: "multi channel w/old and new subscriptions", + oldConfig: &multichannelfanout.Config{ + ChannelConfigs: []multichannelfanout.ChannelConfig{ + { + Namespace: "default", + Name: "test-channel-1", + FanoutConfig: fanout.Config{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ + { + Ref: &v1.ObjectReference{ + Name: "subscription-1", + }, + SubscriberURI: "http://test/subscriber", + }, + { + Ref: &v1.ObjectReference{ + Name: "subscription-2", + }, + SubscriberURI: "http://test/subscriber", + }, + }, + }}}}, + newConfig: &multichannelfanout.Config{ + ChannelConfigs: []multichannelfanout.ChannelConfig{ + { + Namespace: "default", + Name: "test-channel-1", + FanoutConfig: fanout.Config{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ + { + Ref: &v1.ObjectReference{ + Name: "subscription-1", + }, + SubscriberURI: "http://test/subscriber", + }, + }, + }, + }, + { + Namespace: "default", + Name: "test-channel-2", + FanoutConfig: fanout.Config{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ + { + Ref: &v1.ObjectReference{ + Name: "subscription-3", + }, + SubscriberURI: "http://test/subscriber", + }, + { + Ref: &v1.ObjectReference{ + Name: "subscription-4", + }, + SubscriberURI: "http://test/subscriber", + }, + }, + }, + }, + }, + }, + subscribes: []string{"subscription-1", "subscription-3", "subscription-4"}, + unsubscribes: []string{"subscription-2"}, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Logf("Running %s", t.Name()) + d := &KafkaDispatcher{ + kafkaCluster: &mockSaramaCluster{closed: true}, + kafkaConsumers: make(map[buses.ChannelReference]map[subscription]KafkaConsumer), + + logger: zap.NewNop(), + } + d.setConfig(&multichannelfanout.Config{}) + + // Initialize using oldConfig + err := d.UpdateConfig(tc.oldConfig) + if err != nil { + t.Errorf("unexpected error: %s", err) + } + oldSubscribers := make(map[string]bool) + for _, subMap := range d.kafkaConsumers { + for sub, _ := range subMap { + oldSubscribers[sub.Name] = true + } + } + for _, sub := range tc.unsubscribes { + if ok := oldSubscribers[sub]; !ok { + t.Errorf("subscription %s was never subscribed", sub) + } + } + + // Update with new config + err = d.UpdateConfig(tc.newConfig) + if tc.createErr != "" { + if err == nil { + t.Errorf("Expected UpdateConfig error: '%v'. Actual nil", tc.createErr) + } else if err.Error() != tc.createErr { + t.Errorf("Unexpected UpdateConfig error. Expected '%v'. Actual '%v'", tc.createErr, err) + } + return + } else if err != nil { + t.Errorf("Unexpected UpdateConfig error. Expected nil. Actual '%v'", err) + } + + var newSubscribers []string + for _, subMap := range d.kafkaConsumers { + for sub, _ := range subMap { + newSubscribers = append(newSubscribers, sub.Name) + } + } + + if diff := cmp.Diff(tc.subscribes, newSubscribers, sortStrings); diff != "" { + t.Errorf("unexpected subscribers (-want, +got) = %v", diff) + } + + }) + } +} + +func TestFromKafkaMessage(t *testing.T) { + data := []byte("data") + kafkaMessage := &sarama.ConsumerMessage{ + Headers: []*sarama.RecordHeader{ + { + Key: []byte("k1"), + Value: []byte("v1"), + }, + }, + Value: data, + } + want := &buses.Message{ + Headers: map[string]string{ + "k1": "v1", + }, + Payload: data, + } + got := fromKafkaMessage(kafkaMessage) + if diff := cmp.Diff(want, got); diff != "" { + t.Errorf("unexpected message (-want, +got) = %v", diff) + } +} + +func TestToKafkaMessage(t *testing.T) { + data := []byte("data") + channelRef := buses.ChannelReference{ + Name: "test-channel", + Namespace: "test-ns", + } + msg := &buses.Message{ + Headers: map[string]string{ + "k1": "v1", + }, + Payload: data, + } + want := &sarama.ProducerMessage{ + Topic: "test-ns.test-channel", + Headers: []sarama.RecordHeader{ + { + Key: []byte("k1"), + Value: []byte("v1"), + }, + }, + Value: sarama.ByteEncoder(data), + } + got := toKafkaMessage(channelRef, msg) + if diff := cmp.Diff(want, got, cmpopts.IgnoreUnexported(sarama.ProducerMessage{})); diff != "" { + t.Errorf("unexpected message (-want, +got) = %v", diff) + } +} + +type dispatchTestHandler struct { + t *testing.T + payload []byte + done chan bool +} + +func (h *dispatchTestHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + defer r.Body.Close() + body, err := ioutil.ReadAll(r.Body) + if err != nil { + h.t.Error("Failed to read the request body") + } + if diff := cmp.Diff(h.payload, body); diff != "" { + h.t.Errorf("unexpected body (-want, +got) = %v", diff) + } + h.done <- true +} + +func TestSubscribe(t *testing.T) { + sc := &mockSaramaCluster{} + data := []byte("data") + d := &KafkaDispatcher{ + kafkaCluster: sc, + kafkaConsumers: make(map[buses.ChannelReference]map[subscription]KafkaConsumer), + dispatcher: buses.NewMessageDispatcher(zap.NewNop().Sugar()), + logger: zap.NewNop(), + } + + testHandler := &dispatchTestHandler{ + t: t, + payload: data, + done: make(chan bool)} + + server := httptest.NewServer(testHandler) + defer server.Close() + + channelRef := buses.ChannelReference{ + Name: "test-channel", + Namespace: "test-ns", + } + + subRef := subscription{ + Name: "test-sub", + Namespace: "test-ns", + SubscriberURI: server.URL[7:], + } + err := d.subscribe(channelRef, subRef) + if err != nil { + t.Errorf("unexpected error %s", err) + } + defer close(sc.consumerChannel) + sc.consumerChannel <- &sarama.ConsumerMessage{ + Headers: []*sarama.RecordHeader{ + { + Key: []byte("k1"), + Value: []byte("v1"), + }, + }, + Value: data, + } + + <-testHandler.done + +} + +func TestSubscribeError(t *testing.T) { + sc := &mockSaramaCluster{ + createErr: true, + } + d := &KafkaDispatcher{ + kafkaCluster: sc, + logger: zap.NewNop(), + } + + channelRef := buses.ChannelReference{ + Name: "test-channel", + Namespace: "test-ns", + } + + subRef := subscription{ + Name: "test-sub", + Namespace: "test-ns", + } + err := d.subscribe(channelRef, subRef) + if err == nil { + t.Errorf("expected error want %s, got %s", "error creating consumer", err) + } +} + +func TestUnsubscribeUnknownSub(t *testing.T) { + sc := &mockSaramaCluster{ + createErr: true, + } + d := &KafkaDispatcher{ + kafkaCluster: sc, + logger: zap.NewNop(), + } + + channelRef := buses.ChannelReference{ + Name: "test-channel", + Namespace: "test-ns", + } + + subRef := subscription{ + Name: "test-sub", + Namespace: "test-ns", + } + err := d.unsubscribe(channelRef, subRef) + if err != nil { + t.Errorf("uexpected error %s", err) + } +} + +func TestKafkaDispatcher_Start(t *testing.T) { + d := &KafkaDispatcher{} + err := d.Start(make(chan struct{})) + if err == nil { + t.Errorf("expected error want %s, got %s", "message receiver is not set", err) + } + + d.receiver = buses.NewMessageReceiver(func(channel buses.ChannelReference, message *buses.Message) error { + return nil + }, zap.NewNop().Sugar()) + err = d.Start(make(chan struct{})) + if err == nil { + t.Errorf("expected error want %s, got %s", "kafkaAsyncProducer is not set", err) + } +} + +var sortStrings = cmpopts.SortSlices(func(x, y string) bool { + return x < y +}) diff --git a/pkg/provisioners/kafka/main.go b/pkg/provisioners/kafka/main.go new file mode 100644 index 00000000000..eb779abf630 --- /dev/null +++ b/pkg/provisioners/kafka/main.go @@ -0,0 +1,106 @@ +package main + +import ( + "flag" + "fmt" + "os" + "strings" + + istiov1alpha3 "github.com/knative/pkg/apis/istio/v1alpha3" + "go.uber.org/zap" + "k8s.io/apimachinery/pkg/runtime" + _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" + "sigs.k8s.io/controller-runtime/pkg/client/config" + "sigs.k8s.io/controller-runtime/pkg/controller" + "sigs.k8s.io/controller-runtime/pkg/manager" + logf "sigs.k8s.io/controller-runtime/pkg/runtime/log" + "sigs.k8s.io/controller-runtime/pkg/runtime/signals" + + eventingv1alpha "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + "github.com/knative/eventing/pkg/provisioners" + provisionerController "github.com/knative/eventing/pkg/provisioners/kafka/controller" + "github.com/knative/eventing/pkg/provisioners/kafka/controller/channel" + "github.com/knative/pkg/configmap" +) + +const ( + BrokerConfigMapKey = "bootstrap_servers" +) + +// SchemeFunc adds types to a Scheme. +type SchemeFunc func(*runtime.Scheme) error + +// ProvideFunc adds a controller to a Manager. +type ProvideFunc func(mgr manager.Manager, config *provisionerController.KafkaProvisionerConfig, logger *zap.Logger) (controller.Controller, error) + +func main() { + flag.Parse() + logf.SetLogger(logf.ZapLogger(false)) + + logger := provisioners.NewProvisionerLoggerFromConfig(provisioners.NewLoggingConfig()) + defer logger.Sync() + + // Setup a Manager + mgr, err := manager.New(config.GetConfigOrDie(), manager.Options{}) + if err != nil { + logger.Error(err, "unable to run controller manager") + os.Exit(1) + } + + // Add custom types to this array to get them into the manager's scheme. + schemeFuncs := []SchemeFunc{ + eventingv1alpha.AddToScheme, + istiov1alpha3.AddToScheme, + } + for _, schemeFunc := range schemeFuncs { + schemeFunc(mgr.GetScheme()) + } + + // Add each controller's ProvideController func to this list to have the + // manager run it. + providers := []ProvideFunc{ + provisionerController.ProvideController, + channel.ProvideController, + } + + // TODO the underlying config map needs to be watched and the config should be reloaded if there is a change. + provisionerConfig, err := getProvisionerConfig() + + if err != nil { + logger.Error(err, "unable to run controller manager") + os.Exit(1) + } + + for _, provider := range providers { + if _, err := provider(mgr, provisionerConfig, logger.Desugar()); err != nil { + logger.Error(err, "unable to run controller manager") + os.Exit(1) + } + } + + mgr.Start(signals.SetupSignalHandler()) +} + +// getProvisionerConfig returns the details of the associated Provisioner/ClusterChannelProvisioner object +func getProvisionerConfig() (*provisionerController.KafkaProvisionerConfig, error) { + configMap, err := configmap.Load("/etc/config-provisioner") + if err != nil { + return nil, fmt.Errorf("error loading provisioner configuration: %s", err) + } + + if len(configMap) == 0 { + return nil, fmt.Errorf("missing provisioner configuration") + } + + config := &provisionerController.KafkaProvisionerConfig{} + + if value, ok := configMap[BrokerConfigMapKey]; ok { + bootstrapServers := strings.Split(value, ",") + if len(bootstrapServers) != 0 { + config.Brokers = bootstrapServers + return config, nil + } + } + + return nil, fmt.Errorf("missing key %s in provisioner configuration", BrokerConfigMapKey) +} diff --git a/pkg/provisioners/logging.go b/pkg/provisioners/logging.go new file mode 100644 index 00000000000..46dc9830151 --- /dev/null +++ b/pkg/provisioners/logging.go @@ -0,0 +1,63 @@ +/* + * Copyright 2018 The Knative 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 provisioners + +import ( + "github.com/knative/pkg/logging" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" +) + +const ( + provisionerLoggingComponent = "provisioner" +) + +// NewLoggingConfig creates a static logging configuration appropriate for a +// provisioner. All logging levels are set to Info. +func NewLoggingConfig() *logging.Config { + lc := &logging.Config{} + lc.LoggingConfig = `{ + "level": "info", + "development": false, + "outputPaths": ["stdout"], + "errorOutputPaths": ["stderr"], + "encoding": "json", + "encoderConfig": { + "timeKey": "ts", + "levelKey": "level", + "nameKey": "logger", + "callerKey": "caller", + "messageKey": "msg", + "stacktraceKey": "stacktrace", + "lineEnding": "", + "levelEncoder": "", + "timeEncoder": "iso8601", + "durationEncoder": "", + "callerEncoder": "" + } + }` + lc.LoggingLevel = make(map[string]zapcore.Level) + lc.LoggingLevel[provisionerLoggingComponent] = zapcore.InfoLevel + return lc +} + +// NewProvisionerLoggerFromConfig creates a new zap logger for the provisioner component based +// on the provided configuration +func NewProvisionerLoggerFromConfig(config *logging.Config) *zap.SugaredLogger { + logger, _ := logging.NewLoggerFromConfig(config, provisionerLoggingComponent) + return logger +} diff --git a/pkg/provisioners/provisioner_util.go b/pkg/provisioners/provisioner_util.go new file mode 100644 index 00000000000..787a1c58155 --- /dev/null +++ b/pkg/provisioners/provisioner_util.go @@ -0,0 +1,95 @@ +package provisioners + +import ( + "context" + + "go.uber.org/zap" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/intstr" + runtimeClient "sigs.k8s.io/controller-runtime/pkg/client" + + eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + "github.com/knative/eventing/pkg/controller" + "github.com/knative/eventing/pkg/system" + "github.com/knative/pkg/logging" +) + +func CreateDispatcherService(ctx context.Context, client runtimeClient.Client, ccp *eventingv1alpha1.ClusterChannelProvisioner) (*corev1.Service, error) { + svcName := controller.ClusterBusDispatcherServiceName(ccp.Name) + svcKey := types.NamespacedName{ + Namespace: system.Namespace, + Name: svcName, + } + svc := &corev1.Service{} + err := client.Get(ctx, svcKey, svc) + + if errors.IsNotFound(err) { + svc = newDispatcherService(ccp) + err = client.Create(ctx, svc) + } + + // If an error occurred in either Get or Create, we need to reconcile again. + if err != nil { + return nil, err + } + + return svc, nil +} + +func UpdateClusterChannelProvisionerStatus(ctx context.Context, client runtimeClient.Client, u *eventingv1alpha1.ClusterChannelProvisioner) error { + o := &eventingv1alpha1.ClusterChannelProvisioner{} + if err := client.Get(ctx, runtimeClient.ObjectKey{Namespace: u.Namespace, Name: u.Name}, o); err != nil { + logger := logging.FromContext(ctx) + logger.Info("Error getting ClusterChannelProvisioner for status update", zap.Error(err), zap.Any("updatedClusterChannelProvisioner", u)) + return err + } + + if !equality.Semantic.DeepEqual(o.Status, u.Status) { + o.Status = u.Status + return client.Update(ctx, o) + } + return nil +} + +// newDispatcherService creates a new Service for a ClusterChannelProvisioner resource. It also sets +// the appropriate OwnerReferences on the resource so handleObject can discover +// the ClusterChannelProvisioner resource that 'owns' it. +func newDispatcherService(ccp *eventingv1alpha1.ClusterChannelProvisioner) *corev1.Service { + labels := DispatcherLabels(ccp.Name) + return &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{ + Name: controller.ClusterBusDispatcherServiceName(ccp.Name), + Namespace: system.Namespace, + Labels: labels, + OwnerReferences: []metav1.OwnerReference{ + *metav1.NewControllerRef(ccp, schema.GroupVersionKind{ + Group: eventingv1alpha1.SchemeGroupVersion.Group, + Version: eventingv1alpha1.SchemeGroupVersion.Version, + Kind: "ClusterChannelProvisioner", + }), + }, + }, + Spec: corev1.ServiceSpec{ + Selector: labels, + Ports: []corev1.ServicePort{ + { + Name: "http", + Port: 80, + TargetPort: intstr.FromInt(8080), + }, + }, + }, + } +} + +func DispatcherLabels(ccpName string) map[string]string { + return map[string]string{ + "clusterChannelProvisioner": ccpName, + "role": "dispatcher", + } +} diff --git a/pkg/provisioners/provisioner_util_test.go b/pkg/provisioners/provisioner_util_test.go new file mode 100644 index 00000000000..b93e7b780be --- /dev/null +++ b/pkg/provisioners/provisioner_util_test.go @@ -0,0 +1,114 @@ +package provisioners + +import ( + "context" + "fmt" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/knative/pkg/apis" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/intstr" + runtimeClient "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + "github.com/knative/eventing/pkg/system" +) + +const ( + clusterChannelProvisionerName = "kafka" +) + +func TestCreateDispatcherService(t *testing.T) { + want := makeDispatcherService() + client := fake.NewFakeClient() + got, _ := CreateDispatcherService(context.TODO(), client, getNewClusterChannelProvisioner()) + + ignore := cmpopts.IgnoreTypes(apis.VolatileTime{}) + if diff := cmp.Diff(want, got, ignore); diff != "" { + t.Errorf("Service (-want, +got) = %v", diff) + } +} + +func TestCreateDispatcherService_Existing(t *testing.T) { + want := makeDispatcherService() + client := fake.NewFakeClient(want) + got, _ := CreateDispatcherService(context.TODO(), client, getNewClusterChannelProvisioner()) + + ignore := cmpopts.IgnoreTypes(apis.VolatileTime{}) + if diff := cmp.Diff(want, got, ignore); diff != "" { + t.Errorf("Service (-want, +got) = %v", diff) + } +} + +func TestUpdateClusterChannelProvisioner(t *testing.T) { + ccp := getNewClusterChannelProvisioner() + client := fake.NewFakeClient(ccp) + + // Update more than just Status + ccp.Status.MarkReady() + ccp.ObjectMeta.Annotations = map[string]string{"test-annotation": "testing"} + UpdateClusterChannelProvisionerStatus(context.TODO(), client, ccp) + + got := &eventingv1alpha1.ClusterChannelProvisioner{} + client.Get(context.TODO(), runtimeClient.ObjectKey{Namespace: testNS, Name: clusterChannelProvisionerName}, got) + + // Only status should be updated + want := getNewClusterChannelProvisioner() + want.Status.MarkReady() + + ignore := cmpopts.IgnoreTypes(apis.VolatileTime{}) + if diff := cmp.Diff(want, got, ignore); diff != "" { + t.Errorf("ClusterChannelProvisioner (-want, +got) = %v", diff) + } +} + +func getNewClusterChannelProvisioner() *eventingv1alpha1.ClusterChannelProvisioner { + clusterChannelProvisioner := &eventingv1alpha1.ClusterChannelProvisioner{ + TypeMeta: ClusterChannelProvisionerType(), + ObjectMeta: om(testNS, clusterChannelProvisionerName), + Spec: eventingv1alpha1.ClusterChannelProvisionerSpec{}, + } + // selflink is not filled in when we create the object, so clear it + clusterChannelProvisioner.ObjectMeta.SelfLink = "" + return clusterChannelProvisioner +} + +func ClusterChannelProvisionerType() metav1.TypeMeta { + return metav1.TypeMeta{ + APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), + Kind: "ClusterChannelProvisioner", + } +} + +func makeDispatcherService() *corev1.Service { + return &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: system.Namespace, + Name: fmt.Sprintf("%s-clusterbus", clusterChannelProvisionerName), + OwnerReferences: []metav1.OwnerReference{ + { + APIVersion: eventingv1alpha1.SchemeGroupVersion.String(), + Kind: "ClusterChannelProvisioner", + Name: clusterChannelProvisionerName, + Controller: &truePointer, + BlockOwnerDeletion: &truePointer, + }, + }, + Labels: DispatcherLabels(clusterChannelProvisionerName), + }, + Spec: corev1.ServiceSpec{ + Selector: DispatcherLabels(clusterChannelProvisionerName), + Ports: []corev1.ServicePort{ + { + Name: "http", + Port: 80, + TargetPort: intstr.FromInt(8080), + }, + }, + }, + } +} diff --git a/pkg/sidecar/configmap/filesystem/filesystem_watcher_test.go b/pkg/sidecar/configmap/filesystem/filesystem_watcher_test.go index f36e3275018..8152289573c 100644 --- a/pkg/sidecar/configmap/filesystem/filesystem_watcher_test.go +++ b/pkg/sidecar/configmap/filesystem/filesystem_watcher_test.go @@ -27,10 +27,10 @@ import ( "time" "github.com/google/go-cmp/cmp" + eventingduck "github.com/knative/eventing/pkg/apis/duck/v1alpha1" "github.com/knative/eventing/pkg/sidecar/configmap" "github.com/knative/eventing/pkg/sidecar/fanout" "github.com/knative/eventing/pkg/sidecar/multichannelfanout" - duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" "go.uber.org/zap" yaml "gopkg.in/yaml.v2" ) @@ -83,20 +83,20 @@ func TestReadConfigMap(t *testing.T) { name: c1 fanoutConfig: subscriptions: - - callableDomain: event-changer.default.svc.cluster.local - sinkableDomain: message-dumper-bar.default.svc.cluster.local - - callableDomain: message-dumper-foo.default.svc.cluster.local - - sinkableDomain: message-dumper-bar.default.svc.cluster.local + - subscriberURI: event-changer.default.svc.cluster.local + replyURI: message-dumper-bar.default.svc.cluster.local + - subscriberURI: message-dumper-foo.default.svc.cluster.local + - replyURI: message-dumper-bar.default.svc.cluster.local - namespace: default name: c2 fanoutConfig: subscriptions: - - sinkableDomain: message-dumper-foo.default.svc.cluster.local + - replyURI: message-dumper-foo.default.svc.cluster.local - namespace: other name: c3 fanoutConfig: subscriptions: - - sinkableDomain: message-dumper-foo.default.svc.cluster.local + - replyURI: message-dumper-foo.default.svc.cluster.local `, expected: &multichannelfanout.Config{ ChannelConfigs: []multichannelfanout.ChannelConfig{ @@ -104,16 +104,16 @@ func TestReadConfigMap(t *testing.T) { Namespace: "default", Name: "c1", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: "event-changer.default.svc.cluster.local", - SinkableDomain: "message-dumper-bar.default.svc.cluster.local", + SubscriberURI: "event-changer.default.svc.cluster.local", + ReplyURI: "message-dumper-bar.default.svc.cluster.local", }, { - CallableDomain: "message-dumper-foo.default.svc.cluster.local", + SubscriberURI: "message-dumper-foo.default.svc.cluster.local", }, { - SinkableDomain: "message-dumper-bar.default.svc.cluster.local", + ReplyURI: "message-dumper-bar.default.svc.cluster.local", }, }, }, @@ -122,9 +122,9 @@ func TestReadConfigMap(t *testing.T) { Namespace: "default", Name: "c2", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - SinkableDomain: "message-dumper-foo.default.svc.cluster.local", + ReplyURI: "message-dumper-foo.default.svc.cluster.local", }, }, }, @@ -133,9 +133,9 @@ func TestReadConfigMap(t *testing.T) { Namespace: "other", Name: "c3", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - SinkableDomain: "message-dumper-foo.default.svc.cluster.local", + ReplyURI: "message-dumper-foo.default.svc.cluster.local", }, }, }, @@ -186,9 +186,9 @@ func TestWatch(t *testing.T) { Namespace: "default", Name: "c1", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - SinkableDomain: "foo.bar", + ReplyURI: "foo.bar", }, }, }, @@ -203,9 +203,9 @@ func TestWatch(t *testing.T) { Namespace: "default", Name: "c1", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - SinkableDomain: "foo.bar", + ReplyURI: "foo.bar", }, }, }, @@ -221,9 +221,9 @@ func TestWatch(t *testing.T) { Namespace: "default", Name: "c1", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - SinkableDomain: "foo.bar", + ReplyURI: "foo.bar", }, }, }, @@ -236,9 +236,9 @@ func TestWatch(t *testing.T) { Namespace: "default", Name: "new-channel", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: "baz.qux", + SubscriberURI: "baz.qux", }, }, }, diff --git a/pkg/sidecar/configmap/parse_test.go b/pkg/sidecar/configmap/parse_test.go index 5cddb280b89..4a47a7acf9d 100644 --- a/pkg/sidecar/configmap/parse_test.go +++ b/pkg/sidecar/configmap/parse_test.go @@ -17,13 +17,14 @@ limitations under the License. package configmap import ( + "strings" + "testing" + "github.com/google/go-cmp/cmp" + eventingduck "github.com/knative/eventing/pkg/apis/duck/v1alpha1" "github.com/knative/eventing/pkg/sidecar/fanout" "github.com/knative/eventing/pkg/sidecar/multichannelfanout" - duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" "go.uber.org/zap" - "strings" - "testing" ) func TestNewFanoutConfig(t *testing.T) { @@ -64,20 +65,20 @@ func TestNewFanoutConfig(t *testing.T) { name: c1 fanoutConfig: subscriptions: - - callableDomain: event-changer.default.svc.cluster.local - sinkableDomain: message-dumper-bar.default.svc.cluster.local - - callableDomain: message-dumper-foo.default.svc.cluster.local - - sinkableDomain: message-dumper-bar.default.svc.cluster.local + - subscriberURI: event-changer.default.svc.cluster.local + replyURI: message-dumper-bar.default.svc.cluster.local + - subscriberURI: message-dumper-foo.default.svc.cluster.local + - replyURI: message-dumper-bar.default.svc.cluster.local - namespace: default name: c2 fanoutConfig: subscriptions: - - sinkableDomain: message-dumper-foo.default.svc.cluster.local + - replyURI: message-dumper-foo.default.svc.cluster.local - namespace: other name: c3 fanoutConfig: subscriptions: - - sinkableDomain: message-dumper-foo.default.svc.cluster.local + - replyURI: message-dumper-foo.default.svc.cluster.local `, expected: &multichannelfanout.Config{ ChannelConfigs: []multichannelfanout.ChannelConfig{ @@ -85,16 +86,16 @@ func TestNewFanoutConfig(t *testing.T) { Namespace: "default", Name: "c1", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: "event-changer.default.svc.cluster.local", - SinkableDomain: "message-dumper-bar.default.svc.cluster.local", + SubscriberURI: "event-changer.default.svc.cluster.local", + ReplyURI: "message-dumper-bar.default.svc.cluster.local", }, { - CallableDomain: "message-dumper-foo.default.svc.cluster.local", + SubscriberURI: "message-dumper-foo.default.svc.cluster.local", }, { - SinkableDomain: "message-dumper-bar.default.svc.cluster.local", + ReplyURI: "message-dumper-bar.default.svc.cluster.local", }, }, }, @@ -103,9 +104,9 @@ func TestNewFanoutConfig(t *testing.T) { Namespace: "default", Name: "c2", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - SinkableDomain: "message-dumper-foo.default.svc.cluster.local", + ReplyURI: "message-dumper-foo.default.svc.cluster.local", }, }, }, @@ -114,9 +115,9 @@ func TestNewFanoutConfig(t *testing.T) { Namespace: "other", Name: "c3", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - SinkableDomain: "message-dumper-foo.default.svc.cluster.local", + ReplyURI: "message-dumper-foo.default.svc.cluster.local", }, }, }, @@ -156,16 +157,16 @@ func TestSerializeConfig(t *testing.T) { Namespace: "default", Name: "c1", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: "foo.example.com", - SinkableDomain: "bar.example.com", + SubscriberURI: "foo.example.com", + ReplyURI: "bar.example.com", }, { - SinkableDomain: "qux.example.com", + ReplyURI: "qux.example.com", }, { - CallableDomain: "baz.example.com", + SubscriberURI: "baz.example.com", }, {}, }, @@ -175,7 +176,7 @@ func TestSerializeConfig(t *testing.T) { Namespace: "other", Name: "no-subs", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{}, + Subscriptions: []eventingduck.ChannelSubscriberSpec{}, }, }, }, diff --git a/pkg/sidecar/configmap/watcher/watcher_test.go b/pkg/sidecar/configmap/watcher/watcher_test.go index e6296e5f201..6164c38cd63 100644 --- a/pkg/sidecar/configmap/watcher/watcher_test.go +++ b/pkg/sidecar/configmap/watcher/watcher_test.go @@ -18,16 +18,17 @@ package watcher import ( "errors" + "testing" + "github.com/google/go-cmp/cmp" + eventingduck "github.com/knative/eventing/pkg/apis/duck/v1alpha1" sidecarconfigmap "github.com/knative/eventing/pkg/sidecar/configmap" "github.com/knative/eventing/pkg/sidecar/fanout" "github.com/knative/eventing/pkg/sidecar/multichannelfanout" - duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" "github.com/knative/pkg/configmap" "go.uber.org/zap" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "testing" ) const ( @@ -66,8 +67,8 @@ func TestReconcile(t *testing.T) { namespace: bar fanoutConfig: subscriptions: - - callableDomain: callable - sinkableDomain: sinkable`, + - subscriberURI: subscriber + replyURI: reply`, }, expectedConfig: &multichannelfanout.Config{ ChannelConfigs: []multichannelfanout.ChannelConfig{ @@ -75,10 +76,10 @@ func TestReconcile(t *testing.T) { Name: "foo", Namespace: "bar", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: "callable", - SinkableDomain: "sinkable", + SubscriberURI: "subscriber", + ReplyURI: "reply", }, }, }, diff --git a/pkg/sidecar/fanout/fanout_handler.go b/pkg/sidecar/fanout/fanout_handler.go index 065a10d64f0..f5873c527a8 100644 --- a/pkg/sidecar/fanout/fanout_handler.go +++ b/pkg/sidecar/fanout/fanout_handler.go @@ -26,8 +26,8 @@ import ( "net/http" "time" + eventingduck "github.com/knative/eventing/pkg/apis/duck/v1alpha1" "github.com/knative/eventing/pkg/buses" - duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" "go.uber.org/zap" ) @@ -39,7 +39,7 @@ const ( // Configuration for a fanout.Handler. type Config struct { - Subscriptions []duckv1alpha1.ChannelSubscriberSpec `json:"subscriptions"` + Subscriptions []eventingduck.ChannelSubscriberSpec `json:"subscriptions"` } // http.Handler that takes a single request in and fans it out to N other servers. @@ -96,7 +96,7 @@ func (f *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (f *Handler) dispatch(msg *buses.Message) error { errorCh := make(chan error, len(f.config.Subscriptions)) for _, sub := range f.config.Subscriptions { - go func(s duckv1alpha1.ChannelSubscriberSpec) { + go func(s eventingduck.ChannelSubscriberSpec) { errorCh <- f.makeFanoutRequest(*msg, s) }(sub) } @@ -119,6 +119,6 @@ func (f *Handler) dispatch(msg *buses.Message) error { // makeFanoutRequest sends the request to exactly one subscription. It handles both the `call` and // the `sink` portions of the subscription. -func (f *Handler) makeFanoutRequest(m buses.Message, sub duckv1alpha1.ChannelSubscriberSpec) error { - return f.dispatcher.DispatchMessage(&m, sub.CallableDomain, sub.SinkableDomain, buses.DispatchDefaults{}) +func (f *Handler) makeFanoutRequest(m buses.Message, sub eventingduck.ChannelSubscriberSpec) error { + return f.dispatcher.DispatchMessage(&m, sub.SubscriberURI, sub.ReplyURI, buses.DispatchDefaults{}) } diff --git a/pkg/sidecar/fanout/fanout_handler_test.go b/pkg/sidecar/fanout/fanout_handler_test.go index 9bdf020e544..4df6ef744ed 100644 --- a/pkg/sidecar/fanout/fanout_handler_test.go +++ b/pkg/sidecar/fanout/fanout_handler_test.go @@ -18,10 +18,6 @@ package fanout import ( "errors" - "github.com/knative/eventing/pkg/buses" - duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" - "go.uber.org/atomic" - "go.uber.org/zap" "io" "io/ioutil" "net/http" @@ -29,13 +25,18 @@ import ( "strings" "testing" "time" + + eventingduck "github.com/knative/eventing/pkg/apis/duck/v1alpha1" + "github.com/knative/eventing/pkg/buses" + "go.uber.org/atomic" + "go.uber.org/zap" ) // Domains used in subscriptions, which will be replaced by the real domains of the started HTTP // servers. const ( - replaceCallable = "replaceCallable" - replaceSinkable = "replaceSinkable" + replaceSubscriber = "replaceSubscriber" + replaceChannel = "replaceChannel" ) var ( @@ -59,9 +60,9 @@ func TestFanoutHandler_ServeHTTP(t *testing.T) { testCases := map[string]struct { receiverFunc func(buses.ChannelReference, *buses.Message) error timeout time.Duration - subs []duckv1alpha1.ChannelSubscriberSpec - callable func(http.ResponseWriter, *http.Request) - sinkable func(http.ResponseWriter, *http.Request) + subs []eventingduck.ChannelSubscriberSpec + subscriber func(http.ResponseWriter, *http.Request) + channel func(http.ResponseWriter, *http.Request) expectedStatus int }{ "rejected by receiver": { @@ -72,107 +73,107 @@ func TestFanoutHandler_ServeHTTP(t *testing.T) { }, "fanout times out": { timeout: time.Millisecond, - subs: []duckv1alpha1.ChannelSubscriberSpec{ + subs: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: replaceCallable, + SubscriberURI: replaceSubscriber, }, }, - callable: func(writer http.ResponseWriter, _ *http.Request) { + subscriber: func(writer http.ResponseWriter, _ *http.Request) { time.Sleep(10 * time.Millisecond) writer.WriteHeader(http.StatusAccepted) }, expectedStatus: http.StatusInternalServerError, }, "zero subs succeed": { - subs: []duckv1alpha1.ChannelSubscriberSpec{}, + subs: []eventingduck.ChannelSubscriberSpec{}, expectedStatus: http.StatusAccepted, }, "empty sub succeeds": { - subs: []duckv1alpha1.ChannelSubscriberSpec{ + subs: []eventingduck.ChannelSubscriberSpec{ {}, }, expectedStatus: http.StatusAccepted, }, - "sinkable fails": { - subs: []duckv1alpha1.ChannelSubscriberSpec{ + "reply fails": { + subs: []eventingduck.ChannelSubscriberSpec{ { - SinkableDomain: replaceSinkable, + ReplyURI: replaceChannel, }, }, - sinkable: func(writer http.ResponseWriter, _ *http.Request) { + channel: func(writer http.ResponseWriter, _ *http.Request) { writer.WriteHeader(http.StatusNotFound) }, expectedStatus: http.StatusInternalServerError, }, - "callable fails": { - subs: []duckv1alpha1.ChannelSubscriberSpec{ + "subscriber fails": { + subs: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: replaceCallable, + SubscriberURI: replaceSubscriber, }, }, - callable: func(writer http.ResponseWriter, _ *http.Request) { + subscriber: func(writer http.ResponseWriter, _ *http.Request) { writer.WriteHeader(http.StatusNotFound) }, expectedStatus: http.StatusInternalServerError, }, - "callable succeeds, sinkable fails": { - subs: []duckv1alpha1.ChannelSubscriberSpec{ + "subscriber succeeds, result fails": { + subs: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: replaceCallable, - SinkableDomain: replaceSinkable, + SubscriberURI: replaceSubscriber, + ReplyURI: replaceChannel, }, }, - callable: callableSucceed, - sinkable: func(writer http.ResponseWriter, _ *http.Request) { + subscriber: callableSucceed, + channel: func(writer http.ResponseWriter, _ *http.Request) { writer.WriteHeader(http.StatusForbidden) }, expectedStatus: http.StatusInternalServerError, }, "one sub succeeds": { - subs: []duckv1alpha1.ChannelSubscriberSpec{ + subs: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: replaceCallable, - SinkableDomain: replaceSinkable, + SubscriberURI: replaceSubscriber, + ReplyURI: replaceChannel, }, }, - callable: callableSucceed, - sinkable: func(writer http.ResponseWriter, _ *http.Request) { + subscriber: callableSucceed, + channel: func(writer http.ResponseWriter, _ *http.Request) { writer.WriteHeader(http.StatusAccepted) }, expectedStatus: http.StatusAccepted, }, "one sub succeeds, one sub fails": { - subs: []duckv1alpha1.ChannelSubscriberSpec{ + subs: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: replaceCallable, - SinkableDomain: replaceSinkable, + SubscriberURI: replaceSubscriber, + ReplyURI: replaceChannel, }, { - CallableDomain: replaceCallable, - SinkableDomain: replaceSinkable, + SubscriberURI: replaceSubscriber, + ReplyURI: replaceChannel, }, }, - callable: callableSucceed, - sinkable: (&succeedOnce{}).handler, + subscriber: callableSucceed, + channel: (&succeedOnce{}).handler, expectedStatus: http.StatusInternalServerError, }, "all subs succeed": { - subs: []duckv1alpha1.ChannelSubscriberSpec{ + subs: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: replaceCallable, - SinkableDomain: replaceSinkable, + SubscriberURI: replaceSubscriber, + ReplyURI: replaceChannel, }, { - CallableDomain: replaceCallable, - SinkableDomain: replaceSinkable, + SubscriberURI: replaceSubscriber, + ReplyURI: replaceChannel, }, { - CallableDomain: replaceCallable, - SinkableDomain: replaceSinkable, + SubscriberURI: replaceSubscriber, + ReplyURI: replaceChannel, }, }, - callable: callableSucceed, - sinkable: func(writer http.ResponseWriter, _ *http.Request) { + subscriber: callableSucceed, + channel: func(writer http.ResponseWriter, _ *http.Request) { writer.WriteHeader(http.StatusAccepted) }, expectedStatus: http.StatusAccepted, @@ -184,22 +185,22 @@ func TestFanoutHandler_ServeHTTP(t *testing.T) { } t.Run(n, func(t *testing.T) { callableServer := httptest.NewServer(&fakeHandler{ - handler: tc.callable, + handler: tc.subscriber, }) defer callableServer.Close() - sinkableServer := httptest.NewServer(&fakeHandler{ - handler: tc.sinkable, + channelServer := httptest.NewServer(&fakeHandler{ + handler: tc.channel, }) - defer sinkableServer.Close() + defer channelServer.Close() // Rewrite the subs to use the servers we just started. - subs := make([]duckv1alpha1.ChannelSubscriberSpec, 0) + subs := make([]eventingduck.ChannelSubscriberSpec, 0) for _, sub := range tc.subs { - if sub.CallableDomain == replaceCallable { - sub.CallableDomain = callableServer.URL[7:] // strip the leading 'http://' + if sub.SubscriberURI == replaceSubscriber { + sub.SubscriberURI = callableServer.URL[7:] // strip the leading 'http://' } - if sub.SinkableDomain == replaceSinkable { - sub.SinkableDomain = sinkableServer.URL[7:] // strip the leading 'http://' + if sub.ReplyURI == replaceChannel { + sub.ReplyURI = channelServer.URL[7:] // strip the leading 'http://' } subs = append(subs, sub) } diff --git a/pkg/sidecar/multichannelfanout/multi_channel_fanout_handler_test.go b/pkg/sidecar/multichannelfanout/multi_channel_fanout_handler_test.go index 3bc5e6f0faf..02cad30d9e1 100644 --- a/pkg/sidecar/multichannelfanout/multi_channel_fanout_handler_test.go +++ b/pkg/sidecar/multichannelfanout/multi_channel_fanout_handler_test.go @@ -18,14 +18,15 @@ package multichannelfanout import ( "fmt" - "github.com/google/go-cmp/cmp" - "github.com/knative/eventing/pkg/sidecar/fanout" - duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" - "go.uber.org/zap" "net/http" "net/http/httptest" "strings" "testing" + + "github.com/google/go-cmp/cmp" + eventingduck "github.com/knative/eventing/pkg/apis/duck/v1alpha1" + "github.com/knative/eventing/pkg/sidecar/fanout" + "go.uber.org/zap" ) const ( @@ -108,9 +109,9 @@ func TestCopyWithNewConfig(t *testing.T) { Namespace: "default", Name: "c1", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: "callabledomain", + SubscriberURI: "subscriberdomain", }, }, }, @@ -123,9 +124,9 @@ func TestCopyWithNewConfig(t *testing.T) { Namespace: "default", Name: "somethingdifferent", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - SinkableDomain: "sinkabledomain", + ReplyURI: "replydomain", }, }, }, @@ -161,9 +162,9 @@ func TestConfigDiff(t *testing.T) { Namespace: "default", Name: "c1", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: "callabledomain", + SubscriberURI: "subscriberdomain", }, }, }, @@ -191,9 +192,9 @@ func TestConfigDiff(t *testing.T) { Namespace: "default", Name: "c1", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: "different", + SubscriberURI: "different", }, }, }, @@ -238,9 +239,9 @@ func TestServeHTTP(t *testing.T) { Namespace: "default", Name: "first-channel", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - SinkableDomain: replaceDomain, + ReplyURI: replaceDomain, }, }, }, @@ -258,9 +259,9 @@ func TestServeHTTP(t *testing.T) { Namespace: "default", Name: "first-channel", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - SinkableDomain: "first-to-domain", + ReplyURI: "first-to-domain", }, }, }, @@ -269,9 +270,9 @@ func TestServeHTTP(t *testing.T) { Namespace: "default", Name: "second-channel", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: replaceDomain, + SubscriberURI: replaceDomain, }, }, }, @@ -317,11 +318,11 @@ func TestServeHTTP(t *testing.T) { func replaceDomains(config Config, replacement string) { for i, cc := range config.ChannelConfigs { for j, sub := range cc.FanoutConfig.Subscriptions { - if sub.CallableDomain == replaceDomain { - sub.CallableDomain = replacement + if sub.SubscriberURI == replaceDomain { + sub.SubscriberURI = replacement } - if sub.SinkableDomain == replaceDomain { - sub.SinkableDomain = replacement + if sub.ReplyURI == replaceDomain { + sub.ReplyURI = replacement } cc.FanoutConfig.Subscriptions[j] = sub } diff --git a/pkg/sidecar/multichannelfanout/parse_test.go b/pkg/sidecar/multichannelfanout/parse_test.go index 568ac7d3391..8ef86bc7542 100644 --- a/pkg/sidecar/multichannelfanout/parse_test.go +++ b/pkg/sidecar/multichannelfanout/parse_test.go @@ -17,12 +17,13 @@ limitations under the License. package multichannelfanout import ( + "strings" + "testing" + "github.com/google/go-cmp/cmp" + eventingduck "github.com/knative/eventing/pkg/apis/duck/v1alpha1" "github.com/knative/eventing/pkg/sidecar/fanout" - duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" "go.uber.org/zap" - "strings" - "testing" ) func TestConfigMapData(t *testing.T) { @@ -33,11 +34,11 @@ func TestConfigMapData(t *testing.T) { expectedErr bool }{ { - name: "no data", - expected: &Config {}, + name: "no data", + expected: &Config{}, }, { - name: "invalid YAML", + name: "invalid YAML", config: ` key: - value @@ -56,27 +57,27 @@ func TestConfigMapData(t *testing.T) { expectedErr: true, }, { - name: "valid", + name: "valid", config: ` channelConfigs: - namespace: default name: c1 fanoutConfig: subscriptions: - - callableDomain: event-changer.default.svc.cluster.local - sinkableDomain: message-dumper-bar.default.svc.cluster.local - - callableDomain: message-dumper-foo.default.svc.cluster.local - - sinkableDomain: message-dumper-bar.default.svc.cluster.local + - subscriberURI: event-changer.default.svc.cluster.local + replyURI: message-dumper-bar.default.svc.cluster.local + - subscriberURI: message-dumper-foo.default.svc.cluster.local + - replyURI: message-dumper-bar.default.svc.cluster.local - namespace: default name: c2 fanoutConfig: subscriptions: - - sinkableDomain: message-dumper-foo.default.svc.cluster.local + - replyURI: message-dumper-foo.default.svc.cluster.local - namespace: other name: c3 fanoutConfig: subscriptions: - - sinkableDomain: message-dumper-foo.default.svc.cluster.local + - replyURI: message-dumper-foo.default.svc.cluster.local `, expected: &Config{ ChannelConfigs: []ChannelConfig{ @@ -84,16 +85,16 @@ func TestConfigMapData(t *testing.T) { Namespace: "default", Name: "c1", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: "event-changer.default.svc.cluster.local", - SinkableDomain: "message-dumper-bar.default.svc.cluster.local", + SubscriberURI: "event-changer.default.svc.cluster.local", + ReplyURI: "message-dumper-bar.default.svc.cluster.local", }, { - CallableDomain: "message-dumper-foo.default.svc.cluster.local", + SubscriberURI: "message-dumper-foo.default.svc.cluster.local", }, { - SinkableDomain: "message-dumper-bar.default.svc.cluster.local", + ReplyURI: "message-dumper-bar.default.svc.cluster.local", }, }, }, @@ -102,9 +103,9 @@ func TestConfigMapData(t *testing.T) { Namespace: "default", Name: "c2", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - SinkableDomain: "message-dumper-foo.default.svc.cluster.local", + ReplyURI: "message-dumper-foo.default.svc.cluster.local", }, }, }, @@ -113,9 +114,9 @@ func TestConfigMapData(t *testing.T) { Namespace: "other", Name: "c3", FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - SinkableDomain: "message-dumper-foo.default.svc.cluster.local", + ReplyURI: "message-dumper-foo.default.svc.cluster.local", }, }, }, @@ -126,7 +127,9 @@ func TestConfigMapData(t *testing.T) { } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - if tc.name != "valid" { return } + if tc.name != "valid" { + return + } c, e := Parse(zap.NewNop(), formatData(tc.config)) if tc.expectedErr { if e == nil { diff --git a/pkg/sidecar/swappable/swappable_test.go b/pkg/sidecar/swappable/swappable_test.go index 2c663bf800b..3993ed17fd9 100644 --- a/pkg/sidecar/swappable/swappable_test.go +++ b/pkg/sidecar/swappable/swappable_test.go @@ -18,14 +18,15 @@ package swappable import ( "fmt" - "github.com/knative/eventing/pkg/sidecar/fanout" - "github.com/knative/eventing/pkg/sidecar/multichannelfanout" - duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" - "go.uber.org/zap" "net/http" "net/http/httptest" "strings" "testing" + + eventingduck "github.com/knative/eventing/pkg/apis/duck/v1alpha1" + "github.com/knative/eventing/pkg/sidecar/fanout" + "github.com/knative/eventing/pkg/sidecar/multichannelfanout" + "go.uber.org/zap" ) const ( @@ -46,9 +47,9 @@ func TestHandler(t *testing.T) { Namespace: namespace, Name: name, FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: replaceDomain, + SubscriberURI: replaceDomain, }, }, }, @@ -61,9 +62,9 @@ func TestHandler(t *testing.T) { Namespace: namespace, Name: name, FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - SinkableDomain: replaceDomain, + ReplyURI: replaceDomain, }, }, }, @@ -98,9 +99,9 @@ func TestHandler_InvalidConfigChange(t *testing.T) { Namespace: namespace, Name: name, FanoutConfig: fanout.Config{ - Subscriptions: []duckv1alpha1.ChannelSubscriberSpec{ + Subscriptions: []eventingduck.ChannelSubscriberSpec{ { - CallableDomain: replaceDomain, + SubscriberURI: replaceDomain, }, }, }, @@ -203,11 +204,11 @@ func makeRequest(namespace, name string) *http.Request { func replaceDomains(c multichannelfanout.Config, replacement string) multichannelfanout.Config { for i, cc := range c.ChannelConfigs { for j, sub := range cc.FanoutConfig.Subscriptions { - if sub.SinkableDomain == replaceDomain { - sub.SinkableDomain = replacement + if sub.ReplyURI == replaceDomain { + sub.ReplyURI = replacement } - if sub.CallableDomain == replaceDomain { - sub.CallableDomain = replacement + if sub.SubscriberURI == replaceDomain { + sub.SubscriberURI = replacement } cc.FanoutConfig.Subscriptions[j] = sub } diff --git a/pkg/sources/container_event_source_job.go b/pkg/sources/container_event_source_job.go deleted file mode 100644 index 0f948778c6b..00000000000 --- a/pkg/sources/container_event_source_job.go +++ /dev/null @@ -1,164 +0,0 @@ -/* -Copyright 2018 The Knative 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 sources - -import ( - "encoding/base64" - "encoding/json" - - v1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - batchv1 "k8s.io/api/batch/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// FeedOperation specifies whether we're starting or stopping -type FeedOperation string - -const ( - // Each feed lifecycle pod gets these. - watcherContainerCPU = "400m" - - // START specifies a Feed should be started - StartFeed FeedOperation = "START" - - // STOP specifies a Feed should be stopped - StopFeed FeedOperation = "STOP" - - // FeedOperationKey is the Env variable that gets set to requested FeedOperationKey - FeedOperationKey string = "FEED_OPERATION" - - // FeedTriggerKey is the Env variable that gets set to serialized trigger configuration - FeedTriggerKey string = "FEED_TRIGGER" - - // FeedTargetKey is the Env variable that gets set to target of the feed - FeedTargetKey string = "FEED_TARGET" - - // FeedContextKey is the Env variable that gets set to serialized FeedContext if stopping - FeedContextKey string = "FEED_CONTEXT" - - // EventSourceParametersKey is the Env variable that gets set to serialized EventSourceSpec - EventSourceParametersKey string = "EVENT_SOURCE_PARAMETERS" - - // FeedNamespaceKey is the Env variable that gets set to namespace of the container performing - // the Feed lifecycle operation (aka, namespace of the feed). Uses downward api - FeedNamespaceKey string = "FEED_NAMESPACE" - - // FeedServiceAccount is the Env variable that gets set to serviceaccount of the - // container performing the Feed operation. Uses downward api - FeedServiceAccountKey string = "FEED_SERVICE_ACCOUNT" -) - -// MakeJob creates a Job to complete a start or stop operation for a Feed. -func MakeJob(feed *v1alpha1.Feed, spec *v1alpha1.EventSourceSpec, op FeedOperation, trigger EventTrigger, route string, feedContext FeedContext) (*batchv1.Job, error) { - labels := map[string]string{ - "app": "feedlifecyclepod", - } - - podTemplate, err := makePodTemplate(feed, spec, op, trigger, route, feedContext) - if err != nil { - return nil, err - } - - return &batchv1.Job{ - ObjectMeta: metav1.ObjectMeta{ - Name: "feedlet", - Namespace: feed.Namespace, - Labels: labels, - OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(feed, v1alpha1.SchemeGroupVersion.WithKind("Feed"))}, - }, - Spec: batchv1.JobSpec{ - Template: *podTemplate, - }, - }, nil -} - -// makePodTemplate creates a pod template for starting or stopping a feed. -func makePodTemplate(feed *v1alpha1.Feed, spec *v1alpha1.EventSourceSpec, op FeedOperation, trigger EventTrigger, route string, feedContext FeedContext) (*corev1.PodTemplateSpec, error) { - marshalledFeedContext, err := json.Marshal(feedContext) - if err != nil { - return nil, err - } - encodedFeedContext := base64.StdEncoding.EncodeToString(marshalledFeedContext) - - marshalledTrigger, err := json.Marshal(trigger) - if err != nil { - return nil, err - } - encodedTrigger := base64.StdEncoding.EncodeToString(marshalledTrigger) - - encodedParameters := "" - if spec.Parameters != nil { - marshalledParameters, err := json.Marshal(spec.Parameters) - if err != nil { - return nil, err - } - encodedParameters = base64.StdEncoding.EncodeToString(marshalledParameters) - } - - return &corev1.PodTemplateSpec{ - Spec: corev1.PodSpec{ - ServiceAccountName: feed.Spec.ServiceAccountName, - RestartPolicy: corev1.RestartPolicyNever, - Containers: []corev1.Container{ - { - Name: "feedlet", - Image: spec.Image, - ImagePullPolicy: "Always", - Env: []corev1.EnvVar{ - { - Name: FeedOperationKey, - Value: string(op), - }, - { - Name: FeedTargetKey, - Value: route, - }, - { - Name: FeedTriggerKey, - Value: encodedTrigger, - }, - { - Name: FeedContextKey, - Value: encodedFeedContext, - }, - { - Name: EventSourceParametersKey, - Value: encodedParameters, - }, - { - Name: FeedNamespaceKey, - ValueFrom: &corev1.EnvVarSource{ - FieldRef: &corev1.ObjectFieldSelector{ - FieldPath: "metadata.namespace", - }, - }, - }, - { - Name: FeedServiceAccountKey, - ValueFrom: &corev1.EnvVarSource{ - FieldRef: &corev1.ObjectFieldSelector{ - FieldPath: "spec.serviceAccountName", - }, - }, - }, - }, - }, - }, - }, - }, nil -} diff --git a/pkg/sources/event_source.go b/pkg/sources/event_source.go deleted file mode 100644 index ef3bf15c60e..00000000000 --- a/pkg/sources/event_source.go +++ /dev/null @@ -1,31 +0,0 @@ -/* -Copyright 2018 The Knative 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 sources - -const ( - // EventTriggerKey is the Env variable that gets set to EventTrigger - EventTriggerKey string = "EVENT_TRIGGER" -) - -type FeedContext struct { - Context map[string]interface{} -} - -type EventSource interface { - StartFeed(trigger EventTrigger, route string) (*FeedContext, error) - StopFeed(trigger EventTrigger, feedContext FeedContext) error -} diff --git a/pkg/sources/event_source_wrapper.go b/pkg/sources/event_source_wrapper.go deleted file mode 100644 index 806bb7356d4..00000000000 --- a/pkg/sources/event_source_wrapper.go +++ /dev/null @@ -1,56 +0,0 @@ -package sources - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "io/ioutil" - "log" - "os" -) - -func RunEventSource(es EventSource) { - op := os.Getenv(FeedOperationKey) - feedContext := os.Getenv(FeedContextKey) - trigger := os.Getenv(FeedTriggerKey) - target := os.Getenv(FeedTargetKey) - - decodedContext, _ := base64.StdEncoding.DecodeString(feedContext) - decodedTrigger, _ := base64.StdEncoding.DecodeString(trigger) - var c FeedContext - var t EventTrigger - - err := json.Unmarshal(decodedContext, &c) - if err != nil { - panic(fmt.Sprintf("can not unmarshal %q %q : %s", FeedContextKey, decodedContext, err)) - } - - err = json.Unmarshal(decodedTrigger, &t) - if err != nil { - panic(fmt.Sprintf("can not unmarshal %q %q : %s", FeedTriggerKey, decodedTrigger, err)) - } - - log.Printf("Doing %q target: %q Received feedContext as %+v trigger %+v", op, target, c, t) - if op == string(StartFeed) { - b, err := es.StartFeed(t, target) - if err != nil { - panic(fmt.Sprintf("Failed to start feed: %s", err)) - } - - marshalledFeedContext, err := json.Marshal(b) - if err != nil { - panic(fmt.Sprintf("Failed to marshal returned feed context %+v : %s", b, err)) - } - encodedFeedContext := base64.StdEncoding.EncodeToString(marshalledFeedContext) - - err = ioutil.WriteFile("/dev/termination-log", []byte(encodedFeedContext), os.ModeDevice) - if err != nil { - panic(fmt.Sprintf("Failed to write the termination message: %s", err)) - } - } else { - err = es.StopFeed(t, c) - if err != nil { - panic(fmt.Sprintf("Failed to stop feed: %s", err)) - } - } -} diff --git a/pkg/sources/event_trigger.go b/pkg/sources/event_trigger.go deleted file mode 100644 index a36ff723607..00000000000 --- a/pkg/sources/event_trigger.go +++ /dev/null @@ -1,17 +0,0 @@ -package sources - -// EventTrigger is a version of v1alpha1.EventTrigger where -// parameters have been resolved. -type EventTrigger struct { - // EventType is the type of event to be observed - EventType string `json:"eventType"` - - // Resource is the resource(s) from which to observe events. - Resource string `json:"resource"` - - // Service is the hostname of the service that should be observed. - Service string `json:"service"` - - // Parameters is an opaque map of configuration needed by the EventSource. - Parameters map[string]interface{} `json:"params"` -} diff --git a/pkg/sources/gcppubsub/eventsource.yaml b/pkg/sources/gcppubsub/eventsource.yaml deleted file mode 100644 index 62d8d483a5d..00000000000 --- a/pkg/sources/gcppubsub/eventsource.yaml +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright 2018 The Knative 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 -# -# https://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. - -apiVersion: feeds.knative.dev/v1alpha1 -kind: EventSource -metadata: - name: pubsub.googleapis.com - namespace: default -spec: - source: pubsub.googleapis.com - image: github.com/knative/eventing/pkg/sources/gcppubsub - parameters: - image: github.com/knative/eventing/pkg/sources/gcppubsub/receive_adapter diff --git a/pkg/sources/gcppubsub/eventtype.yaml b/pkg/sources/gcppubsub/eventtype.yaml deleted file mode 100644 index b86901eb734..00000000000 --- a/pkg/sources/gcppubsub/eventtype.yaml +++ /dev/null @@ -1,22 +0,0 @@ -# Copyright 2018 The Knative 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 -# -# https://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. - -apiVersion: feeds.knative.dev/v1alpha1 -kind: EventType -metadata: - name: google.pubsub.topic.publish - namespace: default -spec: - eventSource: pubsub.googleapis.com - description: "subscription for receiving pubsub messages" diff --git a/pkg/sources/gcppubsub/gcp_pubsub.go b/pkg/sources/gcppubsub/gcp_pubsub.go deleted file mode 100644 index 65bac12d013..00000000000 --- a/pkg/sources/gcppubsub/gcp_pubsub.go +++ /dev/null @@ -1,251 +0,0 @@ -/* -Copyright 2018 The Knative 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 main - -import ( - "encoding/base64" - "encoding/json" - "flag" - "fmt" - "log" - "os" - "regexp" - - "github.com/golang/glog" - "github.com/google/uuid" - "github.com/knative/eventing/pkg/sources" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - apierrs "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/tools/clientcmd" - - "cloud.google.com/go/pubsub" - "golang.org/x/net/context" -) - -const ( - deployment = "deployment" - subscription = "subscription" -) - -var ( - resourceFormat = regexp.MustCompile("^projects/([^/]+)/topics/([^/]+)$") -) - -type GCPPubSubEventSource struct { - // kubeclientset is a standard kubernetes clientset - kubeclientset kubernetes.Interface - image string - // namespace where the feed is created - feedNamespace string - // serviceAccount that the container runs as. Launches Receive Adapter with the - // same Service Account - feedServiceAccountName string -} - -// The Go client libraries make you explicitly reconstruct the URI through builder patterns, so we sadly must crack it first. -func crackTopic(topic string) (projectID, topicID string, err error) { - matches := resourceFormat.FindStringSubmatch(topic) - if len(matches) != 3 { - return "", "", fmt.Errorf(`Google Cloud Pub/Sub topics must match the pattern projects/*/topics/*";Got %q`, topic) - } - return matches[1], matches[2], nil -} - -func NewGCPPubSubEventSource(kubeclientset kubernetes.Interface, feedNamespace string, feedServiceAccountName string, image string) sources.EventSource { - glog.Infof("Image: %q", image) - return &GCPPubSubEventSource{kubeclientset: kubeclientset, feedNamespace: feedNamespace, feedServiceAccountName: feedServiceAccountName, image: image} -} - -func (t *GCPPubSubEventSource) StopFeed(trigger sources.EventTrigger, feedContext sources.FeedContext) error { - glog.Infof("Stopping GCP PUBSUB Feed with context %+v", feedContext) - - projectID, _, err := crackTopic(trigger.Resource) - if err != nil { - glog.Warningf("Failed to delete deployment: %s", err) - return err - } - - if _, ok := feedContext.Context[deployment]; ok { - deploymentName := feedContext.Context[deployment].(string) - - err = t.deleteWatcher(t.feedNamespace, deploymentName) - if err != nil { - glog.Warningf("Failed to delete deployment: %s", err) - return err - } - } - - if _, ok := feedContext.Context[subscription]; ok { - subscriptionName := feedContext.Context[subscription].(string) - ctx := context.Background() - // Creates a client. - client, err := pubsub.NewClient(ctx, projectID) - if err != nil { - glog.Infof("Failed to create client: %v", err) - return err - } - - sub := client.Subscription(subscriptionName) - err = sub.Delete(ctx) - if err != nil { - glog.Warningf("Failed to delete subscription %q : %s : %+v", subscriptionName, err, err) - // Return error only if it's something else than NotFound - rpcStatus := status.Convert(err) - if rpcStatus.Code() != codes.NotFound { - return err - } - glog.Infof("Subscription %q already deleted", subscriptionName) - } - } - return nil -} - -func (t *GCPPubSubEventSource) StartFeed(trigger sources.EventTrigger, route string) (*sources.FeedContext, error) { - glog.Infof("CREATING GCP PUBSUB feed") - - projectID, topicID, err := crackTopic(trigger.Resource) - if err != nil { - glog.Infof("Failed to create deployment: %v", err) - return nil, err - } - - // Just generate a random UUID as a subscriptionName - uuid, err := uuid.NewRandom() - if err != nil { - glog.Infof("Failed to get create random uuid: %v", err) - return nil, err - } - subscriptionName := fmt.Sprintf("sub-%s", uuid.String()) - - glog.Infof("ProjectID: %q Topic: %q SubscriptionName: %q Route: %s", projectID, topicID, subscriptionName, route) - - ctx := context.Background() - - // TODO: Create a unique credential here just for this watcher... - - // Creates a client. - client, err := pubsub.NewClient(ctx, projectID) - if err != nil { - glog.Infof("Failed to create client: %v", err) - return nil, err - } - - sub, err := client.CreateSubscription(ctx, subscriptionName, - pubsub.SubscriptionConfig{Topic: client.Topic(topicID)}) - if err != nil { - glog.Infof("Failed to create subscription (might already exist): %+v", err) - return nil, err - } - - glog.Infof("Created subscription: %v", sub) - - // Create actual watcher - deploymentName := subscriptionName - err = t.createWatcher(deploymentName, t.image, projectID, topicID, subscriptionName, route) - if err != nil { - glog.Infof("Failed to create deployment: %v", err) - - // delete the subscription so it's not left floating around. - errDelete := sub.Delete(ctx) - if errDelete != nil { - glog.Infof("Failed to delete subscription while trying to clean up %q : %s", subscriptionName, errDelete) - } - - return nil, err - } - - return &sources.FeedContext{ - Context: map[string]interface{}{ - subscription: subscriptionName, - deployment: deploymentName, - }}, nil - -} - -func (t *GCPPubSubEventSource) createWatcher(deploymentName string, image string, projectID string, topicID string, subscription string, route string) error { - dc := t.kubeclientset.AppsV1().Deployments(t.feedNamespace) - - // First, check if deployment exists already. - if _, err := dc.Get(deploymentName, metav1.GetOptions{}); err != nil { - if !apierrs.IsNotFound(err) { - glog.Infof("deployments.Get for %q failed: %s", deploymentName, err) - return err - } - glog.Infof("Deployment %q doesn't exist, creating", deploymentName) - } else { - glog.Infof("Found existing deployment %q", deploymentName) - return nil - } - - // TODO: Create ownerref to the feed so when the feed goes away deployment - // gets removed. Currently we manually delete the deployment. - deployment := MakeWatcherDeployment(t.feedNamespace, deploymentName, t.feedServiceAccountName, image, projectID, topicID, subscription, route) - _, createErr := dc.Create(deployment) - return createErr -} - -func (t *GCPPubSubEventSource) deleteWatcher(namespace string, deploymentName string) error { - dc := t.kubeclientset.AppsV1().Deployments(namespace) - - // First, check if deployment exists already. - if _, err := dc.Get(deploymentName, metav1.GetOptions{}); err != nil { - if !apierrs.IsNotFound(err) { - glog.Infof("deployments.Get for %q failed: %s", deploymentName, err) - return err - } - glog.Infof("Deployment %q already deleted", deploymentName) - return nil - } - - return dc.Delete(deploymentName, &metav1.DeleteOptions{}) -} - -type parameters struct { - Image string `json:"image,omitempty"` -} - -func main() { - flag.Parse() - - decodedParameters, _ := base64.StdEncoding.DecodeString(os.Getenv(sources.EventSourceParametersKey)) - - feedNamespace := os.Getenv(sources.FeedNamespaceKey) - feedServiceAccountName := os.Getenv(sources.FeedServiceAccountKey) - - var p parameters - err := json.Unmarshal(decodedParameters, &p) - if err != nil { - panic(fmt.Sprintf("can not unmarshal %q : %s", decodedParameters, err)) - } - - cfg, err := clientcmd.BuildConfigFromFlags("", "") - if err != nil { - glog.Fatalf("Error building kubeconfig: %v", err) - } - - kubeClient, err := kubernetes.NewForConfig(cfg) - if err != nil { - glog.Fatalf("Error building kubernetes clientset: %v", err) - } - - sources.RunEventSource(NewGCPPubSubEventSource(kubeClient, feedNamespace, feedServiceAccountName, p.Image)) - log.Printf("Done...") -} diff --git a/pkg/sources/gcppubsub/googleapis-serviceentry.yaml b/pkg/sources/gcppubsub/googleapis-serviceentry.yaml deleted file mode 100644 index 7e1ba890110..00000000000 --- a/pkg/sources/gcppubsub/googleapis-serviceentry.yaml +++ /dev/null @@ -1,65 +0,0 @@ -# Copyright 2018 The Knative 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. -apiVersion: networking.istio.io/v1alpha3 -kind: ServiceEntry -metadata: - name: googleapis -spec: - hosts: - - "*.googleapis.com" - - "accounts.google.com" - ports: - - number: 443 - name: https - protocol: HTTPS - location: MESH_EXTERNAL ---- -apiVersion: networking.istio.io/v1alpha3 -kind: ServiceEntry -metadata: - name: metadata-server-gke -spec: - hosts: - - metadata - ports: - - number: 80 - name: http - protocol: HTTP - - number: 443 - name: https - protocol: HTTPS - location: MESH_EXTERNAL - resolution: DNS - endpoints: - - address: 169.254.169.254 ---- -apiVersion: networking.istio.io/v1alpha3 -kind: ServiceEntry -metadata: - name: metadata-server -spec: - hosts: - - metadata.google.internal - addresses: - - 169.254.169.254 - ports: - - number: 80 - name: http - protocol: HTTP - - number: 443 - name: https - protocol: HTTPS - resolution: DNS - endpoints: - - address: 169.254.169.254 diff --git a/pkg/sources/gcppubsub/receive_adapter/kodata/LICENSE b/pkg/sources/gcppubsub/receive_adapter/kodata/LICENSE deleted file mode 120000 index 2a64f9d0fc6..00000000000 --- a/pkg/sources/gcppubsub/receive_adapter/kodata/LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../../LICENSE \ No newline at end of file diff --git a/pkg/sources/gcppubsub/receive_adapter/kodata/VENDOR-LICENSE b/pkg/sources/gcppubsub/receive_adapter/kodata/VENDOR-LICENSE deleted file mode 120000 index 681789ed22f..00000000000 --- a/pkg/sources/gcppubsub/receive_adapter/kodata/VENDOR-LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/pkg/sources/gcppubsub/receive_adapter/receive_adapter.go b/pkg/sources/gcppubsub/receive_adapter/receive_adapter.go deleted file mode 100644 index 1dce5d3e82e..00000000000 --- a/pkg/sources/gcppubsub/receive_adapter/receive_adapter.go +++ /dev/null @@ -1,97 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "io/ioutil" - "log" - "net/http" - "os" - - // Imports the Google Cloud Pub/Sub client package. - "cloud.google.com/go/pubsub" - "github.com/knative/eventing/pkg/event" - "golang.org/x/net/context" -) - -const ( - // Environment variable containing project id - envProject = "PROJECT_ID" - - // Environment variable containing topic id - envTopic = "TOPIC_ID" - - // Target for messages - envTarget = "TARGET" - - // Name of the subscription to use - envSubscription = "SUBSCRIPTION" -) - -func main() { - flag.Parse() - - projectID := os.Getenv(envProject) - topicID := os.Getenv(envTopic) - target := os.Getenv(envTarget) - subscriptionName := os.Getenv(envSubscription) - - log.Printf("projectID is: %q", projectID) - log.Printf("topicID is: %q", topicID) - log.Printf("subscriptionName is: %q", subscriptionName) - log.Printf("Target is: %q", target) - - ctx := context.Background() - source := fmt.Sprintf("//pubsub.googleapis.com/projects/%s/topics/%s", projectID, topicID) - - // Creates a client. - // TODO: Support additional ways of specifying the credentials for creating. - client, err := pubsub.NewClient(ctx, projectID) - if err != nil { - log.Fatalf("Failed to create client: %v", err) - } - - sub := client.Subscription(subscriptionName) - - err = sub.Receive(ctx, func(ctx context.Context, m *pubsub.Message) { - log.Printf("Got message: %s", m.Data) - err = postMessage(target, source, m) - if err != nil { - log.Printf("Failed to post message: %s", err) - m.Nack() - } else { - m.Ack() - } - }) - if err != nil { - log.Fatalf("Failed to create receive: %v", err) - } -} - -func postMessage(target string, source string, m *pubsub.Message) error { - URL := fmt.Sprintf("http://%s/", target) - ctx := event.EventContext{ - CloudEventsVersion: event.CloudEventsVersion, - EventType: "google.pubsub.topic.publish", - EventID: m.ID, - EventTime: m.PublishTime, - Source: source, - } - req, err := event.Binary.NewRequest(URL, m, ctx) - if err != nil { - log.Printf("Failed to marshal the message: %+v : %s", m, err) - return err - } - - log.Printf("Posting to %q", URL) - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - log.Printf("response Status: %s", resp.Status) - body, _ := ioutil.ReadAll(resp.Body) - log.Printf("response Body: %s", string(body)) - return nil -} diff --git a/pkg/sources/gcppubsub/receive_adapter/stub_test.go b/pkg/sources/gcppubsub/receive_adapter/stub_test.go deleted file mode 100644 index ee7bbe8c445..00000000000 --- a/pkg/sources/gcppubsub/receive_adapter/stub_test.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright 2018 The Knative 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 main - -import "testing" - -func TestStub(t *testing.T) { - // TODO: Implement tests in this directory, please. - // This file is used to make code coverage on this directly count. -} diff --git a/pkg/sources/gcppubsub/stub_test.go b/pkg/sources/gcppubsub/stub_test.go deleted file mode 100644 index ee7bbe8c445..00000000000 --- a/pkg/sources/gcppubsub/stub_test.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright 2018 The Knative 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 main - -import "testing" - -func TestStub(t *testing.T) { - // TODO: Implement tests in this directory, please. - // This file is used to make code coverage on this directly count. -} diff --git a/pkg/sources/gcppubsub/watcher_pod.go b/pkg/sources/gcppubsub/watcher_pod.go deleted file mode 100644 index 086a328e31f..00000000000 --- a/pkg/sources/gcppubsub/watcher_pod.go +++ /dev/null @@ -1,83 +0,0 @@ -/* -Copyright 2018 The Knative 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 main - -import ( - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -const ( - sidecarIstioInjectAnnotation = "sidecar.istio.io/inject" -) - -// MakeWatcherDeployment creates a deployment for a watcher. -// TODO: a whole bunch... -func MakeWatcherDeployment(namespace string, deploymentName string, serviceAccount string, image string, projectID string, topicID string, subscription string, route string) *appsv1.Deployment { - replicas := int32(1) - labels := map[string]string{ - "watcher": deploymentName, - } - return &appsv1.Deployment{ - ObjectMeta: metav1.ObjectMeta{ - Name: deploymentName, - Namespace: namespace, - Labels: labels, - }, - Spec: appsv1.DeploymentSpec{ - Replicas: &replicas, - Selector: &metav1.LabelSelector{MatchLabels: labels}, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: labels, - // Inject Istio so any connection made from the receive adapter - // goes through and is enforced by Istio. - Annotations: map[string]string{sidecarIstioInjectAnnotation: "true"}, - }, - Spec: corev1.PodSpec{ - ServiceAccountName: serviceAccount, - Containers: []corev1.Container{ - { - Name: "receive-adapter", - Image: image, - ImagePullPolicy: "Always", - Env: []corev1.EnvVar{ - { - Name: "PROJECT_ID", - Value: projectID, - }, - { - Name: "TOPIC_ID", - Value: topicID, - }, - { - Name: "SUBSCRIPTION", - Value: subscription, - }, - { - Name: "TARGET", - Value: route, - }, - }, - }, - }, - }, - }, - }, - } -} diff --git a/pkg/sources/github/README.md b/pkg/sources/github/README.md deleted file mode 100644 index c71e1061496..00000000000 --- a/pkg/sources/github/README.md +++ /dev/null @@ -1,99 +0,0 @@ -Knative GitHub Source -===================== - -This source will enable receiving of GitHub events from within Knative Eventing. - -## Events - -- dev.knative.github.pullrequest - -## Images - -Uses two images, the feedlet and the receive adapter. - -### Feedlet - -A Feedlet is a container to create or destroy event source bindings. - -The Feedlet is run as a Job by the Feed controller. - -This Feedlet will create the Receive Adapter and register a webhook in GitHub -for the account provided. - -### Receive Adapter - -The Receive Adapter is a Service.serving.knative.dev resource that is registered -to receive GitHub webhook requests. The source will wrap this request in a -CloudEvent and send it to the action provided. - -## Usage - -The GitHub Source expects there to be a secret in the following form: - -```yaml -apiVersion: v1 -kind: Secret -metadata: - name: githubsecret -type: Opaque -stringData: - githubCredentials: > - { - "accessToken": "", - "secretToken": "" - } - -``` - -The Feedlet requires a ServiceAccount to run as a cluster admin for the targeted namespace: - -```yaml -apiVersion: v1 -kind: ServiceAccount -metadata: - name: feed-sa - namespace: default ---- -apiVersion: rbac.authorization.k8s.io/v1beta1 -kind: ClusterRoleBinding -metadata: - name: feed-admin -subjects: - - kind: ServiceAccount - name: feed-sa - namespace: default -roleRef: - kind: ClusterRole - name: cluster-admin - apiGroup: rbac.authorization.k8s.io - -``` - -To create a Receive Adapter (via the Feedlet), a Flow needs to exist: - -```yaml -apiVersion: flows.knative.dev/v1alpha1 -kind: Flow -metadata: - name: my-github-flow - namespace: default -spec: - serviceAccountName: feed-sa - trigger: - eventType: pullrequest - resource: / # TODO: Fill this out - service: github - parameters: - secretName: githubsecret - secretKey: githubCredentials - parametersFrom: - - secretKeyRef: - name: githubsecret - key: githubCredentials - action: - target: - kind: Service - apiVersion: serving.knative.dev/v1alpha1 - name: my-service - -``` \ No newline at end of file diff --git a/pkg/sources/github/events.go b/pkg/sources/github/events.go deleted file mode 100644 index 310fd55287e..00000000000 --- a/pkg/sources/github/events.go +++ /dev/null @@ -1,32 +0,0 @@ -/* -Copyright 2018 The Knative 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 github - -const ( - // Event Names - PullrequestEvent = "dev.knative.github.pullrequest" - UnsupportedEvent = "dev.knative.github.unsupported" -) - -var CloudEventType = map[string]string{ - "pull_request": PullrequestEvent, - "": UnsupportedEvent, -} - -var GithubEventType = map[string]string{ - PullrequestEvent: "pull_request", -} diff --git a/pkg/sources/github/eventsource.yaml b/pkg/sources/github/eventsource.yaml deleted file mode 100644 index a86410f0a4b..00000000000 --- a/pkg/sources/github/eventsource.yaml +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright 2018 The Knative 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 -# -# https://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. - -apiVersion: feeds.knative.dev/v1alpha1 -kind: EventSource -metadata: - name: github - namespace: default -spec: - source: github - image: github.com/knative/eventing/pkg/sources/github/feedlet - parameters: - image: github.com/knative/eventing/pkg/sources/github/receive_adapter diff --git a/pkg/sources/github/eventtype.yaml b/pkg/sources/github/eventtype.yaml deleted file mode 100644 index 32069634693..00000000000 --- a/pkg/sources/github/eventtype.yaml +++ /dev/null @@ -1,22 +0,0 @@ -# Copyright 2018 The Knative 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 -# -# https://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. - -apiVersion: feeds.knative.dev/v1alpha1 -kind: EventType -metadata: - name: dev.knative.github.pullrequest - namespace: default -spec: - eventSource: github - description: "notifications on pullrequests" diff --git a/pkg/sources/github/feedlet/feedlet.go b/pkg/sources/github/feedlet/feedlet.go deleted file mode 100644 index 8e52a8953d1..00000000000 --- a/pkg/sources/github/feedlet/feedlet.go +++ /dev/null @@ -1,463 +0,0 @@ -/* -Copyright 2018 The Knative 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 main - -import ( - "context" - "flag" - "fmt" - "strconv" - "strings" - - apierrs "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "github.com/knative/eventing/pkg/sources" - servingclientset "github.com/knative/serving/pkg/client/clientset/versioned" - "golang.org/x/oauth2" - - "encoding/base64" - "encoding/json" - "os" - - ghclient "github.com/google/go-github/github" - "github.com/knative/eventing/pkg/sources/github" - "github.com/knative/eventing/pkg/sources/github/resources" - "github.com/knative/serving/pkg/apis/serving/v1alpha1" - "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/tools/clientcmd" - "log" - "time" -) - -/* -A Feedlet is a container to create or destroy event source bindings. -The Feedlet is run as a Job by the Feed controller. -*/ - -const ( - webhookIDKey = "id" - - // property bag keys - accessTokenKey = "accessToken" - secretTokenKey = "secretToken" - - // receiveAdapterSuffix is appended to the name of the service running the Receive Adapter - receiveAdapterSuffix = "rcvadptr" - - // watchTimeout is the timeout that the feedlet will wait for the Receiver Adapter to get a domain name. - watchTimeout = 5 * time.Minute - - // secretNameKey is the name of the secret that contains the GitHub credentials. - secretNameKey = "secretName" - // secretKeyKey is the name of key inside the secret that contains the GitHub credentials. - secretKeyKey = "secretKey" -) - -type githubEventSource struct { - // kubeclientset is a standard kubernetes clientset - kubeclientset kubernetes.Interface - // servingclientset is a clientset for serving API groups - servingclientset servingclientset.Interface - // namespace where the feed is created - feedNamespace string - // serviceAccount that the container runs as. Launches Receive Adapter with the - // same Service Account - feedServiceAccountName string - // image for the receive adapter - image string -} - -func NewGithubEventSource(kubeclientset kubernetes.Interface, servingclientset servingclientset.Interface, feedNamespace, feedServiceAccountName, image string) sources.EventSource { - return &githubEventSource{ - kubeclientset: kubeclientset, - servingclientset: servingclientset, - feedNamespace: feedNamespace, - feedServiceAccountName: feedServiceAccountName, - image: image, - } -} - -// TODO(n3wscott): Add a timeout for StopFeed. -func (t *githubEventSource) StopFeed(trigger sources.EventTrigger, feedContext sources.FeedContext) error { - log.Printf("stopping github webhook feed with context %+v", feedContext) - - return t.deleteWebhook(trigger, feedContext) -} - -// TODO(n3wscott): Add a timeout for StartFeed. -func (t *githubEventSource) StartFeed(trigger sources.EventTrigger, target string) (*sources.FeedContext, error) { - - // Create the Receive Adapter Service that will accept incoming requests from GitHub. - service, err := t.createReceiveAdapter(trigger, target) - if err != nil { - return nil, fmt.Errorf("failed to create service: %v", err) - } - - log.Printf("created Service: %+v", service) - - // Start watching the Receive Adapter Service for it's updated domain name. This will be passed - // to GitHub as part of the webhook registration. - receiveAdapterDomain, err := t.waitForServiceDomain(service.GetObjectMeta().GetName()) - if err != nil { - return nil, fmt.Errorf("failed to get the service: %v", err) - } - - return t.createWebhook(trigger, service.GetObjectMeta().GetName(), receiveAdapterDomain) -} - -func (t *githubEventSource) waitForServiceDomain(serviceName string) (string, error) { - sc := t.servingclientset.ServingV1alpha1().Services(t.feedNamespace) - - wt := int64(watchTimeout / time.Second) - opts := metav1.ListOptions{ - TypeMeta: metav1.TypeMeta{ - Kind: "Service", - APIVersion: "v1alpha1", - }, - FieldSelector: fmt.Sprintf("metadata.name=%s", serviceName), - LabelSelector: "receive-adapter=github", - Watch: true, - TimeoutSeconds: &wt, - } - - w, err := sc.Watch(opts) - if err != nil { - log.Printf("[%s] failed to create watch: %v", serviceName, err) - return "", err - } - - eventChan := w.ResultChan() - for { - event, more := <-eventChan - if !more { - return "", fmt.Errorf("[%s] watch channel closed, failed to observe Service domain update", serviceName) - } - switch event.Type { - case watch.Error: - return "", fmt.Errorf("[%s] watched Service error", serviceName) - case watch.Deleted: - return "", fmt.Errorf("[%s] watched Service deleted", serviceName) - case watch.Added, watch.Modified: - service, ok := event.Object.(*v1alpha1.Service) - if !ok { - log.Printf("[%s] expected a Service object, but got %T", serviceName, event.Object) - continue - } - if service.Name != serviceName { - log.Printf("Error: [%s] expected a service.Name %q to match expected serviceName %q", - serviceName, service.Name, serviceName) - continue - } - status := service.Status - if status.Domain != "" { - w.Stop() - return status.Domain, nil - } - - } - } -} - -func receiveAdapterName(trigger sources.EventTrigger) string { - // TODO(n3wscott): this needs more UUID on the end of it? - // TODO(n3wscott): Currently this needs to be deterministic so StopFeed can find the receive adapter. If the receive - // adapter name were added to the feed context, then this could be a uuid. There is an issue where where we will - // get blocked by a pre-existing conflicting name and we are not able to unblock or regenerate without deleting - // the feed and trying it again. - serviceName := fmt.Sprintf("%s-%s-%s", "github", trigger.Resource, receiveAdapterSuffix) - serviceName = strings.Replace(serviceName, "/", "-", -1) - serviceName = strings.Replace(serviceName, ".", "-", -1) - serviceName = strings.ToLower(serviceName) - return serviceName -} - -func (t *githubEventSource) createReceiveAdapter(trigger sources.EventTrigger, target string) (*v1alpha1.Service, error) { - sc := t.servingclientset.ServingV1alpha1().Services(t.feedNamespace) - - serviceName := receiveAdapterName(trigger) - - // First, check if service exists already. - if sc, err := sc.Get(serviceName, metav1.GetOptions{}); err != nil { - if !apierrs.IsNotFound(err) { - return nil, fmt.Errorf("service.Get for %q failed: %v", serviceName, err) - } - log.Printf("service %q doesn't exist, creating", serviceName) - } else { - log.Printf("found existing service %q", serviceName) - // Don't try again. - return sc, nil - } - - secretName, err := stringFrom(trigger.Parameters, secretNameKey) - if err != nil { - return nil, fmt.Errorf("failed to get secret name from trigger parameters: %v", err) - } - - secretKey, err := stringFrom(trigger.Parameters, secretKeyKey) - if err != nil { - return nil, fmt.Errorf("failed to get secret key from trigger parameters: %v", err) - } - - // TODO(n3wscott): if we add an owner reference here we can remove the delete service call on stopFeed - service := resources.MakeService(t.feedNamespace, serviceName, t.image, t.feedServiceAccountName, target, secretName, secretKey) - service, err = sc.Create(service) - if err != nil { - return nil, fmt.Errorf("failed to create service: %s", err) - } - - return service, nil -} - -func (t *githubEventSource) deleteReceiveAdapter(namespace string, serviceName string) error { - sc := t.servingclientset.ServingV1alpha1().Services(t.feedNamespace) - - // First, check if deployment exists already. - if _, err := sc.Get(serviceName, metav1.GetOptions{}); err != nil { - if !apierrs.IsNotFound(err) { - return fmt.Errorf("services.Get for %q failed: %v", serviceName, err) - } - log.Printf("service %q already deleted", serviceName) - // Don't try again. - return nil - } - - return sc.Delete(serviceName, &metav1.DeleteOptions{}) -} - -func (t *githubEventSource) deleteWebhook(trigger sources.EventTrigger, feedContext sources.FeedContext) error { - serviceName := receiveAdapterName(trigger) - err := t.deleteReceiveAdapter(t.feedNamespace, serviceName) - if err != nil { - log.Printf("Error: Failed to delete the ReceiveAdapter \"%s/%s\": %v", t.feedNamespace, serviceName, err) - // Continue deleting the webhook. - } - - owner, repo, err := parseOwnerRepoFrom(trigger.Resource) - if err != nil { - log.Printf("Error: Failed to parse owner and repo from tigger.resource: %v; bailing...", err) - // Don't try again. - return nil - } - - webhookID, err := webhookIDFrom(feedContext) - if err != nil { - log.Printf("Error: Failed to get webhook id from context: %v; bailing...", err) - // Don't try again. - return nil - } - - accessToken, err := stringFrom(trigger.Parameters, accessTokenKey) - if err != nil { - log.Printf("Error: Failed to get access token from trigger parameters: %v; bailing...", err) - // Don't try again. - return nil - } - - ctx := context.Background() - ts := oauth2.StaticTokenSource( - &oauth2.Token{AccessToken: accessToken}, - ) - tc := oauth2.NewClient(ctx, ts) - client := ghclient.NewClient(tc) - - _, err = client.Repositories.DeleteHook(ctx, owner, repo, webhookID) - if err != nil { - // Note: errResp.Message == "Not Found" is not ideal, but the gh errors are not very easy to parse. - // It would be better to look into the errResp.Errors[] and confirm that the issue is "not found". - if errResp, ok := err.(*ghclient.ErrorResponse); ok && errResp.Message == "Not Found" { - // If the webhook doesn't exist, nothing to do - log.Printf("webhook doesn't exist, nothing to delete") - return nil - } - return fmt.Errorf("failed to delete the webhook: %v", err) - } - log.Printf("deleted webhook \"%d\" successfully", webhookID) - return nil -} - -func (t *githubEventSource) createWebhook(trigger sources.EventTrigger, name, domain string) (*sources.FeedContext, error) { - - log.Printf("creating GitHub webhook") - - owner, repo, err := parseOwnerRepoFrom(trigger.Resource) - if err != nil { - return nil, err - } - - events, err := parseEventsFrom(trigger.EventType) - if err != nil { - return nil, err - } - - accessToken, err := stringFrom(trigger.Parameters, accessTokenKey) - if err != nil { - return nil, fmt.Errorf("failed to get access token from trigger parameters: %v", err) - } - - secretToken, err := stringFrom(trigger.Parameters, secretTokenKey) - if err != nil { - return nil, fmt.Errorf("failed to get secret token from trigger parameters: %v", err) - } - - ctx := context.Background() - ts := oauth2.StaticTokenSource( - &oauth2.Token{AccessToken: accessToken}, - ) - tc := oauth2.NewClient(ctx, ts) - - client := ghclient.NewClient(tc) - active := true - config := make(map[string]interface{}) - config["url"] = fmt.Sprintf("http://%s", domain) - config["content_type"] = "json" - config["secret"] = secretToken - - // GitHub hook names are required to be named "web" or the name of a GitHub service - hookname := "web" - hook := ghclient.Hook{ - Name: &hookname, - URL: &domain, - Events: events, - Active: &active, - Config: config, - } - - h, r, err := client.Repositories.CreateHook(ctx, owner, repo, &hook) - if err != nil { - log.Printf("create webhook error response:\n%+v", r) - return nil, fmt.Errorf("failed to create the webhook: %v", err) - } - log.Printf("created hook: %+v", h) - - return &sources.FeedContext{ - Context: map[string]interface{}{ - webhookIDKey: strconv.FormatInt(*h.ID, 10), - }}, nil -} - -type parameters struct { - Image string `json:"image,omitempty"` -} - -// The main entry point for the GitHub Feedlet -func main() { - flag.Parse() - - log.Printf("GitHub Feedlet starting...") - - decodedParameters, _ := base64.StdEncoding.DecodeString(os.Getenv(sources.EventSourceParametersKey)) - - var p parameters - err := json.Unmarshal(decodedParameters, &p) - if err != nil { - log.Printf("Fatal: can not unmarshal %q : %v", decodedParameters, err) - os.Exit(1) - } - - feedNamespace := os.Getenv(sources.FeedNamespaceKey) - if len(feedNamespace) == 0 { - log.Printf("Fatal: feed namespace not provided, expected envvar %q to be set", sources.FeedNamespaceKey) - os.Exit(1) - } - - feedServiceAccountName := os.Getenv(sources.FeedServiceAccountKey) - if len(feedServiceAccountName) == 0 { - log.Printf("Fatal: feed service account not provided, expected envvar %q to be set", sources.FeedServiceAccountKey) - os.Exit(1) - } - - cfg, err := clientcmd.BuildConfigFromFlags("", "") - if err != nil { - log.Printf("Error: error building kubeconfig: %v", err) - } - - kubeClient, err := kubernetes.NewForConfig(cfg) - if err != nil { - log.Printf("Error: error building kubernetes clientset: %v", err) - } - - servingClient, err := servingclientset.NewForConfig(cfg) - if err != nil { - log.Printf("Error: error building serving clientset: %v", err) - } - - sources.RunEventSource(NewGithubEventSource(kubeClient, servingClient, feedNamespace, feedServiceAccountName, p.Image)) - log.Printf("GitHub Feedlet finished") -} - -func webhookIDFrom(feedContext sources.FeedContext) (int64, error) { - webhookID, err := stringFrom(feedContext.Context, webhookIDKey) - if err != nil { - return 0, err - - } - id, err := int64From(webhookID) - if err != nil { - return 0, fmt.Errorf("failed to convert webhook %q to int64 : %v", webhookID, err) - } - return id, nil -} - -func int64From(strNum string) (int64, error) { - return strconv.ParseInt(strNum, 10, 64) -} - -// TODO(n3wscott): Move this to knative/pkg/context. -func stringFrom(bag map[string]interface{}, key string) (string, error) { - // check to see if the key is in the bag. - if _, ok := bag[key]; !ok { - return "", fmt.Errorf("%s not found", key) - } - value, ok := bag[key].(string) - if !ok { - return "", fmt.Errorf("value for %s was not a valid string", key) - } - return value, nil -} - -func parseOwnerRepoFrom(resource string) (string, string, error) { - if len(resource) == 0 { - return "", "", fmt.Errorf("resouce is empty") - } - components := strings.Split(resource, "/") - if len(components) != 2 { - return "", "", fmt.Errorf("resouce is malformatted, expected 'owner/repo' but found %q", resource) - } - owner := components[0] - if len(owner) == 0 { - return "", "", fmt.Errorf("owner is empty, expected 'owner/repo' but found %q", resource) - } - repo := components[1] - if len(repo) == 0 { - return "", "", fmt.Errorf("repo is empty, expected 'owner/repo' but found %q", resource) - } - - return owner, repo, nil -} - -func parseEventsFrom(eventType string) ([]string, error) { - if len(eventType) == 0 { - return []string(nil), fmt.Errorf("event type is empty") - } - event, ok := github.GithubEventType[eventType] - if !ok { - return []string(nil), fmt.Errorf("event type is unknown: %s", eventType) - } - return []string{event}, nil -} diff --git a/pkg/sources/github/feedlet/kodata/LICENSE b/pkg/sources/github/feedlet/kodata/LICENSE deleted file mode 120000 index 2a64f9d0fc6..00000000000 --- a/pkg/sources/github/feedlet/kodata/LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../../LICENSE \ No newline at end of file diff --git a/pkg/sources/github/feedlet/kodata/VENDOR-LICENSE b/pkg/sources/github/feedlet/kodata/VENDOR-LICENSE deleted file mode 120000 index 681789ed22f..00000000000 --- a/pkg/sources/github/feedlet/kodata/VENDOR-LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/pkg/sources/github/feedlet/stub_test.go b/pkg/sources/github/feedlet/stub_test.go deleted file mode 100644 index ee7bbe8c445..00000000000 --- a/pkg/sources/github/feedlet/stub_test.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright 2018 The Knative 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 main - -import "testing" - -func TestStub(t *testing.T) { - // TODO: Implement tests in this directory, please. - // This file is used to make code coverage on this directly count. -} diff --git a/pkg/sources/github/github-serviceentry.yaml b/pkg/sources/github/github-serviceentry.yaml deleted file mode 100644 index 9c9576aae7e..00000000000 --- a/pkg/sources/github/github-serviceentry.yaml +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright 2018 The Knative 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 -# -# https://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. -apiVersion: networking.istio.io/v1alpha3 -kind: ServiceEntry -metadata: - name: github-receive-adapter-ext -spec: - hosts: - - "*.github.com" - ports: - - number: 443 - name: https - protocol: HTTPS - location: MESH_EXTERNAL diff --git a/pkg/sources/github/receive_adapter/kodata/LICENSE b/pkg/sources/github/receive_adapter/kodata/LICENSE deleted file mode 120000 index 2a64f9d0fc6..00000000000 --- a/pkg/sources/github/receive_adapter/kodata/LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../../LICENSE \ No newline at end of file diff --git a/pkg/sources/github/receive_adapter/kodata/VENDOR-LICENSE b/pkg/sources/github/receive_adapter/kodata/VENDOR-LICENSE deleted file mode 120000 index 681789ed22f..00000000000 --- a/pkg/sources/github/receive_adapter/kodata/VENDOR-LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/pkg/sources/github/receive_adapter/receive_adapter.go b/pkg/sources/github/receive_adapter/receive_adapter.go deleted file mode 100644 index f4f75ebb75c..00000000000 --- a/pkg/sources/github/receive_adapter/receive_adapter.go +++ /dev/null @@ -1,151 +0,0 @@ -/* -Copyright 2018 The Knative 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 - - https://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 main - -import ( - "encoding/json" - "flag" - "fmt" - "os" - - "gopkg.in/go-playground/webhooks.v3" - gh "gopkg.in/go-playground/webhooks.v3/github" - - "io/ioutil" - "net/http" - - ghclient "github.com/google/go-github/github" - "github.com/google/uuid" - "github.com/knative/eventing/pkg/event" - "github.com/knative/eventing/pkg/sources/github" - "log" - "time" -) - -const ( - // Target for messages - envTarget = "TARGET" - // Environment variable containing json credentials - envSecret = "GITHUB_SECRET" -) - -// GithubHandler holds necessary objects for communicating with the Github. -type GithubHandler struct { - client *ghclient.Client - target string -} - -type GithubSecrets struct { - AccessToken string `json:"accessToken"` - SecretToken string `json:"secretToken"` -} - -// HandlePullRequest is invoked whenever a PullRequest is modified (created, updated, etc.) -func (h *GithubHandler) HandlePullRequest(payload interface{}, header webhooks.Header) { - log.Print("Handling Pull Request") - - hdr := http.Header(header) - - pl := payload.(gh.PullRequestPayload) - - source := pl.PullRequest.HTMLURL - - eventType, ok := github.CloudEventType[hdr.Get("X-GitHub-Event")] - if !ok { - eventType = github.UnsupportedEvent - } - - eventID := hdr.Get("X-GitHub-Delivery") - if len(eventID) == 0 { - if uuid, err := uuid.NewRandom(); err != nil { - eventID = uuid.String() - } - } - - postMessage(h.target, payload, source, eventType, eventID) -} - -func main() { - flag.Parse() - - target := os.Getenv(envTarget) - - log.Printf("Target is: %q", target) - - githubSecrets := os.Getenv(envSecret) - - var credentials GithubSecrets - err := json.Unmarshal([]byte(githubSecrets), &credentials) - if err != nil { - log.Fatalf("Failed to unmarshal credentials: %v", err) - return - } - - // Set up the auth for being able to talk to Github. - var tc *http.Client = nil - - client := ghclient.NewClient(tc) - - h := &GithubHandler{ - client: client, - target: target, - } - - hook := gh.New(&gh.Config{Secret: credentials.SecretToken}) - // TODO: GitHub has more than just Pull Request Events. This needs to - // handle them all? - hook.RegisterEvents(h.HandlePullRequest, gh.PullRequestEvent) - - // TODO(n3wscott): Do we need to configure the PORT? - err = webhooks.Run(hook, ":8080", "/") - if err != nil { - log.Fatalf("Failed to run the webhook") - } -} - -func postMessage(target string, payload interface{}, source, eventType, eventID string) error { - URL := fmt.Sprintf("http://%s/", target) - - ctx := event.EventContext{ - CloudEventsVersion: event.CloudEventsVersion, - EventType: eventType, - EventID: eventID, - EventTime: time.Now(), - Source: source, - } - req, err := event.Binary.NewRequest(URL, payload, ctx) - if err != nil { - log.Printf("Failed to marshal the message: %+v : %s", payload, err) - return err - } - - log.Printf("Posting to %q", URL) - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - // TODO: in general, receive adapters may have to be able to retry for error cases. - log.Printf("response Status: %s", resp.Status) - body, _ := ioutil.ReadAll(resp.Body) - log.Printf("response Body: %s", string(body)) - } - return nil -} diff --git a/pkg/sources/github/receive_adapter/stub_test.go b/pkg/sources/github/receive_adapter/stub_test.go deleted file mode 100644 index ee7bbe8c445..00000000000 --- a/pkg/sources/github/receive_adapter/stub_test.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright 2018 The Knative 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 main - -import "testing" - -func TestStub(t *testing.T) { - // TODO: Implement tests in this directory, please. - // This file is used to make code coverage on this directly count. -} diff --git a/pkg/sources/github/resources/service.go b/pkg/sources/github/resources/service.go deleted file mode 100644 index 23d1576b6bb..00000000000 --- a/pkg/sources/github/resources/service.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 2018 The Knative 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 resources - -import ( - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "github.com/knative/serving/pkg/apis/serving/v1alpha1" -) - -func MakeService(namespace, name, image, serviceAccount, target, githubSecret, githubSecretKey string) *v1alpha1.Service { - labels := map[string]string{ - "receive-adapter": "github", - } - return &v1alpha1.Service{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - Labels: labels, - }, - Spec: v1alpha1.ServiceSpec{ - RunLatest: &v1alpha1.RunLatestType{ - Configuration: v1alpha1.ConfigurationSpec{ - RevisionTemplate: v1alpha1.RevisionTemplateSpec{ - Spec: v1alpha1.RevisionSpec{ - ServiceAccountName: serviceAccount, - Container: corev1.Container{ - Image: image, - Env: []corev1.EnvVar{ - { - Name: "GITHUB_SECRET", - ValueFrom: &corev1.EnvVarSource{ - SecretKeyRef: &corev1.SecretKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: githubSecret, - }, - Key: githubSecretKey, - }, - }, - }, - { - Name: "TARGET", - Value: target, - }, - }, - }, - }, - }, - }, - }, - }, - } -} diff --git a/pkg/sources/github/resources/stub_test.go b/pkg/sources/github/resources/stub_test.go deleted file mode 100644 index d4c244afe73..00000000000 --- a/pkg/sources/github/resources/stub_test.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright 2018 The Knative 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 resources - -import "testing" - -func TestStub(t *testing.T) { - // TODO: Implement tests in this directory, please. - // This file is used to make code coverage on this directly count. -} diff --git a/pkg/sources/github/stub_test.go b/pkg/sources/github/stub_test.go deleted file mode 100644 index b92a55ef568..00000000000 --- a/pkg/sources/github/stub_test.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright 2018 The Knative 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 github - -import "testing" - -func TestStub(t *testing.T) { - // TODO: Implement tests in this directory, please. - // This file is used to make code coverage on this directly count. -} diff --git a/pkg/sources/k8sevents/eventsource.yaml b/pkg/sources/k8sevents/eventsource.yaml deleted file mode 100644 index d2cc3a3c150..00000000000 --- a/pkg/sources/k8sevents/eventsource.yaml +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright 2018 The Knative 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 -# -# https://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. - -apiVersion: feeds.knative.dev/v1alpha1 -kind: EventSource -metadata: - name: k8sevents - namespace: default -spec: - source: k8sevents - image: github.com/knative/eventing/pkg/sources/k8sevents - parameters: - image: github.com/knative/eventing/pkg/sources/k8sevents/receive_adapter diff --git a/pkg/sources/k8sevents/eventtype.yaml b/pkg/sources/k8sevents/eventtype.yaml deleted file mode 100644 index 5b7aa277609..00000000000 --- a/pkg/sources/k8sevents/eventtype.yaml +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright 2018 The Knative 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 -# -# https://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. - -apiVersion: feeds.knative.dev/v1alpha1 -kind: EventType -metadata: - # Warning: This event type has not been ratified by any K8S SIG and may - # change in future versions of Knative Eventing. - name: dev.knative.k8s.event - namespace: default -spec: - eventSource: k8sevents - description: "subscription for receiving k8s cluster events" diff --git a/pkg/sources/k8sevents/k8s_events.go b/pkg/sources/k8sevents/k8s_events.go deleted file mode 100644 index d4be32ab7a8..00000000000 --- a/pkg/sources/k8sevents/k8s_events.go +++ /dev/null @@ -1,171 +0,0 @@ -/* -Copyright 2018 The Knative 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 main - -import ( - "encoding/base64" - "encoding/json" - "flag" - "fmt" - "log" - "os" - - "github.com/golang/glog" - "github.com/google/uuid" - "github.com/knative/eventing/pkg/sources" - - apierrs "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/tools/clientcmd" -) - -const ( - projectIDKey = "projectID" - deployment = "deployment" - subscription = "subscription" -) - -type K8SEventsEventSource struct { - // kubeclientset is a standard kubernetes clientset - kubeclientset kubernetes.Interface - image string - // namespace where the feed is created - feedNamespace string - // serviceAccount that the container runs as. Launches Receive Adapter with the - // same Service Account - feedServiceAccountName string -} - -func NewK8SEventsEventSource(kubeclientset kubernetes.Interface, feedNamespace string, feedServiceAccountName string, image string) sources.EventSource { - glog.Infof("Image: %q", image) - return &K8SEventsEventSource{kubeclientset: kubeclientset, feedNamespace: feedNamespace, feedServiceAccountName: feedServiceAccountName, image: image} -} - -func (t *K8SEventsEventSource) StopFeed(trigger sources.EventTrigger, feedContext sources.FeedContext) error { - glog.Infof("Stopping K8S Events feed with context %+v", feedContext) - - deploymentName := feedContext.Context[deployment].(string) - - err := t.deleteWatcher(deploymentName) - if err != nil { - glog.Warningf("Failed to delete deployment: %s", err) - return err - } - return nil -} - -func (t *K8SEventsEventSource) StartFeed(trigger sources.EventTrigger, route string) (*sources.FeedContext, error) { - glog.Infof("CREATING K8S Event feed") - - namespace := trigger.Parameters["namespace"].(string) - - // Just generate a random UUID as a subscriptionName - uuid, err := uuid.NewRandom() - if err != nil { - glog.Infof("Failed to create new random uuid: %v", err) - return nil, err - } - subscriptionName := fmt.Sprintf("sub-%s", uuid.String()) - - glog.Infof("Namespace: %q Route: %s", namespace, route) - - // Create actual watcher - deploymentName := subscriptionName - err = t.createWatcher(deploymentName, t.image, namespace, route) - if err != nil { - glog.Infof("Failed to create deployment: %v", err) - return nil, err - } - - return &sources.FeedContext{ - Context: map[string]interface{}{ - subscription: subscriptionName, - deployment: deploymentName, - }}, nil - -} - -func (t *K8SEventsEventSource) createWatcher(deploymentName string, image string, eventNamespace string, route string) error { - dc := t.kubeclientset.AppsV1().Deployments(t.feedNamespace) - - // First, check if deployment exists already. - if _, err := dc.Get(deploymentName, metav1.GetOptions{}); err != nil { - if !apierrs.IsNotFound(err) { - glog.Infof("deployments.Get for %q failed: %v", deploymentName, err) - return err - } - glog.Infof("Deployment %q doesn't exist, creating", deploymentName) - } else { - glog.Infof("Found existing deployment %q", deploymentName) - return nil - } - - // TODO: Create ownerref to the feed so when the feed goes away deployment - // gets removed. Currently we manually delete the deployment. - deployment := MakeWatcherDeployment(t.feedNamespace, deploymentName, t.feedServiceAccountName, image, eventNamespace, route) - _, createErr := dc.Create(deployment) - return createErr -} - -func (t *K8SEventsEventSource) deleteWatcher(deploymentName string) error { - dc := t.kubeclientset.AppsV1().Deployments(t.feedNamespace) - - // First, check if deployment exists already. - if _, err := dc.Get(deploymentName, metav1.GetOptions{}); err != nil { - if !apierrs.IsNotFound(err) { - glog.Infof("deployments.Get for %q failed: %v", deploymentName, err) - return err - } - glog.Infof("Deployment %q already deleted", deploymentName) - return nil - } - - return dc.Delete(deploymentName, &metav1.DeleteOptions{}) -} - -type parameters struct { - Image string `json:"image,omitempty"` -} - -func main() { - flag.Parse() - - decodedParameters, _ := base64.StdEncoding.DecodeString(os.Getenv(sources.EventSourceParametersKey)) - - feedNamespace := os.Getenv(sources.FeedNamespaceKey) - feedServiceAccountName := os.Getenv(sources.FeedServiceAccountKey) - - var p parameters - err := json.Unmarshal(decodedParameters, &p) - if err != nil { - panic(fmt.Sprintf("can not unmarshal %q : %v", decodedParameters, err)) - } - - cfg, err := clientcmd.BuildConfigFromFlags("", "") - if err != nil { - glog.Fatalf("Error building kubeconfig: %v", err) - } - - kubeClient, err := kubernetes.NewForConfig(cfg) - if err != nil { - glog.Fatalf("Error building kubernetes clientset: %v", err) - } - - sources.RunEventSource(NewK8SEventsEventSource(kubeClient, feedNamespace, feedServiceAccountName, p.Image)) - log.Printf("Done...") -} diff --git a/pkg/sources/k8sevents/kodata/LICENSE b/pkg/sources/k8sevents/kodata/LICENSE deleted file mode 120000 index 14776154326..00000000000 --- a/pkg/sources/k8sevents/kodata/LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../LICENSE \ No newline at end of file diff --git a/pkg/sources/k8sevents/kodata/VENDOR-LICENSE b/pkg/sources/k8sevents/kodata/VENDOR-LICENSE deleted file mode 120000 index 7322c09d957..00000000000 --- a/pkg/sources/k8sevents/kodata/VENDOR-LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/pkg/sources/k8sevents/receive_adapter/kodata/LICENSE b/pkg/sources/k8sevents/receive_adapter/kodata/LICENSE deleted file mode 120000 index 2a64f9d0fc6..00000000000 --- a/pkg/sources/k8sevents/receive_adapter/kodata/LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../../LICENSE \ No newline at end of file diff --git a/pkg/sources/k8sevents/receive_adapter/kodata/VENDOR-LICENSE b/pkg/sources/k8sevents/receive_adapter/kodata/VENDOR-LICENSE deleted file mode 120000 index 681789ed22f..00000000000 --- a/pkg/sources/k8sevents/receive_adapter/kodata/VENDOR-LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/pkg/sources/k8sevents/receive_adapter/receive_adapter.go b/pkg/sources/k8sevents/receive_adapter/receive_adapter.go deleted file mode 100644 index 76cbc97a280..00000000000 --- a/pkg/sources/k8sevents/receive_adapter/receive_adapter.go +++ /dev/null @@ -1,194 +0,0 @@ -/* -Copyright 2018 The Knative 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 main - -import ( - "flag" - "fmt" - "io/ioutil" - "log" - "net/http" - "os" - "strings" - - "github.com/golang/glog" - "github.com/knative/eventing/pkg/event" - "github.com/knative/pkg/signals" - corev1 "k8s.io/api/core/v1" - coreinformers "k8s.io/client-go/informers/core/v1" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/tools/cache" - "k8s.io/client-go/tools/clientcmd" -) - -const ( - // Target for messages - envTarget = "TARGET" - // Namespace to watch - envNamespace = "NAMESPACE" -) - -type EventWatcher struct { - target string -} - -func NewEventWatcher(target string) *EventWatcher { - return &EventWatcher{target: target} -} - -func (e *EventWatcher) updateEvent(old, new interface{}) { - e.addEvent(new) -} - -func (e *EventWatcher) addEvent(new interface{}) { - event := new.(*corev1.Event) - log.Printf("GOT EVENT: %+v", event) - postMessage(e.target, event) -} - -func main() { - flag.Parse() - - // set up signals so we handle the first shutdown signal gracefully - stopCh := signals.SetupSignalHandler() - - target := os.Getenv(envTarget) - namespace := os.Getenv(envNamespace) - - log.Printf("Target is: %q", target) - log.Printf("Namespace is: %q", namespace) - - cfg, err := clientcmd.BuildConfigFromFlags("", "") - if err != nil { - log.Fatalf("Error building kubeconfig: %v", err) - } - - kubeClient, err := kubernetes.NewForConfig(cfg) - if err != nil { - log.Fatalf("Error building kubernetes clientset: %v", err) - } - - log.Printf("Creating a new Event Watcher...") - watcher := NewEventWatcher(target) - - eventsInformer := coreinformers.NewFilteredEventInformer( - kubeClient, namespace, 0, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, nil) - - eventsInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: watcher.addEvent, - UpdateFunc: watcher.updateEvent, - }) - - log.Printf("Starting eventsInformer...") - go eventsInformer.Run(stopCh) - - log.Printf("Waiting for caches to sync...") - if ok := cache.WaitForCacheSync(stopCh, eventsInformer.HasSynced); !ok { - glog.Fatalf("Failed to wait for events cache to sync") - } - log.Printf("Caches synced...") - <-stopCh - log.Printf("Exiting...") -} - -// Creates a URI of the form found in object metadata selfLinks -// Format looks like: /apis/feeds.knative.dev/v1alpha1/namespaces/default/feeds/k8s-events-example -// KNOWN ISSUES: -// * ObjectReference.APIVersion has no version information (e.g. serving.knative.dev rather than serving.knative.dev/v1alpha1) -// * ObjectReference does not have enough information to create the pluaralized list type (e.g. "revisions" from kind: Revision) -// -// Track these issues at https://github.com/kubernetes/kubernetes/issues/66313 -// We could possibly work around this by adding a lister for the resources referenced by these events. -func createSelfLink(o corev1.ObjectReference) string { - collectionNameHack := strings.ToLower(o.Kind) + "s" - versionNameHack := o.APIVersion - - // Core API types don't have a separate package name and only have a version string (e.g. /apis/v1/namespaces/default/pods/myPod) - // To avoid weird looking strings like "v1/versionUnknown" we'll sniff for a "." in the version - if strings.Contains(versionNameHack, ".") && !strings.Contains(versionNameHack, "/") { - versionNameHack = versionNameHack + "/versionUnknown" - } - return fmt.Sprintf("/apis/%s/namespaces/%s/%s/%s", versionNameHack, o.Namespace, collectionNameHack, o.Name) -} - -// Creates a CloudEvent Context for a given K8S event. For clarity, the following is a spew-dump -// of a real K8S event: -// &Event{ -// ObjectMeta:k8s_io_apimachinery_pkg_apis_meta_v1.ObjectMeta{ -// Name:k8s-events-00001.1542495ae3f5fbba, -// Namespace:default, -// SelfLink:/api/v1/namespaces/default/events/k8s-events-00001.1542495ae3f5fbba, -// UID:fc2fffb3-8a12-11e8-8874-42010a8a0fd9, -// ResourceVersion:2729, -// Generation:0, -// CreationTimestamp:2018-07-17 22:44:37 +0000 UTC, -// }, -// InvolvedObject:ObjectReference{ -// Kind:Revision, -// Namespace:default, -// Name:k8s-events-00001, -// UID:f5c19306-8a12-11e8-8874-42010a8a0fd9, -// APIVersion:serving.knative.dev, -// ResourceVersion:42683, -// }, -// Reason:RevisionReady, -// Message:Revision becomes ready upon endpoint "k8s-events-00001-service" becoming ready, -// Source:EventSource{ -// Component:revision-controller, -// }, -// FirstTimestamp:2018-07-17 22:44:37 +0000 UTC, -// LastTimestamp:2018-07-17 22:49:40 +0000 UTC, -// Count:91, -// Type:Normal, -// EventTime:0001-01-01 00:00:00 +0000 UTC, -// } -func cloudEventsContext(m *corev1.Event) *event.EventContext { - return &event.EventContext{ - // Events are themselves object and have a unique UUID. Could also have used the UID - CloudEventsVersion: event.CloudEventsVersion, - EventType: "dev.knative.k8s.event", - EventID: string(m.ObjectMeta.UID), - Source: createSelfLink(m.InvolvedObject), - EventTime: m.ObjectMeta.CreationTimestamp.Time, - } -} - -func postMessage(target string, m *corev1.Event) error { - ctx := cloudEventsContext(m) - - URL := fmt.Sprintf("http://%s/", target) - log.Printf("Posting to %q", URL) - // Explicitly using Binary encoding so that Istio, et. al. can better inspect - // event metadata. - req, err := event.Binary.NewRequest(URL, m, *ctx) - if err != nil { - log.Printf("Failed to create http request: %s", err) - return err - } - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - log.Printf("Failed to do POST: %v", err) - return err - } - defer resp.Body.Close() - log.Printf("response Status: %s", resp.Status) - body, _ := ioutil.ReadAll(resp.Body) - log.Printf("response Body: %s", string(body)) - return nil -} diff --git a/pkg/sources/k8sevents/receive_adapter/stub_test.go b/pkg/sources/k8sevents/receive_adapter/stub_test.go deleted file mode 100644 index ee7bbe8c445..00000000000 --- a/pkg/sources/k8sevents/receive_adapter/stub_test.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright 2018 The Knative 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 main - -import "testing" - -func TestStub(t *testing.T) { - // TODO: Implement tests in this directory, please. - // This file is used to make code coverage on this directly count. -} diff --git a/pkg/sources/k8sevents/stub_test.go b/pkg/sources/k8sevents/stub_test.go deleted file mode 100644 index ee7bbe8c445..00000000000 --- a/pkg/sources/k8sevents/stub_test.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright 2018 The Knative 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 main - -import "testing" - -func TestStub(t *testing.T) { - // TODO: Implement tests in this directory, please. - // This file is used to make code coverage on this directly count. -} diff --git a/pkg/sources/k8sevents/watcher_pod.go b/pkg/sources/k8sevents/watcher_pod.go deleted file mode 100644 index 0fee312d272..00000000000 --- a/pkg/sources/k8sevents/watcher_pod.go +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright 2018 The Knative 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 main - -import ( - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -const ( - sidecarIstioInjectAnnotation = "sidecar.istio.io/inject" -) - -// MakeWatcherDeployment creates a deployment for a watcher. -// TODO: a whole bunch... -func MakeWatcherDeployment(namespace string, deploymentName string, serviceAccount string, image string, eventNamespace string, route string) *appsv1.Deployment { - replicas := int32(1) - labels := map[string]string{ - "watcher": deploymentName, - } - return &appsv1.Deployment{ - ObjectMeta: metav1.ObjectMeta{ - Name: deploymentName, - Namespace: namespace, - Labels: labels, - }, - Spec: appsv1.DeploymentSpec{ - Replicas: &replicas, - Selector: &metav1.LabelSelector{MatchLabels: labels}, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: labels, - // Inject Istio so any connection made from the receive adapter - // goes through and is enforced by Istio. - Annotations: map[string]string{sidecarIstioInjectAnnotation: "true"}, - }, - Spec: corev1.PodSpec{ - ServiceAccountName: serviceAccount, - Containers: []corev1.Container{ - { - Name: "receive-adapter", - Image: image, - ImagePullPolicy: "Always", - Env: []corev1.EnvVar{ - { - Name: "TARGET", - Value: route, - }, - { - Name: "NAMESPACE", - Value: eventNamespace, - }, - }, - }, - }, - }, - }, - }, - } -} diff --git a/pkg/sources/stub_test.go b/pkg/sources/stub_test.go deleted file mode 100644 index 46f51918354..00000000000 --- a/pkg/sources/stub_test.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright 2018 The Knative 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 sources - -import "testing" - -func TestStub(t *testing.T) { - // TODO: Implement tests in this directory, please. - // This file is used to make code coverage on this directly count. -} diff --git a/sample/README.md b/sample/README.md index 8d41f0c6cf3..69f85cf45ca 100644 --- a/sample/README.md +++ b/sample/README.md @@ -1,12 +1,3 @@ # Samples -This location is a staging ground for _Knative eventing_ samples, which are being moved to [the docs repository](https://github.com/knative/docs/tree/master/eventing/samples). - -The `docs` repo contains the following best-maintained samples: - -* [Handling Kubernetes events](https://github.com/knative/docs/tree/master/eventing/samples/k8s-events) - - A simple handler for processing k8s events from the local cluster. -* [Binding running services to an IoT core](https://github.com/knative/docs/tree/master/eventing/samples/event-flow) - - A sample using Google PubSub to read events from Google's IoT core. -* [Github Pull Request Handler](https://github.com/knative/docs/tree/master/eventing/samples/github-events) - - A simple handler for Github Pull Requests +_Knative eventing_ samples have moved to [the docs repository](https://github.com/knative/docs/tree/master/eventing/samples). diff --git a/test/README.md b/test/README.md index 20ca7d73919..5b02898ee2f 100644 --- a/test/README.md +++ b/test/README.md @@ -84,7 +84,10 @@ A docker tag is mandatory to avoid issues with using `latest` tag for images dep ### Adding new test images -New test image paths should be placed in `./test/image_paths.txt`. +New test images should be placed in `./test/test_images`. For each image create a new sub-folder +and include a Go file that will be an entry point to the application. This Go file should use the +package "main" and include the function main(). It is a good practice to include a readme file as well. +When uploading test images, `ko` will build an image from this folder. ## Flags diff --git a/test/cleanup.go b/test/cleanup.go index 150160866e6..ddaf2b408d7 100644 --- a/test/cleanup.go +++ b/test/cleanup.go @@ -85,6 +85,12 @@ func (c *Cleaner) Add(group string, version string, resource string, namespace s // Clean will delete all registered resources func (c *Cleaner) Clean(awaitDeletion bool) error { for _, deleter := range c.resourcesToClean { + r, err := deleter.Resource.Get(deleter.Name, metav1.GetOptions{}) + if err != nil { + c.logger.Errorf("Failed to get to-be cleaned resource %q : %s", deleter.Name, err) + } else { + c.logger.Infof("Cleaning resource: %q\n%+v", deleter.Name, r) + } if err := deleter.Resource.Delete(deleter.Name, nil); err != nil { c.logger.Errorf("Error: %v", err) } else if awaitDeletion { diff --git a/test/clients.go b/test/clients.go index cf2e447da02..34ab9e01a81 100644 --- a/test/clients.go +++ b/test/clients.go @@ -18,6 +18,7 @@ limitations under the License. package test import ( + sources "github.com/knative/eventing-sources/pkg/client/clientset/versioned" eventing "github.com/knative/eventing/pkg/client/clientset/versioned" "github.com/knative/pkg/test" serving "github.com/knative/serving/pkg/client/clientset/versioned" @@ -32,6 +33,7 @@ type Clients struct { Serving *serving.Clientset Eventing *eventing.Clientset Dynamic dynamic.Interface + Sources *sources.Clientset } // NewClients instantiates and returns several clientsets required for making request to the @@ -63,6 +65,11 @@ func NewClients(configPath string, clusterName string, namespace string) (*Clien return nil, err } + clients.Sources, err = sources.NewForConfig(cfg) + if err != nil { + return nil, err + } + return clients, nil } diff --git a/test/crd.go b/test/crd.go index ca93978d4c8..b65c68260d0 100644 --- a/test/crd.go +++ b/test/crd.go @@ -18,28 +18,24 @@ package test // crd contains functions that construct boilerplate CRD definitions. import ( - "fmt" - - channelsV1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - feedsV1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - flowsV1alpha1 "github.com/knative/eventing/pkg/apis/flows/v1alpha1" - "github.com/knative/serving/pkg/apis/serving/v1alpha1" + sourcesv1alpha1 "github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1" + "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" + servingv1alpha1 "github.com/knative/serving/pkg/apis/serving/v1alpha1" corev1 "k8s.io/api/core/v1" - rbacV1beta1 "k8s.io/api/rbac/v1beta1" + rbacv1beta1 "k8s.io/api/rbac/v1beta1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" ) // Route returns a Route object in namespace -func Route(name string, namespace string, configName string) *v1alpha1.Route { - return &v1alpha1.Route{ +func Route(name string, namespace string, configName string) *servingv1alpha1.Route { + return &servingv1alpha1.Route{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, Name: name, }, - Spec: v1alpha1.RouteSpec{ - Traffic: []v1alpha1.TrafficTarget{ - v1alpha1.TrafficTarget{ + Spec: servingv1alpha1.RouteSpec{ + Traffic: []servingv1alpha1.TrafficTarget{ + servingv1alpha1.TrafficTarget{ ConfigurationName: configName, Percent: 100, }, @@ -50,18 +46,18 @@ func Route(name string, namespace string, configName string) *v1alpha1.Route { // Configuration returns a Configuration object in namespace with the name names.Config // that uses the image specifed by imagePath. -func Configuration(name string, namespace string, imagePath string) *v1alpha1.Configuration { - return &v1alpha1.Configuration{ +func Configuration(name string, namespace string, imagePath string) *servingv1alpha1.Configuration { + return &servingv1alpha1.Configuration{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: namespace, }, - Spec: v1alpha1.ConfigurationSpec{ - RevisionTemplate: v1alpha1.RevisionTemplateSpec{ + Spec: servingv1alpha1.ConfigurationSpec{ + RevisionTemplate: servingv1alpha1.RevisionTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{"knative.dev/type": "container"}, }, - Spec: v1alpha1.RevisionSpec{ + Spec: servingv1alpha1.RevisionSpec{ Container: corev1.Container{ Image: imagePath, }, @@ -81,20 +77,20 @@ func ServiceAccount(name string, namespace string) *corev1.ServiceAccount { } } -// ClusterRoleBinding create ClusterRoleBinding for given subject and role -func ClusterRoleBinding(name string, namespace string, serviceAccount string, role string) *rbacV1beta1.ClusterRoleBinding { - return &rbacV1beta1.ClusterRoleBinding{ +// ClusterRoleBinding returns ClusterRoleBinding for given subject and role +func ClusterRoleBinding(name string, namespace string, serviceAccount string, role string) *rbacv1beta1.ClusterRoleBinding { + return &rbacv1beta1.ClusterRoleBinding{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, - Subjects: []rbacV1beta1.Subject{ + Subjects: []rbacv1beta1.Subject{ { Kind: "ServiceAccount", Name: serviceAccount, Namespace: namespace, }, }, - RoleRef: rbacV1beta1.RoleRef{ + RoleRef: rbacv1beta1.RoleRef{ Kind: "ClusterRole", Name: role, APIGroup: "rbac.authorization.k8s.io", @@ -102,82 +98,74 @@ func ClusterRoleBinding(name string, namespace string, serviceAccount string, ro } } -// ClusterBus returns ClusterBus object with given name and imagePath -func ClusterBus(name string, namespace string, imagePath string) *channelsV1alpha1.ClusterBus { - return &channelsV1alpha1.ClusterBus{ +// ClusterChannelProvisioner returns a ClusterChannelProvisioner for a given name +func ClusterChannelProvisioner(name string) *corev1.ObjectReference { + return &corev1.ObjectReference{ + Kind: "ClusterChannelProvisioner", + APIVersion: "eventing.knative.dev/v1alpha1", + Name: name, + } +} + +// ChannelRef returns an ObjectReference for a given Channel Name +func ChannelRef(name string) *corev1.ObjectReference { + return &corev1.ObjectReference{ + Kind: "Channel", + APIVersion: "eventing.knative.dev/v1alpha1", + Name: name, + } +} + +// Channel returns a Channel with the specified provisioner +func Channel(name string, namespace string, provisioner *corev1.ObjectReference) *v1alpha1.Channel { + return &v1alpha1.Channel{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: namespace, }, - Spec: channelsV1alpha1.ClusterBusSpec{ - Dispatcher: corev1.Container{ - Name: "dispatcher", - Image: imagePath, - Args: []string{"-logtostderr", "-stderrthreshold", "INFO"}, - }, + Spec: v1alpha1.ChannelSpec{ + Provisioner: provisioner, }, } } -// EventSource returns EventSource object using the given image paths -func EventSource(eventSource string, namespace string, eventSourceImagePath string, receiverAdapterImagePath string) *feedsV1alpha1.EventSource { - return &feedsV1alpha1.EventSource{ +// KubernetesEventSource returns a KubernetesEventSource sinking to specified channel +func KubernetesEventSource(name string, namespace string, targetNamespace string, serviceAccount string, channel *corev1.ObjectReference) *sourcesv1alpha1.KubernetesEventSource { + return &sourcesv1alpha1.KubernetesEventSource{ ObjectMeta: metav1.ObjectMeta{ - Name: eventSource, + Name: name, Namespace: namespace, }, - Spec: feedsV1alpha1.EventSourceSpec{ - CommonEventSourceSpec: feedsV1alpha1.CommonEventSourceSpec{ - Source: eventSource, - Image: eventSourceImagePath, - Parameters: &runtime.RawExtension{ - Raw: []byte(fmt.Sprintf(`{"image": "%s"}`, receiverAdapterImagePath)), - }, - }, + Spec: sourcesv1alpha1.KubernetesEventSourceSpec{ + Namespace: targetNamespace, + ServiceAccountName: serviceAccount, + Sink: channel, }, } } -// EventType returns an EventType object referencing given eventSource -func EventType(name string, namespace string, eventSource string) *feedsV1alpha1.EventType { - return &feedsV1alpha1.EventType{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - }, - Spec: feedsV1alpha1.EventTypeSpec{ - CommonEventTypeSpec: feedsV1alpha1.CommonEventTypeSpec{ - Description: "subscription for receiving k8s cluster events", - }, - EventSource: eventSource, +// SubscriberSpecForRoute returns a SubscriberSpec for a given Knative Service. +func SubscriberSpecForRoute(name string) *v1alpha1.SubscriberSpec { + return &v1alpha1.SubscriberSpec{ + Ref: &corev1.ObjectReference{ + Kind: "Route", + APIVersion: "serving.knative.dev/v1alpha1", + Name: name, }, } } -// Flow will return Flow object with given parameters -func Flow(flowName string, namespace string, serviceAccount string, eventType string, eventSource string, routeName string, testNamespace string) *flowsV1alpha1.Flow { - return &flowsV1alpha1.Flow{ +// Subscription returns a Subscription +func Subscription(name string, namespace string, channel *corev1.ObjectReference, subscriber *v1alpha1.SubscriberSpec, reply *v1alpha1.ReplyStrategy) *v1alpha1.Subscription { + return &v1alpha1.Subscription{ ObjectMeta: metav1.ObjectMeta{ - Name: flowName, + Name: name, Namespace: namespace, }, - Spec: flowsV1alpha1.FlowSpec{ - ServiceAccountName: serviceAccount, - Trigger: flowsV1alpha1.EventTrigger{ - EventType: eventType, - Resource: "k8sevents/receiveevent", - Service: eventSource, - Parameters: &runtime.RawExtension{ - Raw: []byte(fmt.Sprintf(`{"namespace": "%s"}`, testNamespace)), - }, - }, - Action: flowsV1alpha1.FlowAction{ - Target: &corev1.ObjectReference{ - Kind: "Route", - APIVersion: "serving.knative.dev/v1alpha1", - Name: routeName, - }, - }, + Spec: v1alpha1.SubscriptionSpec{ + Channel: *channel, + Subscriber: subscriber, + Reply: reply, }, } } @@ -188,6 +176,7 @@ func NGinxPod(namespace string) *corev1.Pod { ObjectMeta: metav1.ObjectMeta{ Name: "nginx", Namespace: namespace, + Annotations: map[string]string{"sidecar.istio.io/inject": "true"}, }, Spec: corev1.PodSpec{ Containers: []corev1.Container{ diff --git a/test/crd_checks.go b/test/crd_checks.go index e551e342cc4..62d93f72732 100644 --- a/test/crd_checks.go +++ b/test/crd_checks.go @@ -23,8 +23,6 @@ import ( "fmt" "time" - flowsV1alpha1 "github.com/knative/eventing/pkg/apis/flows/v1alpha1" - flowstyped "github.com/knative/eventing/pkg/client/clientset/versioned/typed/flows/v1alpha1" servingV1alpha1 "github.com/knative/serving/pkg/apis/serving/v1alpha1" servingtyped "github.com/knative/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1" "go.opencensus.io/trace" @@ -54,21 +52,3 @@ func WaitForRouteState(client servingtyped.RouteInterface, name string, inState return inState(r) }) } - -// WaitForFlowState polls the status of the Flow called name -// from client every interval until inState returns `true` indicating it -// is done, returns an error or timeout. desc will be used to name the metric -// that is emitted to track how long it took for name to get into the state checked by inState. -func WaitForFlowState(client flowstyped.FlowInterface, name string, inState func(s *flowsV1alpha1.Flow) (bool, error), desc string) error { - metricName := fmt.Sprintf("WaitForFlowState/%s/%s", name, desc) - _, span := trace.StartSpan(context.Background(), metricName) - defer span.End() - - return wait.PollImmediate(interval, timeout, func() (bool, error) { - s, err := client.Get(name, metav1.GetOptions{}) - if err != nil { - return true, err - } - return inState(s) - }) -} diff --git a/test/e2e-tests.sh b/test/e2e-tests.sh index 4aa91c03de3..388680e81c6 100755 --- a/test/e2e-tests.sh +++ b/test/e2e-tests.sh @@ -27,26 +27,34 @@ source $(dirname $0)/../vendor/github.com/knative/test-infra/scripts/e2e-tests.sh +readonly KNATIVE_EVENTING_SOURCES_RELEASE=https://knative-releases.storage.googleapis.com/eventing-sources/latest/release.yaml + # Names of the Resources used in the tests. readonly E2E_TEST_NAMESPACE=e2etest readonly E2E_TEST_FUNCTION_NAMESPACE=e2etestfn3 -function run_e2e_tests() { - header "Running tests in $1" - local options="" - (( EMIT_METRICS )) && options="-emitmetrics" - report_go_test -v -tags=e2e -count=1 ./test/$1 -dockerrepo $DOCKER_REPO_OVERRIDE ${options} - return $? +# Helper functions. + +# Install the latest stable Knative/serving in the current cluster. +function start_latest_eventing_sources() { + header "Starting Knative Eventing Sources" + subheader "Installing Knative Eventing Sources" + kubectl apply -f ${KNATIVE_EVENTING_SOURCES_RELEASE} || return 1 + wait_until_pods_running knative-sources || return 1 } -# Helper functions. function teardown() { teardown_events_test_resources +# ko delete --ignore-not-found=true -f config/provisioners/in-memory-channel/in-memory-channel.yaml ko delete --ignore-not-found=true -f config/ + ko delete --ignore-not-found=true -f ${KNATIVE_EVENTING_SOURCES_RELEASE} + wait_until_object_does_not_exist namespaces knative-eventing - wait_until_object_does_not_exist customresourcedefinitions feeds.feeds.knative.dev - wait_until_object_does_not_exist customresourcedefinitions flows.flows.knative.dev + wait_until_object_does_not_exist namespaces knative-sources + + wait_until_object_does_not_exist customresourcedefinitions subscriptions.eventing.knative.dev + wait_until_object_does_not_exist customresourcedefinitions channels.eventing.knative.dev } function setup_events_test_resources() { @@ -67,22 +75,6 @@ function teardown_events_test_resources() { wait_until_object_does_not_exist namespaces $E2E_TEST_NAMESPACE } -function publish_test_images() { - echo ">> Publishing test images" - local IMAGE_PATHS_FILE="$(dirname $0)/image_paths.txt" - local DOCKER_TAG=e2e - - while read -r IMAGE || [[ -n "$IMAGE" ]]; do - if [ $(echo "$IMAGE" | grep -v -e "^#") ]; then - ko publish -P $IMAGE - local IMAGE=$KO_DOCKER_REPO/$IMAGE - local DIGEST=$(gcloud container images list-tags --filter="tags:latest" --format='get(digest)' $IMAGE) - echo "Tagging $IMAGE@$DIGEST with $DOCKER_TAG" - gcloud -q container images add-tag $IMAGE@$DIGEST $IMAGE:$DOCKER_TAG - fi - done < "$IMAGE_PATHS_FILE" -} - # Script entry point. initialize $@ @@ -92,6 +84,9 @@ if (( ! USING_EXISTING_CLUSTER )); then start_latest_knative_serving || fail_test fi +# Install Knative Eventing Sources +start_latest_eventing_sources || fail_test + # Clean up anything that might still be around teardown_events_test_resources @@ -105,8 +100,13 @@ ko resolve -f config/ ko apply -f config/ wait_until_pods_running knative-eventing +header "Standing up In-Memory ClusterChannelProvisioner" +ko resolve -f config/provisioners/in-memory-channel/in-memory-channel.yaml +ko apply -f config/provisioners/in-memory-channel/in-memory-channel.yaml +wait_until_pods_running knative-eventing + # Publish test images -publish_test_images +$(dirname $0)/upload-test-images.sh e2e # Handle test failures ourselves, so we can dump useful info. set +o errexit @@ -115,6 +115,6 @@ set +o pipefail # Setup resources common to all eventing tests setup_events_test_resources -run_e2e_tests e2e || fail_test +go_test_e2e ./test/e2e || fail_test success diff --git a/test/e2e/e2e.go b/test/e2e/e2e.go index 3760e410cb7..dc14139e4cf 100644 --- a/test/e2e/e2e.go +++ b/test/e2e/e2e.go @@ -6,9 +6,8 @@ import ( "testing" "time" - channelsV1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - feedsV1alpha1 "github.com/knative/eventing/pkg/apis/feeds/v1alpha1" - flowsV1alpha1 "github.com/knative/eventing/pkg/apis/flows/v1alpha1" + sourcesv1alpha1 "github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1" + "github.com/knative/eventing/pkg/apis/eventing/v1alpha1" "github.com/knative/eventing/test" pkgTest "github.com/knative/pkg/test" "github.com/knative/pkg/test/logging" @@ -97,49 +96,36 @@ func WithRouteReady(clients *test.Clients, logger *logging.BaseLogger, cleaner * return nil } -// CreateFlow will create a Flow -func CreateFlow(clients *test.Clients, flow *flowsV1alpha1.Flow, logger *logging.BaseLogger, cleaner *test.Cleaner) error { - flows := clients.Eventing.FlowsV1alpha1().Flows(pkgTest.Flags.Namespace) - res, err := flows.Create(flow) +// CreateKubernetesEventSource creates a KubernetesEventSource +func CreateKubernetesEventSource(clients *test.Clients, source *sourcesv1alpha1.KubernetesEventSource, logger *logging.BaseLogger, cleaner *test.Cleaner) error { + k8sSources := clients.Sources.SourcesV1alpha1().KubernetesEventSources(pkgTest.Flags.Namespace) + res, err := k8sSources.Create(source) if err != nil { return err } - cleaner.Add(flowsV1alpha1.SchemeGroupVersion.Group, flowsV1alpha1.SchemeGroupVersion.Version, "flows", pkgTest.Flags.Namespace, res.ObjectMeta.Name) - return nil -} - -// WithFlowReady will create a Flow and wait until it is ready -func WithFlowReady(clients *test.Clients, flow *flowsV1alpha1.Flow, logger *logging.BaseLogger, cleaner *test.Cleaner) error { - err := CreateFlow(clients, flow, logger, cleaner) - if err != nil { - return err - } - flows := clients.Eventing.FlowsV1alpha1().Flows(pkgTest.Flags.Namespace) - if err := test.WaitForFlowState(flows, flow.ObjectMeta.Name, test.IsFlowReady, "FlowIsReady"); err != nil { - return err - } + cleaner.Add(sourcesv1alpha1.SchemeGroupVersion.Group, sourcesv1alpha1.SchemeGroupVersion.Version, "kuberneteseventsources", pkgTest.Flags.Namespace, res.ObjectMeta.Name) return nil } // CreateChannel will create a Channel -func CreateChannel(clients *test.Clients, channel *channelsV1alpha1.Channel, logger *logging.BaseLogger, cleaner *test.Cleaner) error { - channels := clients.Eventing.ChannelsV1alpha1().Channels(pkgTest.Flags.Namespace) +func CreateChannel(clients *test.Clients, channel *v1alpha1.Channel, logger *logging.BaseLogger, cleaner *test.Cleaner) error { + channels := clients.Eventing.EventingV1alpha1().Channels(pkgTest.Flags.Namespace) res, err := channels.Create(channel) if err != nil { return err } - cleaner.Add(channelsV1alpha1.SchemeGroupVersion.Group, channelsV1alpha1.SchemeGroupVersion.Version, "channels", pkgTest.Flags.Namespace, res.ObjectMeta.Name) + cleaner.Add(v1alpha1.SchemeGroupVersion.Group, v1alpha1.SchemeGroupVersion.Version, "channels", pkgTest.Flags.Namespace, res.ObjectMeta.Name) return nil } // CreateSubscription will create a Subscription -func CreateSubscription(clients *test.Clients, subs *channelsV1alpha1.Subscription, logger *logging.BaseLogger, cleaner *test.Cleaner) error { - subscriptions := clients.Eventing.ChannelsV1alpha1().Subscriptions(pkgTest.Flags.Namespace) +func CreateSubscription(clients *test.Clients, subs *v1alpha1.Subscription, logger *logging.BaseLogger, cleaner *test.Cleaner) error { + subscriptions := clients.Eventing.EventingV1alpha1().Subscriptions(pkgTest.Flags.Namespace) res, err := subscriptions.Create(subs) if err != nil { return err } - cleaner.Add(channelsV1alpha1.SchemeGroupVersion.Group, channelsV1alpha1.SchemeGroupVersion.Version, "subscriptions", pkgTest.Flags.Namespace, res.ObjectMeta.Name) + cleaner.Add(v1alpha1.SchemeGroupVersion.Group, v1alpha1.SchemeGroupVersion.Version, "subscriptions", pkgTest.Flags.Namespace, res.ObjectMeta.Name) return nil } @@ -180,7 +166,7 @@ func CreateServiceAccountAndBinding(clients *test.Clients, name string, logger * } crb := &rbacV1beta1.ClusterRoleBinding{ ObjectMeta: metav1.ObjectMeta{ - Name: "e2e-feed-admin", + Name: "e2e-tests-admin", }, Subjects: []rbacV1beta1.Subject{ { @@ -202,39 +188,6 @@ func CreateServiceAccountAndBinding(clients *test.Clients, name string, logger * return nil } -// CreateClusterBus will create a ClusterBus -func CreateClusterBus(clients *test.Clients, cbus *channelsV1alpha1.ClusterBus, logger *logging.BaseLogger, cleaner *test.Cleaner) error { - cbuses := clients.Eventing.ChannelsV1alpha1().ClusterBuses() - res, err := cbuses.Create(cbus) - if err != nil { - return err - } - cleaner.Add(channelsV1alpha1.SchemeGroupVersion.Group, channelsV1alpha1.SchemeGroupVersion.Version, "clusterbuses", pkgTest.Flags.Namespace, res.ObjectMeta.Name) - return nil -} - -// CreateEventSource will create an EventSource -func CreateEventSource(clients *test.Clients, es *feedsV1alpha1.EventSource, logger *logging.BaseLogger, cleaner *test.Cleaner) error { - esources := clients.Eventing.FeedsV1alpha1().EventSources(pkgTest.Flags.Namespace) - res, err := esources.Create(es) - if err != nil { - return err - } - cleaner.Add(feedsV1alpha1.SchemeGroupVersion.Group, feedsV1alpha1.SchemeGroupVersion.Version, "eventsources", pkgTest.Flags.Namespace, res.ObjectMeta.Name) - return nil -} - -// CreateEventType will create an EventType -func CreateEventType(clients *test.Clients, et *feedsV1alpha1.EventType, logger *logging.BaseLogger, cleaner *test.Cleaner) error { - eTypes := clients.Eventing.FeedsV1alpha1().EventTypes(pkgTest.Flags.Namespace) - res, err := eTypes.Create(et) - if err != nil { - return err - } - cleaner.Add(feedsV1alpha1.SchemeGroupVersion.Group, feedsV1alpha1.SchemeGroupVersion.Version, "eventtypes", pkgTest.Flags.Namespace, res.ObjectMeta.Name) - return nil -} - // CreatePod will create a Pod func CreatePod(clients *test.Clients, pod *corev1.Pod, logger *logging.BaseLogger, cleaner *test.Cleaner) error { pods := clients.Kube.Kube.CoreV1().Pods(pod.GetNamespace()) diff --git a/test/e2e/k8s_events_test.go b/test/e2e/k8s_events_test.go index cbe3a3ce39f..f321f3071f4 100644 --- a/test/e2e/k8s_events_test.go +++ b/test/e2e/k8s_events_test.go @@ -27,11 +27,12 @@ import ( ) const ( - serviceAccount = "e2e-feed" - eventSource = "k8sevents" - eventType = "dev.knative.k8s.event" - routeName = "e2e-k8s-events-function" - flowName = "e2e-k8s-events-example" + serviceAccount = "e2e-receive-adapter" + eventSource = "k8sevents" + routeName = "e2e-k8s-events-function" + channelName = "e2e-k8s-events-channel" + provisionerName = "in-memory-channel" + subscriptionName = "e2e-k8s-events-subscription" ) func TestKubernetesEvents(t *testing.T) { @@ -50,51 +51,33 @@ func TestKubernetesEvents(t *testing.T) { t.Fatalf("Failed to create ServiceAccount or Binding: %v", err) } - logger.Infof("Creating ClusterBus") - - // The dispatcher used by the ClusterBus to dispatch messages between channels and subscriptions - dispatcherImagePath := ImagePath("github.com/knative/eventing/pkg/buses/stub/dispatcher") - stub := test.ClusterBus("stub", defaultNamespaceName, dispatcherImagePath) - err = CreateClusterBus(clients, stub, logger, cleaner) + logger.Infof("Creating Channel") + channel := test.Channel(channelName, defaultNamespaceName, test.ClusterChannelProvisioner(provisionerName)) + err = CreateChannel(clients, channel, logger, cleaner) if err != nil { - t.Fatalf("Failed to create ClusterBus: %v", err) + t.Fatalf("Failed to create Channel: %v", err) } logger.Infof("Creating EventSource") - - // The event source wrapper for Kubernetes events - eventSourceImagePath := ImagePath("github.com/knative/eventing/pkg/sources/k8sevents") - // The actual event source which receives events and posts them to the given Route - receiverAdapterImagePath := ImagePath("github.com/knative/eventing/pkg/sources/k8sevents/receive_adapter") - eSource := test.EventSource(eventSource, defaultNamespaceName, eventSourceImagePath, receiverAdapterImagePath) - err = CreateEventSource(clients, eSource, logger, cleaner) - if err != nil { - t.Fatalf("Failed to create EventSource: %v", err) - } - - logger.Infof("Creating EventType") - - eType := test.EventType(eventType, defaultNamespaceName, eventSource) - err = CreateEventType(clients, eType, logger, cleaner) + k8sSource := test.KubernetesEventSource(eventSource, defaultNamespaceName, testNamespace, serviceAccount, test.ChannelRef(channelName)) + err = CreateKubernetesEventSource(clients, k8sSource, logger, cleaner) if err != nil { - t.Fatalf("Failed to create EventType: %v", err) + t.Fatalf("Failed to create KubernetesEventSource: %v", err) } logger.Infof("Creating Route and Config") - // The receiver of events which is accessible through Route - configImagePath := ImagePath("github.com/knative/eventing/test/e2e/k8sevents") + configImagePath := ImagePath("k8sevents") err = WithRouteReady(clients, logger, cleaner, routeName, configImagePath) if err != nil { t.Fatalf("The Route was not marked as Ready to serve traffic: %v", err) } - logger.Infof("Creating Flow") - - flow := test.Flow(flowName, defaultNamespaceName, serviceAccount, eventType, eventSource, routeName, testNamespace) - err = WithFlowReady(clients, flow, logger, cleaner) + logger.Infof("Creating Subscription") + subscription := test.Subscription(subscriptionName, defaultNamespaceName, test.ChannelRef(channelName), test.SubscriberSpecForRoute(routeName), nil) + err = CreateSubscription(clients, subscription, logger, cleaner) if err != nil { - t.Fatalf("Failed to create Flow: %v", err) + t.Fatalf("Failed to create Subscription: %v", err) } //Work around for: https://github.com/knative/eventing/issues/125 diff --git a/test/e2e/k8sevents/kodata/LICENSE b/test/e2e/k8sevents/kodata/LICENSE deleted file mode 120000 index 14776154326..00000000000 --- a/test/e2e/k8sevents/kodata/LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../LICENSE \ No newline at end of file diff --git a/test/e2e/k8sevents/kodata/VENDOR-LICENSE b/test/e2e/k8sevents/kodata/VENDOR-LICENSE deleted file mode 120000 index 7322c09d957..00000000000 --- a/test/e2e/k8sevents/kodata/VENDOR-LICENSE +++ /dev/null @@ -1 +0,0 @@ -../../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/test/e2e_flags.go b/test/e2e_flags.go index 4828e189e8e..8f90995023d 100644 --- a/test/e2e_flags.go +++ b/test/e2e_flags.go @@ -21,6 +21,7 @@ package test import ( "flag" "os" + "path" pkgTest "github.com/knative/pkg/test" "github.com/knative/pkg/test/logging" @@ -38,7 +39,7 @@ type EventingEnvironmentFlags struct { func initializeEventingFlags() *EventingEnvironmentFlags { var f EventingEnvironmentFlags - defaultRepo := os.Getenv("DOCKER_REPO_OVERRIDE") + defaultRepo := path.Join(os.Getenv("DOCKER_REPO_OVERRIDE"), "github.com/knative/eventing/test/test_images") flag.StringVar(&f.DockerRepo, "dockerrepo", defaultRepo, "Provide the uri of the docker repo you have uploaded the test image to using `uploadtestimage.sh`. Defaults to $DOCKER_REPO_OVERRIDE") diff --git a/test/image_paths.txt b/test/image_paths.txt deleted file mode 100644 index 62cdf1286b5..00000000000 --- a/test/image_paths.txt +++ /dev/null @@ -1,8 +0,0 @@ -# The dispatcher used by the ClusterBus to dispatch messages between channels and subscriptions -github.com/knative/eventing/pkg/buses/stub/dispatcher -# The event source wrapper for Kubernetes events -github.com/knative/eventing/pkg/sources/k8sevents -# The actual event source which receives events and posts them to the given Route -github.com/knative/eventing/pkg/sources/k8sevents/receive_adapter -# The receiver of events which is accessible through Route -github.com/knative/eventing/test/e2e/k8sevents diff --git a/test/presubmit-tests.sh b/test/presubmit-tests.sh index a317f3487cb..90f7bf03eda 100755 --- a/test/presubmit-tests.sh +++ b/test/presubmit-tests.sh @@ -48,8 +48,6 @@ function unit_tests() { report_go_test ${CODE_PACKAGES_STR} } -function integration_tests() { - ./test/e2e-tests.sh -} +# We use the default integration test runner. main $@ diff --git a/test/states.go b/test/states.go index e239dd12a81..849f5e360d8 100644 --- a/test/states.go +++ b/test/states.go @@ -16,7 +16,6 @@ limitations under the License. package test import ( - flowsV1alpha1 "github.com/knative/eventing/pkg/apis/flows/v1alpha1" "github.com/knative/serving/pkg/apis/serving/v1alpha1" corev1 "k8s.io/api/core/v1" ) @@ -44,12 +43,6 @@ func IsRouteReady(r *v1alpha1.Route) (bool, error) { return r.Status.IsReady(), nil } -// IsFlowReady will check the status conditions of the flow and return true if the flow is -// ready. -func IsFlowReady(f *flowsV1alpha1.Flow) (bool, error) { - return f.Status.IsReady(), nil -} - // PodsRunning will check the status conditions of the pod list and return true all pods are Running func PodsRunning(podList *corev1.PodList) (bool, error) { for _, pod := range podList.Items { diff --git a/test/e2e/k8sevents/function.go b/test/test_images/k8sevents/function.go similarity index 85% rename from test/e2e/k8sevents/function.go rename to test/test_images/k8sevents/function.go index 3743aab5fe2..108d9320cc5 100644 --- a/test/e2e/k8sevents/function.go +++ b/test/test_images/k8sevents/function.go @@ -15,21 +15,20 @@ package main import ( "context" + "github.com/knative/pkg/cloudevents" "log" "net/http" "time" corev1 "k8s.io/api/core/v1" - - "github.com/knative/eventing/pkg/event" ) func handler(ctx context.Context, e *corev1.Event) { - metadata := event.FromContext(ctx) + metadata := cloudevents.FromContext(ctx) log.Printf("[%s] %s : %q", metadata.EventTime.Format(time.RFC3339), metadata.Source, e.Message) } func main() { log.Print("Ready and listening on port 8080") - log.Fatal(http.ListenAndServe(":8080", event.Handler(handler))) + log.Fatal(http.ListenAndServe(":8080", cloudevents.Handler(handler))) } diff --git a/pkg/sources/gcppubsub/kodata/LICENSE b/test/test_images/k8sevents/kodata/LICENSE similarity index 100% rename from pkg/sources/gcppubsub/kodata/LICENSE rename to test/test_images/k8sevents/kodata/LICENSE diff --git a/pkg/sources/gcppubsub/kodata/VENDOR-LICENSE b/test/test_images/k8sevents/kodata/VENDOR-LICENSE similarity index 100% rename from pkg/sources/gcppubsub/kodata/VENDOR-LICENSE rename to test/test_images/k8sevents/kodata/VENDOR-LICENSE diff --git a/test/upload-test-images.sh b/test/upload-test-images.sh index 9f7441fc7f0..f9c2edb45bb 100755 --- a/test/upload-test-images.sh +++ b/test/upload-test-images.sh @@ -16,20 +16,25 @@ set -o errexit +function upload_test_images() { + echo ">> Publishing test images" + local image_dirs="$(find $(dirname $0)/test_images -mindepth 1 -maxdepth 1 -type d)" + local docker_tag=$1 + + for image_dir in ${image_dirs}; do + local image="github.com/knative/eventing/test/test_images/$(basename ${image_dir})" + ko publish -P ${image} + if [ -n "$docker_tag" ]; then + image=$KO_DOCKER_REPO/${image} + local digest=$(gcloud container images list-tags --filter="tags:latest" --format='get(digest)' ${image}) + echo "Tagging ${image}@${digest} with $docker_tag" + gcloud -q container images add-tag ${image}@${digest} ${image}:$docker_tag + fi + done +} + : ${DOCKER_REPO_OVERRIDE:?"You must set 'DOCKER_REPO_OVERRIDE', see DEVELOPMENT.md"} export KO_DOCKER_REPO=${DOCKER_REPO_OVERRIDE} -IMAGE_PATHS_FILE="$(dirname $0)/image_paths.txt" -DOCKER_TAG=$1 -while read -r IMAGE || [[ -n "$IMAGE" ]]; do - if [ $(echo "$IMAGE" | grep -v -e "^#") ]; then - ko publish -P $IMAGE - if [ -n "$DOCKER_TAG" ]; then - IMAGE=$KO_DOCKER_REPO/$IMAGE - DIGEST=$(gcloud container images list-tags --filter="tags:latest" --format='get(digest)' $IMAGE) - echo "Tagging $IMAGE@$DIGEST with $DOCKER_TAG" - gcloud -q container images add-tag $IMAGE@$DIGEST $IMAGE:$DOCKER_TAG - fi - fi -done < "$IMAGE_PATHS_FILE" \ No newline at end of file +upload_test_images $@ \ No newline at end of file diff --git a/third_party/VENDOR-LICENSE b/third_party/VENDOR-LICENSE index e1969f98375..44283ce9234 100644 --- a/third_party/VENDOR-LICENSE +++ b/third_party/VENDOR-LICENSE @@ -207,6 +207,32 @@ Import: github.com/knative/eventing/vendor/cloud.google.com/go +=========================================================== +Import: github.com/knative/eventing/vendor/github.com/Shopify/sarama + +Copyright (c) 2013 Shopify + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + =========================================================== Import: github.com/knative/eventing/vendor/github.com/beorn7/perks @@ -233,6 +259,34 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +=========================================================== +Import: github.com/knative/eventing/vendor/github.com/bsm/sarama-cluster + +(The MIT License) + +Copyright (c) 2017 Black Square Media Ltd + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + =========================================================== Import: github.com/knative/eventing/vendor/github.com/davecgh/go-spew @@ -254,6 +308,118 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +=========================================================== +Import: github.com/knative/eventing/vendor/github.com/eapache/go-resiliency + +The MIT License (MIT) + +Copyright (c) 2014 Evan Huus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + + + +=========================================================== +Import: github.com/knative/eventing/vendor/github.com/eapache/go-xerial-snappy + +The MIT License (MIT) + +Copyright (c) 2016 Evan Huus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + + +=========================================================== +Import: github.com/knative/eventing/vendor/github.com/eapache/queue + +The MIT License (MIT) + +Copyright (c) 2014 Evan Huus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +=========================================================== +Import: github.com/knative/eventing/vendor/github.com/evanphx/json-patch + +Copyright (c) 2014, Evan Phoenix +All rights reserved. + +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 the Evan Phoenix 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. + + + =========================================================== Import: github.com/knative/eventing/vendor/github.com/fsnotify/fsnotify @@ -758,6 +924,20 @@ Import: github.com/knative/eventing/vendor/github.com/go-logr/zapr +=========================================================== +Import: github.com/knative/eventing/vendor/github.com/gobuffalo/envy + +The MIT License (MIT) +Copyright (c) 2018 Mark Bates + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + =========================================================== Import: github.com/knative/eventing/vendor/github.com/gogo/protobuf @@ -1231,6 +1411,39 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +=========================================================== +Import: github.com/knative/eventing/vendor/github.com/golang/snappy + +Copyright (c) 2011 The Snappy-Go Authors. All rights reserved. + +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. + + + =========================================================== Import: github.com/knative/eventing/vendor/github.com/google/btree @@ -2336,6 +2549,35 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +=========================================================== +Import: github.com/knative/eventing/vendor/github.com/joho/godotenv + +Copyright (c) 2013 John Barton + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + =========================================================== Import: github.com/knative/eventing/vendor/github.com/json-iterator/go @@ -2570,6 +2812,19 @@ Import: github.com/knative/eventing/vendor/github.com/knative/pkg +=========================================================== +Import: github.com/knative/eventing/vendor/github.com/markbates/inflect + +Copyright (c) 2011 Chris Farmiloe + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + =========================================================== Import: github.com/knative/eventing/vendor/github.com/mattbaird/jsonpatch @@ -3457,6 +3712,40 @@ THE SOFTWARE. +=========================================================== +Import: github.com/knative/eventing/vendor/github.com/pierrec/lz4 + +Copyright (c) 2015, Pierre Curto +All rights reserved. + +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 xxHash 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 HOLDER 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. + + + + =========================================================== Import: github.com/knative/eventing/vendor/github.com/prometheus/client_golang @@ -4285,6 +4574,41 @@ Import: github.com/knative/eventing/vendor/github.com/prometheus/procfs +=========================================================== +Import: github.com/knative/eventing/vendor/github.com/rcrowley/go-metrics + +Copyright 2012 Richard Crowley. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. 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. + +THIS SOFTWARE IS PROVIDED BY RICHARD CROWLEY ``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 RICHARD CROWLEY 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. + +The views and conclusions contained in the software and documentation +are those of the authors and should not be interpreted as representing +official policies, either expressed or implied, of Richard Crowley. + + + =========================================================== Import: github.com/knative/eventing/vendor/github.com/spf13/pflag diff --git a/vendor/cloud.google.com/go/iam/iam.go b/vendor/cloud.google.com/go/iam/iam.go deleted file mode 100644 index 37720aa2d67..00000000000 --- a/vendor/cloud.google.com/go/iam/iam.go +++ /dev/null @@ -1,284 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package iam supports the resource-specific operations of Google Cloud -// IAM (Identity and Access Management) for the Google Cloud Libraries. -// See https://cloud.google.com/iam for more about IAM. -// -// Users of the Google Cloud Libraries will typically not use this package -// directly. Instead they will begin with some resource that supports IAM, like -// a pubsub topic, and call its IAM method to get a Handle for that resource. -package iam - -import ( - "time" - - gax "github.com/googleapis/gax-go" - "golang.org/x/net/context" - pb "google.golang.org/genproto/googleapis/iam/v1" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" -) - -// client abstracts the IAMPolicy API to allow multiple implementations. -type client interface { - Get(ctx context.Context, resource string) (*pb.Policy, error) - Set(ctx context.Context, resource string, p *pb.Policy) error - Test(ctx context.Context, resource string, perms []string) ([]string, error) -} - -// grpcClient implements client for the standard gRPC-based IAMPolicy service. -type grpcClient struct { - c pb.IAMPolicyClient -} - -var withRetry = gax.WithRetry(func() gax.Retryer { - return gax.OnCodes([]codes.Code{ - codes.DeadlineExceeded, - codes.Unavailable, - }, gax.Backoff{ - Initial: 100 * time.Millisecond, - Max: 60 * time.Second, - Multiplier: 1.3, - }) -}) - -func (g *grpcClient) Get(ctx context.Context, resource string) (*pb.Policy, error) { - var proto *pb.Policy - err := gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error { - var err error - proto, err = g.c.GetIamPolicy(ctx, &pb.GetIamPolicyRequest{Resource: resource}) - return err - }, withRetry) - if err != nil { - return nil, err - } - return proto, nil -} - -func (g *grpcClient) Set(ctx context.Context, resource string, p *pb.Policy) error { - return gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error { - _, err := g.c.SetIamPolicy(ctx, &pb.SetIamPolicyRequest{ - Resource: resource, - Policy: p, - }) - return err - }, withRetry) -} - -func (g *grpcClient) Test(ctx context.Context, resource string, perms []string) ([]string, error) { - var res *pb.TestIamPermissionsResponse - err := gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error { - var err error - res, err = g.c.TestIamPermissions(ctx, &pb.TestIamPermissionsRequest{ - Resource: resource, - Permissions: perms, - }) - return err - }, withRetry) - if err != nil { - return nil, err - } - return res.Permissions, nil -} - -// A Handle provides IAM operations for a resource. -type Handle struct { - c client - resource string -} - -// InternalNewHandle is for use by the Google Cloud Libraries only. -// -// InternalNewHandle returns a Handle for resource. -// The conn parameter refers to a server that must support the IAMPolicy service. -func InternalNewHandle(conn *grpc.ClientConn, resource string) *Handle { - return InternalNewHandleClient(&grpcClient{c: pb.NewIAMPolicyClient(conn)}, resource) -} - -// InternalNewHandleClient is for use by the Google Cloud Libraries only. -// -// InternalNewHandleClient returns a Handle for resource using the given -// client implementation. -func InternalNewHandleClient(c client, resource string) *Handle { - return &Handle{ - c: c, - resource: resource, - } -} - -// Policy retrieves the IAM policy for the resource. -func (h *Handle) Policy(ctx context.Context) (*Policy, error) { - proto, err := h.c.Get(ctx, h.resource) - if err != nil { - return nil, err - } - return &Policy{InternalProto: proto}, nil -} - -// SetPolicy replaces the resource's current policy with the supplied Policy. -// -// If policy was created from a prior call to Get, then the modification will -// only succeed if the policy has not changed since the Get. -func (h *Handle) SetPolicy(ctx context.Context, policy *Policy) error { - return h.c.Set(ctx, h.resource, policy.InternalProto) -} - -// TestPermissions returns the subset of permissions that the caller has on the resource. -func (h *Handle) TestPermissions(ctx context.Context, permissions []string) ([]string, error) { - return h.c.Test(ctx, h.resource, permissions) -} - -// A RoleName is a name representing a collection of permissions. -type RoleName string - -// Common role names. -const ( - Owner RoleName = "roles/owner" - Editor RoleName = "roles/editor" - Viewer RoleName = "roles/viewer" -) - -const ( - // AllUsers is a special member that denotes all users, even unauthenticated ones. - AllUsers = "allUsers" - - // AllAuthenticatedUsers is a special member that denotes all authenticated users. - AllAuthenticatedUsers = "allAuthenticatedUsers" -) - -// A Policy is a list of Bindings representing roles -// granted to members. -// -// The zero Policy is a valid policy with no bindings. -type Policy struct { - // TODO(jba): when type aliases are available, put Policy into an internal package - // and provide an exported alias here. - - // This field is exported for use by the Google Cloud Libraries only. - // It may become unexported in a future release. - InternalProto *pb.Policy -} - -// Members returns the list of members with the supplied role. -// The return value should not be modified. Use Add and Remove -// to modify the members of a role. -func (p *Policy) Members(r RoleName) []string { - b := p.binding(r) - if b == nil { - return nil - } - return b.Members -} - -// HasRole reports whether member has role r. -func (p *Policy) HasRole(member string, r RoleName) bool { - return memberIndex(member, p.binding(r)) >= 0 -} - -// Add adds member member to role r if it is not already present. -// A new binding is created if there is no binding for the role. -func (p *Policy) Add(member string, r RoleName) { - b := p.binding(r) - if b == nil { - if p.InternalProto == nil { - p.InternalProto = &pb.Policy{} - } - p.InternalProto.Bindings = append(p.InternalProto.Bindings, &pb.Binding{ - Role: string(r), - Members: []string{member}, - }) - return - } - if memberIndex(member, b) < 0 { - b.Members = append(b.Members, member) - return - } -} - -// Remove removes member from role r if it is present. -func (p *Policy) Remove(member string, r RoleName) { - bi := p.bindingIndex(r) - if bi < 0 { - return - } - bindings := p.InternalProto.Bindings - b := bindings[bi] - mi := memberIndex(member, b) - if mi < 0 { - return - } - // Order doesn't matter for bindings or members, so to remove, move the last item - // into the removed spot and shrink the slice. - if len(b.Members) == 1 { - // Remove binding. - last := len(bindings) - 1 - bindings[bi] = bindings[last] - bindings[last] = nil - p.InternalProto.Bindings = bindings[:last] - return - } - // Remove member. - // TODO(jba): worry about multiple copies of m? - last := len(b.Members) - 1 - b.Members[mi] = b.Members[last] - b.Members[last] = "" - b.Members = b.Members[:last] -} - -// Roles returns the names of all the roles that appear in the Policy. -func (p *Policy) Roles() []RoleName { - if p.InternalProto == nil { - return nil - } - var rns []RoleName - for _, b := range p.InternalProto.Bindings { - rns = append(rns, RoleName(b.Role)) - } - return rns -} - -// binding returns the Binding for the suppied role, or nil if there isn't one. -func (p *Policy) binding(r RoleName) *pb.Binding { - i := p.bindingIndex(r) - if i < 0 { - return nil - } - return p.InternalProto.Bindings[i] -} - -func (p *Policy) bindingIndex(r RoleName) int { - if p.InternalProto == nil { - return -1 - } - for i, b := range p.InternalProto.Bindings { - if b.Role == string(r) { - return i - } - } - return -1 -} - -// memberIndex returns the index of m in b's Members, or -1 if not found. -func memberIndex(m string, b *pb.Binding) int { - if b == nil { - return -1 - } - for i, mm := range b.Members { - if mm == m { - return i - } - } - return -1 -} diff --git a/vendor/cloud.google.com/go/internal/optional/optional.go b/vendor/cloud.google.com/go/internal/optional/optional.go deleted file mode 100644 index 4c15410aa04..00000000000 --- a/vendor/cloud.google.com/go/internal/optional/optional.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package optional provides versions of primitive types that can -// be nil. These are useful in methods that update some of an API object's -// fields. -package optional - -import ( - "fmt" - "strings" - "time" -) - -type ( - // Bool is either a bool or nil. - Bool interface{} - - // String is either a string or nil. - String interface{} - - // Int is either an int or nil. - Int interface{} - - // Uint is either a uint or nil. - Uint interface{} - - // Float64 is either a float64 or nil. - Float64 interface{} - - // Duration is either a time.Duration or nil. - Duration interface{} -) - -// ToBool returns its argument as a bool. -// It panics if its argument is nil or not a bool. -func ToBool(v Bool) bool { - x, ok := v.(bool) - if !ok { - doPanic("Bool", v) - } - return x -} - -// ToString returns its argument as a string. -// It panics if its argument is nil or not a string. -func ToString(v String) string { - x, ok := v.(string) - if !ok { - doPanic("String", v) - } - return x -} - -// ToInt returns its argument as an int. -// It panics if its argument is nil or not an int. -func ToInt(v Int) int { - x, ok := v.(int) - if !ok { - doPanic("Int", v) - } - return x -} - -// ToUint returns its argument as a uint. -// It panics if its argument is nil or not a uint. -func ToUint(v Uint) uint { - x, ok := v.(uint) - if !ok { - doPanic("Uint", v) - } - return x -} - -// ToFloat64 returns its argument as a float64. -// It panics if its argument is nil or not a float64. -func ToFloat64(v Float64) float64 { - x, ok := v.(float64) - if !ok { - doPanic("Float64", v) - } - return x -} - -// ToDuration returns its argument as a time.Duration. -// It panics if its argument is nil or not a time.Duration. -func ToDuration(v Duration) time.Duration { - x, ok := v.(time.Duration) - if !ok { - doPanic("Duration", v) - } - return x -} - -func doPanic(capType string, v interface{}) { - panic(fmt.Sprintf("optional.%s value should be %s, got %T", capType, strings.ToLower(capType), v)) -} diff --git a/vendor/cloud.google.com/go/internal/version/version.go b/vendor/cloud.google.com/go/internal/version/version.go deleted file mode 100644 index f5c23a564c6..00000000000 --- a/vendor/cloud.google.com/go/internal/version/version.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:generate ./update_version.sh - -// Package version contains version information for Google Cloud Client -// Libraries for Go, as reported in request headers. -package version - -import ( - "runtime" - "strings" - "unicode" -) - -// Repo is the current version of the client libraries in this -// repo. It should be a date in YYYYMMDD format. -const Repo = "20180226" - -// Go returns the Go runtime version. The returned string -// has no whitespace. -func Go() string { - return goVersion -} - -var goVersion = goVer(runtime.Version()) - -const develPrefix = "devel +" - -func goVer(s string) string { - if strings.HasPrefix(s, develPrefix) { - s = s[len(develPrefix):] - if p := strings.IndexFunc(s, unicode.IsSpace); p >= 0 { - s = s[:p] - } - return s - } - - if strings.HasPrefix(s, "go1") { - s = s[2:] - var prerelease string - if p := strings.IndexFunc(s, notSemverRune); p >= 0 { - s, prerelease = s[:p], s[p:] - } - if strings.HasSuffix(s, ".") { - s += "0" - } else if strings.Count(s, ".") < 2 { - s += ".0" - } - if prerelease != "" { - s += "-" + prerelease - } - return s - } - return "" -} - -func notSemverRune(r rune) bool { - return strings.IndexRune("0123456789.", r) < 0 -} diff --git a/vendor/cloud.google.com/go/pubsub/apiv1/doc.go b/vendor/cloud.google.com/go/pubsub/apiv1/doc.go deleted file mode 100644 index ccdce27d66b..00000000000 --- a/vendor/cloud.google.com/go/pubsub/apiv1/doc.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2018 Google LLC -// -// 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 -// -// https://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. - -// AUTO-GENERATED CODE. DO NOT EDIT. - -// Package pubsub is an auto-generated package for the -// Google Cloud Pub/Sub API. -// -// NOTE: This package is in alpha. It is not stable, and is likely to change. -// -// Provides reliable, many-to-many, asynchronous messaging between -// applications. -// -// Use the client at cloud.google.com/go/pubsub in preference to this. -package pubsub // import "cloud.google.com/go/pubsub/apiv1" - -import ( - "golang.org/x/net/context" - "google.golang.org/grpc/metadata" -) - -func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { - out, _ := metadata.FromOutgoingContext(ctx) - out = out.Copy() - for _, md := range mds { - for k, v := range md { - out[k] = append(out[k], v...) - } - } - return metadata.NewOutgoingContext(ctx, out) -} - -// DefaultAuthScopes reports the default set of authentication scopes to use with this package. -func DefaultAuthScopes() []string { - return []string{ - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/pubsub", - } -} diff --git a/vendor/cloud.google.com/go/pubsub/apiv1/path_funcs.go b/vendor/cloud.google.com/go/pubsub/apiv1/path_funcs.go deleted file mode 100644 index b9ab4848db1..00000000000 --- a/vendor/cloud.google.com/go/pubsub/apiv1/path_funcs.go +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright 2018 Google LLC -// -// 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 -// -// https://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 pubsub - -// PublisherProjectPath returns the path for the project resource. -// -// Deprecated: Use -// fmt.Sprintf("projects/%s", project) -// instead. -func PublisherProjectPath(project string) string { - return "" + - "projects/" + - project + - "" -} - -// PublisherTopicPath returns the path for the topic resource. -// -// Deprecated: Use -// fmt.Sprintf("projects/%s/topics/%s", project, topic) -// instead. -func PublisherTopicPath(project, topic string) string { - return "" + - "projects/" + - project + - "/topics/" + - topic + - "" -} - -// SubscriberProjectPath returns the path for the project resource. -// -// Deprecated: Use -// fmt.Sprintf("projects/%s", project) -// instead. -func SubscriberProjectPath(project string) string { - return "" + - "projects/" + - project + - "" -} - -// SubscriberSnapshotPath returns the path for the snapshot resource. -// -// Deprecated: Use -// fmt.Sprintf("projects/%s/snapshots/%s", project, snapshot) -// instead. -func SubscriberSnapshotPath(project, snapshot string) string { - return "" + - "projects/" + - project + - "/snapshots/" + - snapshot + - "" -} - -// SubscriberSubscriptionPath returns the path for the subscription resource. -// -// Deprecated: Use -// fmt.Sprintf("projects/%s/subscriptions/%s", project, subscription) -// instead. -func SubscriberSubscriptionPath(project, subscription string) string { - return "" + - "projects/" + - project + - "/subscriptions/" + - subscription + - "" -} - -// SubscriberTopicPath returns the path for the topic resource. -// -// Deprecated: Use -// fmt.Sprintf("projects/%s/topics/%s", project, topic) -// instead. -func SubscriberTopicPath(project, topic string) string { - return "" + - "projects/" + - project + - "/topics/" + - topic + - "" -} diff --git a/vendor/cloud.google.com/go/pubsub/apiv1/publisher_client.go b/vendor/cloud.google.com/go/pubsub/apiv1/publisher_client.go deleted file mode 100644 index 6e9b1faee1a..00000000000 --- a/vendor/cloud.google.com/go/pubsub/apiv1/publisher_client.go +++ /dev/null @@ -1,398 +0,0 @@ -// Copyright 2018 Google LLC -// -// 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 -// -// https://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. - -// AUTO-GENERATED CODE. DO NOT EDIT. - -package pubsub - -import ( - "math" - "time" - - "cloud.google.com/go/iam" - "cloud.google.com/go/internal/version" - gax "github.com/googleapis/gax-go" - "golang.org/x/net/context" - "google.golang.org/api/iterator" - "google.golang.org/api/option" - "google.golang.org/api/transport" - pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/metadata" -) - -// PublisherCallOptions contains the retry settings for each method of PublisherClient. -type PublisherCallOptions struct { - CreateTopic []gax.CallOption - UpdateTopic []gax.CallOption - Publish []gax.CallOption - GetTopic []gax.CallOption - ListTopics []gax.CallOption - ListTopicSubscriptions []gax.CallOption - DeleteTopic []gax.CallOption -} - -func defaultPublisherClientOptions() []option.ClientOption { - return []option.ClientOption{ - option.WithEndpoint("pubsub.googleapis.com:443"), - option.WithScopes(DefaultAuthScopes()...), - } -} - -func defaultPublisherCallOptions() *PublisherCallOptions { - retry := map[[2]string][]gax.CallOption{ - {"default", "idempotent"}: { - gax.WithRetry(func() gax.Retryer { - return gax.OnCodes([]codes.Code{ - codes.DeadlineExceeded, - codes.Unavailable, - }, gax.Backoff{ - Initial: 100 * time.Millisecond, - Max: 60000 * time.Millisecond, - Multiplier: 1.3, - }) - }), - }, - {"messaging", "one_plus_delivery"}: { - gax.WithRetry(func() gax.Retryer { - return gax.OnCodes([]codes.Code{ - codes.Aborted, - codes.Canceled, - codes.DeadlineExceeded, - codes.Internal, - codes.ResourceExhausted, - codes.Unavailable, - codes.Unknown, - }, gax.Backoff{ - Initial: 100 * time.Millisecond, - Max: 60000 * time.Millisecond, - Multiplier: 1.3, - }) - }), - }, - } - return &PublisherCallOptions{ - CreateTopic: retry[[2]string{"default", "idempotent"}], - UpdateTopic: retry[[2]string{"default", "idempotent"}], - Publish: retry[[2]string{"messaging", "one_plus_delivery"}], - GetTopic: retry[[2]string{"default", "idempotent"}], - ListTopics: retry[[2]string{"default", "idempotent"}], - ListTopicSubscriptions: retry[[2]string{"default", "idempotent"}], - DeleteTopic: retry[[2]string{"default", "idempotent"}], - } -} - -// PublisherClient is a client for interacting with Google Cloud Pub/Sub API. -type PublisherClient struct { - // The connection to the service. - conn *grpc.ClientConn - - // The gRPC API client. - publisherClient pubsubpb.PublisherClient - - // The call options for this service. - CallOptions *PublisherCallOptions - - // The x-goog-* metadata to be sent with each request. - xGoogMetadata metadata.MD -} - -// NewPublisherClient creates a new publisher client. -// -// The service that an application uses to manipulate topics, and to send -// messages to a topic. -func NewPublisherClient(ctx context.Context, opts ...option.ClientOption) (*PublisherClient, error) { - conn, err := transport.DialGRPC(ctx, append(defaultPublisherClientOptions(), opts...)...) - if err != nil { - return nil, err - } - c := &PublisherClient{ - conn: conn, - CallOptions: defaultPublisherCallOptions(), - - publisherClient: pubsubpb.NewPublisherClient(conn), - } - c.SetGoogleClientInfo() - return c, nil -} - -// Connection returns the client's connection to the API service. -func (c *PublisherClient) Connection() *grpc.ClientConn { - return c.conn -} - -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *PublisherClient) Close() error { - return c.conn.Close() -} - -// SetGoogleClientInfo sets the name and version of the application in -// the `x-goog-api-client` header passed on each request. Intended for -// use by Google-written clients. -func (c *PublisherClient) SetGoogleClientInfo(keyval ...string) { - kv := append([]string{"gl-go", version.Go()}, keyval...) - kv = append(kv, "gapic", version.Repo, "gax", gax.Version, "grpc", grpc.Version) - c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) -} - -func (c *PublisherClient) SubscriptionIAM(subscription *pubsubpb.Subscription) *iam.Handle { - return iam.InternalNewHandle(c.Connection(), subscription.Name) -} - -func (c *PublisherClient) TopicIAM(topic *pubsubpb.Topic) *iam.Handle { - return iam.InternalNewHandle(c.Connection(), topic.Name) -} - -// CreateTopic creates the given topic with the given name. -func (c *PublisherClient) CreateTopic(ctx context.Context, req *pubsubpb.Topic, opts ...gax.CallOption) (*pubsubpb.Topic, error) { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.CreateTopic[0:len(c.CallOptions.CreateTopic):len(c.CallOptions.CreateTopic)], opts...) - var resp *pubsubpb.Topic - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.publisherClient.CreateTopic(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// UpdateTopic updates an existing topic. Note that certain properties of a topic are not -// modifiable. Options settings follow the style guide: -// NOTE: The style guide requires body: "topic" instead of body: "*". -// Keeping the latter for internal consistency in V1, however it should be -// corrected in V2. See -// https://cloud.google.com/apis/design/standard_methods#update for details. -func (c *PublisherClient) UpdateTopic(ctx context.Context, req *pubsubpb.UpdateTopicRequest, opts ...gax.CallOption) (*pubsubpb.Topic, error) { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.UpdateTopic[0:len(c.CallOptions.UpdateTopic):len(c.CallOptions.UpdateTopic)], opts...) - var resp *pubsubpb.Topic - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.publisherClient.UpdateTopic(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// Publish adds one or more messages to the topic. Returns NOT_FOUND if the topic -// does not exist. The message payload must not be empty; it must contain -// either a non-empty data field, or at least one attribute. -func (c *PublisherClient) Publish(ctx context.Context, req *pubsubpb.PublishRequest, opts ...gax.CallOption) (*pubsubpb.PublishResponse, error) { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.Publish[0:len(c.CallOptions.Publish):len(c.CallOptions.Publish)], opts...) - var resp *pubsubpb.PublishResponse - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.publisherClient.Publish(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// GetTopic gets the configuration of a topic. -func (c *PublisherClient) GetTopic(ctx context.Context, req *pubsubpb.GetTopicRequest, opts ...gax.CallOption) (*pubsubpb.Topic, error) { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.GetTopic[0:len(c.CallOptions.GetTopic):len(c.CallOptions.GetTopic)], opts...) - var resp *pubsubpb.Topic - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.publisherClient.GetTopic(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// ListTopics lists matching topics. -func (c *PublisherClient) ListTopics(ctx context.Context, req *pubsubpb.ListTopicsRequest, opts ...gax.CallOption) *TopicIterator { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListTopics[0:len(c.CallOptions.ListTopics):len(c.CallOptions.ListTopics)], opts...) - it := &TopicIterator{} - it.InternalFetch = func(pageSize int, pageToken string) ([]*pubsubpb.Topic, string, error) { - var resp *pubsubpb.ListTopicsResponse - req.PageToken = pageToken - if pageSize > math.MaxInt32 { - req.PageSize = math.MaxInt32 - } else { - req.PageSize = int32(pageSize) - } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.publisherClient.ListTopics(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, "", err - } - return resp.Topics, resp.NextPageToken, nil - } - fetch := func(pageSize int, pageToken string) (string, error) { - items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) - if err != nil { - return "", err - } - it.items = append(it.items, items...) - return nextPageToken, nil - } - it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) - return it -} - -// ListTopicSubscriptions lists the name of the subscriptions for this topic. -func (c *PublisherClient) ListTopicSubscriptions(ctx context.Context, req *pubsubpb.ListTopicSubscriptionsRequest, opts ...gax.CallOption) *StringIterator { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListTopicSubscriptions[0:len(c.CallOptions.ListTopicSubscriptions):len(c.CallOptions.ListTopicSubscriptions)], opts...) - it := &StringIterator{} - it.InternalFetch = func(pageSize int, pageToken string) ([]string, string, error) { - var resp *pubsubpb.ListTopicSubscriptionsResponse - req.PageToken = pageToken - if pageSize > math.MaxInt32 { - req.PageSize = math.MaxInt32 - } else { - req.PageSize = int32(pageSize) - } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.publisherClient.ListTopicSubscriptions(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, "", err - } - return resp.Subscriptions, resp.NextPageToken, nil - } - fetch := func(pageSize int, pageToken string) (string, error) { - items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) - if err != nil { - return "", err - } - it.items = append(it.items, items...) - return nextPageToken, nil - } - it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) - return it -} - -// DeleteTopic deletes the topic with the given name. Returns NOT_FOUND if the topic -// does not exist. After a topic is deleted, a new topic may be created with -// the same name; this is an entirely new topic with none of the old -// configuration or subscriptions. Existing subscriptions to this topic are -// not deleted, but their topic field is set to _deleted-topic_. -func (c *PublisherClient) DeleteTopic(ctx context.Context, req *pubsubpb.DeleteTopicRequest, opts ...gax.CallOption) error { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.DeleteTopic[0:len(c.CallOptions.DeleteTopic):len(c.CallOptions.DeleteTopic)], opts...) - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - _, err = c.publisherClient.DeleteTopic(ctx, req, settings.GRPC...) - return err - }, opts...) - return err -} - -// StringIterator manages a stream of string. -type StringIterator struct { - items []string - pageInfo *iterator.PageInfo - nextFunc func() error - - // InternalFetch is for use by the Google Cloud Libraries only. - // It is not part of the stable interface of this package. - // - // InternalFetch returns results from a single call to the underlying RPC. - // The number of results is no greater than pageSize. - // If there are no more results, nextPageToken is empty and err is nil. - InternalFetch func(pageSize int, pageToken string) (results []string, nextPageToken string, err error) -} - -// PageInfo supports pagination. See the google.golang.org/api/iterator package for details. -func (it *StringIterator) PageInfo() *iterator.PageInfo { - return it.pageInfo -} - -// Next returns the next result. Its second return value is iterator.Done if there are no more -// results. Once Next returns Done, all subsequent calls will return Done. -func (it *StringIterator) Next() (string, error) { - var item string - if err := it.nextFunc(); err != nil { - return item, err - } - item = it.items[0] - it.items = it.items[1:] - return item, nil -} - -func (it *StringIterator) bufLen() int { - return len(it.items) -} - -func (it *StringIterator) takeBuf() interface{} { - b := it.items - it.items = nil - return b -} - -// TopicIterator manages a stream of *pubsubpb.Topic. -type TopicIterator struct { - items []*pubsubpb.Topic - pageInfo *iterator.PageInfo - nextFunc func() error - - // InternalFetch is for use by the Google Cloud Libraries only. - // It is not part of the stable interface of this package. - // - // InternalFetch returns results from a single call to the underlying RPC. - // The number of results is no greater than pageSize. - // If there are no more results, nextPageToken is empty and err is nil. - InternalFetch func(pageSize int, pageToken string) (results []*pubsubpb.Topic, nextPageToken string, err error) -} - -// PageInfo supports pagination. See the google.golang.org/api/iterator package for details. -func (it *TopicIterator) PageInfo() *iterator.PageInfo { - return it.pageInfo -} - -// Next returns the next result. Its second return value is iterator.Done if there are no more -// results. Once Next returns Done, all subsequent calls will return Done. -func (it *TopicIterator) Next() (*pubsubpb.Topic, error) { - var item *pubsubpb.Topic - if err := it.nextFunc(); err != nil { - return item, err - } - item = it.items[0] - it.items = it.items[1:] - return item, nil -} - -func (it *TopicIterator) bufLen() int { - return len(it.items) -} - -func (it *TopicIterator) takeBuf() interface{} { - b := it.items - it.items = nil - return b -} diff --git a/vendor/cloud.google.com/go/pubsub/apiv1/subscriber_client.go b/vendor/cloud.google.com/go/pubsub/apiv1/subscriber_client.go deleted file mode 100644 index a2266a3a4dc..00000000000 --- a/vendor/cloud.google.com/go/pubsub/apiv1/subscriber_client.go +++ /dev/null @@ -1,593 +0,0 @@ -// Copyright 2018 Google LLC -// -// 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 -// -// https://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. - -// AUTO-GENERATED CODE. DO NOT EDIT. - -package pubsub - -import ( - "math" - "time" - - "cloud.google.com/go/iam" - "cloud.google.com/go/internal/version" - gax "github.com/googleapis/gax-go" - "golang.org/x/net/context" - "google.golang.org/api/iterator" - "google.golang.org/api/option" - "google.golang.org/api/transport" - pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/metadata" -) - -// SubscriberCallOptions contains the retry settings for each method of SubscriberClient. -type SubscriberCallOptions struct { - CreateSubscription []gax.CallOption - GetSubscription []gax.CallOption - UpdateSubscription []gax.CallOption - ListSubscriptions []gax.CallOption - DeleteSubscription []gax.CallOption - ModifyAckDeadline []gax.CallOption - Acknowledge []gax.CallOption - Pull []gax.CallOption - StreamingPull []gax.CallOption - ModifyPushConfig []gax.CallOption - ListSnapshots []gax.CallOption - CreateSnapshot []gax.CallOption - UpdateSnapshot []gax.CallOption - DeleteSnapshot []gax.CallOption - Seek []gax.CallOption -} - -func defaultSubscriberClientOptions() []option.ClientOption { - return []option.ClientOption{ - option.WithEndpoint("pubsub.googleapis.com:443"), - option.WithScopes(DefaultAuthScopes()...), - } -} - -func defaultSubscriberCallOptions() *SubscriberCallOptions { - retry := map[[2]string][]gax.CallOption{ - {"default", "idempotent"}: { - gax.WithRetry(func() gax.Retryer { - return gax.OnCodes([]codes.Code{ - codes.DeadlineExceeded, - codes.Unavailable, - }, gax.Backoff{ - Initial: 100 * time.Millisecond, - Max: 60000 * time.Millisecond, - Multiplier: 1.3, - }) - }), - }, - {"messaging", "pull"}: { - gax.WithRetry(func() gax.Retryer { - return gax.OnCodes([]codes.Code{ - codes.Canceled, - codes.DeadlineExceeded, - codes.Internal, - codes.ResourceExhausted, - codes.Unavailable, - }, gax.Backoff{ - Initial: 100 * time.Millisecond, - Max: 60000 * time.Millisecond, - Multiplier: 1.3, - }) - }), - }, - {"streaming_messaging", "pull"}: { - gax.WithRetry(func() gax.Retryer { - return gax.OnCodes([]codes.Code{ - codes.Canceled, - codes.DeadlineExceeded, - codes.Internal, - codes.ResourceExhausted, - codes.Unavailable, - }, gax.Backoff{ - Initial: 100 * time.Millisecond, - Max: 60000 * time.Millisecond, - Multiplier: 1.3, - }) - }), - }, - } - return &SubscriberCallOptions{ - CreateSubscription: retry[[2]string{"default", "idempotent"}], - GetSubscription: retry[[2]string{"default", "idempotent"}], - UpdateSubscription: retry[[2]string{"default", "idempotent"}], - ListSubscriptions: retry[[2]string{"default", "idempotent"}], - DeleteSubscription: retry[[2]string{"default", "idempotent"}], - ModifyAckDeadline: retry[[2]string{"default", "non_idempotent"}], - Acknowledge: retry[[2]string{"messaging", "non_idempotent"}], - Pull: retry[[2]string{"messaging", "pull"}], - StreamingPull: retry[[2]string{"streaming_messaging", "pull"}], - ModifyPushConfig: retry[[2]string{"default", "non_idempotent"}], - ListSnapshots: retry[[2]string{"default", "idempotent"}], - CreateSnapshot: retry[[2]string{"default", "idempotent"}], - UpdateSnapshot: retry[[2]string{"default", "idempotent"}], - DeleteSnapshot: retry[[2]string{"default", "idempotent"}], - Seek: retry[[2]string{"default", "non_idempotent"}], - } -} - -// SubscriberClient is a client for interacting with Google Cloud Pub/Sub API. -type SubscriberClient struct { - // The connection to the service. - conn *grpc.ClientConn - - // The gRPC API client. - subscriberClient pubsubpb.SubscriberClient - - // The call options for this service. - CallOptions *SubscriberCallOptions - - // The x-goog-* metadata to be sent with each request. - xGoogMetadata metadata.MD -} - -// NewSubscriberClient creates a new subscriber client. -// -// The service that an application uses to manipulate subscriptions and to -// consume messages from a subscription via the Pull method. -func NewSubscriberClient(ctx context.Context, opts ...option.ClientOption) (*SubscriberClient, error) { - conn, err := transport.DialGRPC(ctx, append(defaultSubscriberClientOptions(), opts...)...) - if err != nil { - return nil, err - } - c := &SubscriberClient{ - conn: conn, - CallOptions: defaultSubscriberCallOptions(), - - subscriberClient: pubsubpb.NewSubscriberClient(conn), - } - c.SetGoogleClientInfo() - return c, nil -} - -// Connection returns the client's connection to the API service. -func (c *SubscriberClient) Connection() *grpc.ClientConn { - return c.conn -} - -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *SubscriberClient) Close() error { - return c.conn.Close() -} - -// SetGoogleClientInfo sets the name and version of the application in -// the `x-goog-api-client` header passed on each request. Intended for -// use by Google-written clients. -func (c *SubscriberClient) SetGoogleClientInfo(keyval ...string) { - kv := append([]string{"gl-go", version.Go()}, keyval...) - kv = append(kv, "gapic", version.Repo, "gax", gax.Version, "grpc", grpc.Version) - c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) -} - -func (c *SubscriberClient) SubscriptionIAM(subscription *pubsubpb.Subscription) *iam.Handle { - return iam.InternalNewHandle(c.Connection(), subscription.Name) -} - -func (c *SubscriberClient) TopicIAM(topic *pubsubpb.Topic) *iam.Handle { - return iam.InternalNewHandle(c.Connection(), topic.Name) -} - -// CreateSubscription creates a subscription to a given topic. -// If the subscription already exists, returns ALREADY_EXISTS. -// If the corresponding topic doesn't exist, returns NOT_FOUND. -// -// If the name is not provided in the request, the server will assign a random -// name for this subscription on the same project as the topic, conforming -// to the -// resource name format (at https://cloud.google.com/pubsub/docs/overview#names). -// The generated name is populated in the returned Subscription object. -// Note that for REST API requests, you must specify a name in the request. -func (c *SubscriberClient) CreateSubscription(ctx context.Context, req *pubsubpb.Subscription, opts ...gax.CallOption) (*pubsubpb.Subscription, error) { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.CreateSubscription[0:len(c.CallOptions.CreateSubscription):len(c.CallOptions.CreateSubscription)], opts...) - var resp *pubsubpb.Subscription - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.subscriberClient.CreateSubscription(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// GetSubscription gets the configuration details of a subscription. -func (c *SubscriberClient) GetSubscription(ctx context.Context, req *pubsubpb.GetSubscriptionRequest, opts ...gax.CallOption) (*pubsubpb.Subscription, error) { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.GetSubscription[0:len(c.CallOptions.GetSubscription):len(c.CallOptions.GetSubscription)], opts...) - var resp *pubsubpb.Subscription - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.subscriberClient.GetSubscription(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// UpdateSubscription updates an existing subscription. Note that certain properties of a -// subscription, such as its topic, are not modifiable. -// NOTE: The style guide requires body: "subscription" instead of body: "*". -// Keeping the latter for internal consistency in V1, however it should be -// corrected in V2. See -// https://cloud.google.com/apis/design/standard_methods#update for details. -func (c *SubscriberClient) UpdateSubscription(ctx context.Context, req *pubsubpb.UpdateSubscriptionRequest, opts ...gax.CallOption) (*pubsubpb.Subscription, error) { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.UpdateSubscription[0:len(c.CallOptions.UpdateSubscription):len(c.CallOptions.UpdateSubscription)], opts...) - var resp *pubsubpb.Subscription - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.subscriberClient.UpdateSubscription(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// ListSubscriptions lists matching subscriptions. -func (c *SubscriberClient) ListSubscriptions(ctx context.Context, req *pubsubpb.ListSubscriptionsRequest, opts ...gax.CallOption) *SubscriptionIterator { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListSubscriptions[0:len(c.CallOptions.ListSubscriptions):len(c.CallOptions.ListSubscriptions)], opts...) - it := &SubscriptionIterator{} - it.InternalFetch = func(pageSize int, pageToken string) ([]*pubsubpb.Subscription, string, error) { - var resp *pubsubpb.ListSubscriptionsResponse - req.PageToken = pageToken - if pageSize > math.MaxInt32 { - req.PageSize = math.MaxInt32 - } else { - req.PageSize = int32(pageSize) - } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.subscriberClient.ListSubscriptions(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, "", err - } - return resp.Subscriptions, resp.NextPageToken, nil - } - fetch := func(pageSize int, pageToken string) (string, error) { - items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) - if err != nil { - return "", err - } - it.items = append(it.items, items...) - return nextPageToken, nil - } - it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) - return it -} - -// DeleteSubscription deletes an existing subscription. All messages retained in the subscription -// are immediately dropped. Calls to Pull after deletion will return -// NOT_FOUND. After a subscription is deleted, a new one may be created with -// the same name, but the new one has no association with the old -// subscription or its topic unless the same topic is specified. -func (c *SubscriberClient) DeleteSubscription(ctx context.Context, req *pubsubpb.DeleteSubscriptionRequest, opts ...gax.CallOption) error { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.DeleteSubscription[0:len(c.CallOptions.DeleteSubscription):len(c.CallOptions.DeleteSubscription)], opts...) - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - _, err = c.subscriberClient.DeleteSubscription(ctx, req, settings.GRPC...) - return err - }, opts...) - return err -} - -// ModifyAckDeadline modifies the ack deadline for a specific message. This method is useful -// to indicate that more time is needed to process a message by the -// subscriber, or to make the message available for redelivery if the -// processing was interrupted. Note that this does not modify the -// subscription-level ackDeadlineSeconds used for subsequent messages. -func (c *SubscriberClient) ModifyAckDeadline(ctx context.Context, req *pubsubpb.ModifyAckDeadlineRequest, opts ...gax.CallOption) error { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ModifyAckDeadline[0:len(c.CallOptions.ModifyAckDeadline):len(c.CallOptions.ModifyAckDeadline)], opts...) - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - _, err = c.subscriberClient.ModifyAckDeadline(ctx, req, settings.GRPC...) - return err - }, opts...) - return err -} - -// Acknowledge acknowledges the messages associated with the ack_ids in the -// AcknowledgeRequest. The Pub/Sub system can remove the relevant messages -// from the subscription. -// -// Acknowledging a message whose ack deadline has expired may succeed, -// but such a message may be redelivered later. Acknowledging a message more -// than once will not result in an error. -func (c *SubscriberClient) Acknowledge(ctx context.Context, req *pubsubpb.AcknowledgeRequest, opts ...gax.CallOption) error { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.Acknowledge[0:len(c.CallOptions.Acknowledge):len(c.CallOptions.Acknowledge)], opts...) - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - _, err = c.subscriberClient.Acknowledge(ctx, req, settings.GRPC...) - return err - }, opts...) - return err -} - -// Pull pulls messages from the server. Returns an empty list if there are no -// messages available in the backlog. The server may return UNAVAILABLE if -// there are too many concurrent pull requests pending for the given -// subscription. -func (c *SubscriberClient) Pull(ctx context.Context, req *pubsubpb.PullRequest, opts ...gax.CallOption) (*pubsubpb.PullResponse, error) { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.Pull[0:len(c.CallOptions.Pull):len(c.CallOptions.Pull)], opts...) - var resp *pubsubpb.PullResponse - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.subscriberClient.Pull(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// StreamingPull (EXPERIMENTAL) StreamingPull is an experimental feature. This RPC will -// respond with UNIMPLEMENTED errors unless you have been invited to test -// this feature. Contact cloud-pubsub@google.com with any questions. -// -// Establishes a stream with the server, which sends messages down to the -// client. The client streams acknowledgements and ack deadline modifications -// back to the server. The server will close the stream and return the status -// on any error. The server may close the stream with status OK to reassign -// server-side resources, in which case, the client should re-establish the -// stream. UNAVAILABLE may also be returned in the case of a transient error -// (e.g., a server restart). These should also be retried by the client. Flow -// control can be achieved by configuring the underlying RPC channel. -func (c *SubscriberClient) StreamingPull(ctx context.Context, opts ...gax.CallOption) (pubsubpb.Subscriber_StreamingPullClient, error) { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.StreamingPull[0:len(c.CallOptions.StreamingPull):len(c.CallOptions.StreamingPull)], opts...) - var resp pubsubpb.Subscriber_StreamingPullClient - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.subscriberClient.StreamingPull(ctx, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// ModifyPushConfig modifies the PushConfig for a specified subscription. -// -// This may be used to change a push subscription to a pull one (signified by -// an empty PushConfig) or vice versa, or change the endpoint URL and other -// attributes of a push subscription. Messages will accumulate for delivery -// continuously through the call regardless of changes to the PushConfig. -func (c *SubscriberClient) ModifyPushConfig(ctx context.Context, req *pubsubpb.ModifyPushConfigRequest, opts ...gax.CallOption) error { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ModifyPushConfig[0:len(c.CallOptions.ModifyPushConfig):len(c.CallOptions.ModifyPushConfig)], opts...) - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - _, err = c.subscriberClient.ModifyPushConfig(ctx, req, settings.GRPC...) - return err - }, opts...) - return err -} - -// ListSnapshots lists the existing snapshots. -func (c *SubscriberClient) ListSnapshots(ctx context.Context, req *pubsubpb.ListSnapshotsRequest, opts ...gax.CallOption) *SnapshotIterator { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListSnapshots[0:len(c.CallOptions.ListSnapshots):len(c.CallOptions.ListSnapshots)], opts...) - it := &SnapshotIterator{} - it.InternalFetch = func(pageSize int, pageToken string) ([]*pubsubpb.Snapshot, string, error) { - var resp *pubsubpb.ListSnapshotsResponse - req.PageToken = pageToken - if pageSize > math.MaxInt32 { - req.PageSize = math.MaxInt32 - } else { - req.PageSize = int32(pageSize) - } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.subscriberClient.ListSnapshots(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, "", err - } - return resp.Snapshots, resp.NextPageToken, nil - } - fetch := func(pageSize int, pageToken string) (string, error) { - items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) - if err != nil { - return "", err - } - it.items = append(it.items, items...) - return nextPageToken, nil - } - it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) - return it -} - -// CreateSnapshot creates a snapshot from the requested subscription. -// If the snapshot already exists, returns ALREADY_EXISTS. -// If the requested subscription doesn't exist, returns NOT_FOUND. -// -// If the name is not provided in the request, the server will assign a random -// name for this snapshot on the same project as the subscription, conforming -// to the -// resource name format (at https://cloud.google.com/pubsub/docs/overview#names). -// The generated name is populated in the returned Snapshot object. -// Note that for REST API requests, you must specify a name in the request. -func (c *SubscriberClient) CreateSnapshot(ctx context.Context, req *pubsubpb.CreateSnapshotRequest, opts ...gax.CallOption) (*pubsubpb.Snapshot, error) { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.CreateSnapshot[0:len(c.CallOptions.CreateSnapshot):len(c.CallOptions.CreateSnapshot)], opts...) - var resp *pubsubpb.Snapshot - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.subscriberClient.CreateSnapshot(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// UpdateSnapshot updates an existing snapshot. Note that certain properties of a snapshot -// are not modifiable. -// NOTE: The style guide requires body: "snapshot" instead of body: "*". -// Keeping the latter for internal consistency in V1, however it should be -// corrected in V2. See -// https://cloud.google.com/apis/design/standard_methods#update for details. -func (c *SubscriberClient) UpdateSnapshot(ctx context.Context, req *pubsubpb.UpdateSnapshotRequest, opts ...gax.CallOption) (*pubsubpb.Snapshot, error) { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.UpdateSnapshot[0:len(c.CallOptions.UpdateSnapshot):len(c.CallOptions.UpdateSnapshot)], opts...) - var resp *pubsubpb.Snapshot - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.subscriberClient.UpdateSnapshot(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// DeleteSnapshot removes an existing snapshot. All messages retained in the snapshot -// are immediately dropped. After a snapshot is deleted, a new one may be -// created with the same name, but the new one has no association with the old -// snapshot or its subscription, unless the same subscription is specified. -func (c *SubscriberClient) DeleteSnapshot(ctx context.Context, req *pubsubpb.DeleteSnapshotRequest, opts ...gax.CallOption) error { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.DeleteSnapshot[0:len(c.CallOptions.DeleteSnapshot):len(c.CallOptions.DeleteSnapshot)], opts...) - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - _, err = c.subscriberClient.DeleteSnapshot(ctx, req, settings.GRPC...) - return err - }, opts...) - return err -} - -// Seek seeks an existing subscription to a point in time or to a given snapshot, -// whichever is provided in the request. -func (c *SubscriberClient) Seek(ctx context.Context, req *pubsubpb.SeekRequest, opts ...gax.CallOption) (*pubsubpb.SeekResponse, error) { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.Seek[0:len(c.CallOptions.Seek):len(c.CallOptions.Seek)], opts...) - var resp *pubsubpb.SeekResponse - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.subscriberClient.Seek(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// SnapshotIterator manages a stream of *pubsubpb.Snapshot. -type SnapshotIterator struct { - items []*pubsubpb.Snapshot - pageInfo *iterator.PageInfo - nextFunc func() error - - // InternalFetch is for use by the Google Cloud Libraries only. - // It is not part of the stable interface of this package. - // - // InternalFetch returns results from a single call to the underlying RPC. - // The number of results is no greater than pageSize. - // If there are no more results, nextPageToken is empty and err is nil. - InternalFetch func(pageSize int, pageToken string) (results []*pubsubpb.Snapshot, nextPageToken string, err error) -} - -// PageInfo supports pagination. See the google.golang.org/api/iterator package for details. -func (it *SnapshotIterator) PageInfo() *iterator.PageInfo { - return it.pageInfo -} - -// Next returns the next result. Its second return value is iterator.Done if there are no more -// results. Once Next returns Done, all subsequent calls will return Done. -func (it *SnapshotIterator) Next() (*pubsubpb.Snapshot, error) { - var item *pubsubpb.Snapshot - if err := it.nextFunc(); err != nil { - return item, err - } - item = it.items[0] - it.items = it.items[1:] - return item, nil -} - -func (it *SnapshotIterator) bufLen() int { - return len(it.items) -} - -func (it *SnapshotIterator) takeBuf() interface{} { - b := it.items - it.items = nil - return b -} - -// SubscriptionIterator manages a stream of *pubsubpb.Subscription. -type SubscriptionIterator struct { - items []*pubsubpb.Subscription - pageInfo *iterator.PageInfo - nextFunc func() error - - // InternalFetch is for use by the Google Cloud Libraries only. - // It is not part of the stable interface of this package. - // - // InternalFetch returns results from a single call to the underlying RPC. - // The number of results is no greater than pageSize. - // If there are no more results, nextPageToken is empty and err is nil. - InternalFetch func(pageSize int, pageToken string) (results []*pubsubpb.Subscription, nextPageToken string, err error) -} - -// PageInfo supports pagination. See the google.golang.org/api/iterator package for details. -func (it *SubscriptionIterator) PageInfo() *iterator.PageInfo { - return it.pageInfo -} - -// Next returns the next result. Its second return value is iterator.Done if there are no more -// results. Once Next returns Done, all subsequent calls will return Done. -func (it *SubscriptionIterator) Next() (*pubsubpb.Subscription, error) { - var item *pubsubpb.Subscription - if err := it.nextFunc(); err != nil { - return item, err - } - item = it.items[0] - it.items = it.items[1:] - return item, nil -} - -func (it *SubscriptionIterator) bufLen() int { - return len(it.items) -} - -func (it *SubscriptionIterator) takeBuf() interface{} { - b := it.items - it.items = nil - return b -} diff --git a/vendor/cloud.google.com/go/pubsub/doc.go b/vendor/cloud.google.com/go/pubsub/doc.go deleted file mode 100644 index 848b410e2e3..00000000000 --- a/vendor/cloud.google.com/go/pubsub/doc.go +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/* -Package pubsub provides an easy way to publish and receive Google Cloud Pub/Sub -messages, hiding the the details of the underlying server RPCs. Google Cloud -Pub/Sub is a many-to-many, asynchronous messaging system that decouples senders -and receivers. - -Note: This package is in beta. Some backwards-incompatible changes may occur. - -More information about Google Cloud Pub/Sub is available at -https://cloud.google.com/pubsub/docs - -See https://godoc.org/cloud.google.com/go for authentication, timeouts, -connection pooling and similar aspects of this package. - - -Publishing - -Google Cloud Pub/Sub messages are published to topics. Topics may be created -using the pubsub package like so: - - topic, err := pubsubClient.CreateTopic(context.Background(), "topic-name") - -Messages may then be published to a topic: - - res := topic.Publish(ctx, &pubsub.Message{Data: []byte("payload")}) - -Publish queues the message for publishing and returns immediately. When enough -messages have accumulated, or enough time has elapsed, the batch of messages is -sent to the Pub/Sub service. - -Publish returns a PublishResult, which behaves like a future: its Get method -blocks until the message has been sent to the service. - -The first time you call Publish on a topic, goroutines are started in the -background. To clean up these goroutines, call Stop: - - topic.Stop() - -Receiving - -To receive messages published to a topic, clients create subscriptions -to the topic. There may be more than one subscription per topic; each message -that is published to the topic will be delivered to all of its subscriptions. - -Subsciptions may be created like so: - - sub, err := pubsubClient.CreateSubscription(context.Background(), "sub-name", - pubsub.SubscriptionConfig{Topic: topic}) - -Messages are then consumed from a subscription via callback. - - err := sub.Receive(context.Background(), func(ctx context.Context, m *Message) { - log.Printf("Got message: %s", m.Data) - m.Ack() - }) - if err != nil { - // Handle error. - } - -The callback is invoked concurrently by multiple goroutines, maximizing -throughput. To terminate a call to Receive, cancel its context. - -Once client code has processed the message, it must call Message.Ack, otherwise -the message will eventually be redelivered. As an optimization, if the client -cannot or doesn't want to process the message, it can call Message.Nack to -speed redelivery. For more information and configuration options, see -"Deadlines" below. - -Note: It is possible for Messages to be redelivered, even if Message.Ack has -been called. Client code must be robust to multiple deliveries of messages. - -Deadlines - -The default pubsub deadlines are suitable for most use cases, but may be -overridden. This section describes the tradeoffs that should be considered -when overriding the defaults. - -Behind the scenes, each message returned by the Pub/Sub server has an -associated lease, known as an "ACK deadline". -Unless a message is acknowledged within the ACK deadline, or the client requests that -the ACK deadline be extended, the message will become elegible for redelivery. -As a convenience, the pubsub package will automatically extend deadlines until -either: - * Message.Ack or Message.Nack is called, or - * the "MaxExtension" period elapses from the time the message is fetched from the server. - -The initial ACK deadline given to each messages defaults to 10 seconds, but may -be overridden during subscription creation. Selecting an ACK deadline is a -tradeoff between message redelivery latency and RPC volume. If the pubsub -package fails to acknowledge or extend a message (e.g. due to unexpected -termination of the process), a shorter ACK deadline will generally result in -faster message redelivery by the Pub/Sub system. However, a short ACK deadline -may also increase the number of deadline extension RPCs that the pubsub package -sends to the server. - -The default max extension period is DefaultReceiveSettings.MaxExtension, and can -be overridden by setting Subscription.ReceiveSettings.MaxExtension. Selecting a -max extension period is a tradeoff between the speed at which client code must -process messages, and the redelivery delay if messages fail to be acknowledged -(e.g. because client code neglects to do so). Using a large MaxExtension -increases the available time for client code to process messages. However, if -the client code neglects to call Message.Ack/Nack, a large MaxExtension will -increase the delay before the message is redelivered. - -Slow Message Processing - -For use cases where message processing exceeds 30 minutes, we recommend using -the base client in a pull model, since long-lived streams are periodically killed -by firewalls. See the example at https://godoc.org/cloud.google.com/go/pubsub/apiv1#example-SubscriberClient-Pull-LengthyClientProcessing -*/ -package pubsub // import "cloud.google.com/go/pubsub" diff --git a/vendor/cloud.google.com/go/pubsub/flow_controller.go b/vendor/cloud.google.com/go/pubsub/flow_controller.go deleted file mode 100644 index 0fd7bd6c83d..00000000000 --- a/vendor/cloud.google.com/go/pubsub/flow_controller.go +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package pubsub - -import ( - "golang.org/x/net/context" - "golang.org/x/sync/semaphore" -) - -// flowController implements flow control for Subscription.Receive. -type flowController struct { - maxSize int // max total size of messages - semCount, semSize *semaphore.Weighted // enforces max number and size of messages -} - -// newFlowController creates a new flowController that ensures no more than -// maxCount messages or maxSize bytes are outstanding at once. If maxCount or -// maxSize is < 1, then an unlimited number of messages or bytes is permitted, -// respectively. -func newFlowController(maxCount, maxSize int) *flowController { - fc := &flowController{ - maxSize: maxSize, - semCount: nil, - semSize: nil, - } - if maxCount > 0 { - fc.semCount = semaphore.NewWeighted(int64(maxCount)) - } - if maxSize > 0 { - fc.semSize = semaphore.NewWeighted(int64(maxSize)) - } - return fc -} - -// acquire blocks until one message of size bytes can proceed or ctx is done. -// It returns nil in the first case, or ctx.Err() in the second. -// -// acquire allows large messages to proceed by treating a size greater than maxSize -// as if it were equal to maxSize. -func (f *flowController) acquire(ctx context.Context, size int) error { - if f.semCount != nil { - if err := f.semCount.Acquire(ctx, 1); err != nil { - return err - } - } - if f.semSize != nil { - if err := f.semSize.Acquire(ctx, f.bound(size)); err != nil { - if f.semCount != nil { - f.semCount.Release(1) - } - return err - } - } - return nil -} - -// tryAcquire returns false if acquire would block. Otherwise, it behaves like -// acquire and returns true. -// -// tryAcquire allows large messages to proceed by treating a size greater than -// maxSize as if it were equal to maxSize. -func (f *flowController) tryAcquire(size int) bool { - if f.semCount != nil { - if !f.semCount.TryAcquire(1) { - return false - } - } - if f.semSize != nil { - if !f.semSize.TryAcquire(f.bound(size)) { - if f.semCount != nil { - f.semCount.Release(1) - } - return false - } - } - return true -} - -// release notes that one message of size bytes is no longer outstanding. -func (f *flowController) release(size int) { - if f.semCount != nil { - f.semCount.Release(1) - } - if f.semSize != nil { - f.semSize.Release(f.bound(size)) - } -} - -func (f *flowController) bound(size int) int64 { - if size > f.maxSize { - return int64(f.maxSize) - } - return int64(size) -} diff --git a/vendor/cloud.google.com/go/pubsub/go18.go b/vendor/cloud.google.com/go/pubsub/go18.go deleted file mode 100644 index 7a7229460ad..00000000000 --- a/vendor/cloud.google.com/go/pubsub/go18.go +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright 2018 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build go1.8 - -package pubsub - -import ( - "log" - "sync" - - "go.opencensus.io/plugin/ocgrpc" - "go.opencensus.io/stats" - "go.opencensus.io/stats/view" - "go.opencensus.io/tag" - "golang.org/x/net/context" - "google.golang.org/api/option" - "google.golang.org/grpc" -) - -func openCensusOptions() []option.ClientOption { - return []option.ClientOption{ - option.WithGRPCDialOption(grpc.WithStatsHandler(&ocgrpc.ClientHandler{})), - } -} - -var subscriptionKey tag.Key - -func init() { - var err error - if subscriptionKey, err = tag.NewKey("subscription"); err != nil { - log.Fatal("cannot create 'subscription' key") - } -} - -const statsPrefix = "cloud.google.com/go/pubsub/" - -var ( - // PullCount is a measure of the number of messages pulled. - // It is EXPERIMENTAL and subject to change or removal without notice. - PullCount = stats.Int64(statsPrefix+"pull_count", "Number of PubSub messages pulled", stats.UnitNone) - - // AckCount is a measure of the number of messages acked. - // It is EXPERIMENTAL and subject to change or removal without notice. - AckCount = stats.Int64(statsPrefix+"ack_count", "Number of PubSub messages acked", stats.UnitNone) - - // NackCount is a measure of the number of messages nacked. - // It is EXPERIMENTAL and subject to change or removal without notice. - NackCount = stats.Int64(statsPrefix+"nack_count", "Number of PubSub messages nacked", stats.UnitNone) - - // ModAckCount is a measure of the number of messages whose ack-deadline was modified. - // It is EXPERIMENTAL and subject to change or removal without notice. - ModAckCount = stats.Int64(statsPrefix+"mod_ack_count", "Number of ack-deadlines modified", stats.UnitNone) - - // StreamOpenCount is a measure of the number of times a streaming-pull stream was opened. - // It is EXPERIMENTAL and subject to change or removal without notice. - StreamOpenCount = stats.Int64(statsPrefix+"stream_open_count", "Number of calls opening a new streaming pull", stats.UnitNone) - - // StreamRetryCount is a measure of the number of times a streaming-pull operation was retried. - // It is EXPERIMENTAL and subject to change or removal without notice. - StreamRetryCount = stats.Int64(statsPrefix+"stream_retry_count", "Number of retries of a stream send or receive", stats.UnitNone) - - // StreamRequestCount is a measure of the number of requests sent on a streaming-pull stream. - // It is EXPERIMENTAL and subject to change or removal without notice. - StreamRequestCount = stats.Int64(statsPrefix+"stream_request_count", "Number gRPC StreamingPull request messages sent", stats.UnitNone) - - // StreamResponseCount is a measure of the number of responses received on a streaming-pull stream. - // It is EXPERIMENTAL and subject to change or removal without notice. - StreamResponseCount = stats.Int64(statsPrefix+"stream_response_count", "Number of gRPC StreamingPull response messages received", stats.UnitNone) - - // PullCountView is a cumulative sum of PullCount. - // It is EXPERIMENTAL and subject to change or removal without notice. - PullCountView *view.View - - // AckCountView is a cumulative sum of AckCount. - // It is EXPERIMENTAL and subject to change or removal without notice. - AckCountView *view.View - - // NackCountView is a cumulative sum of NackCount. - // It is EXPERIMENTAL and subject to change or removal without notice. - NackCountView *view.View - - // ModAckCountView is a cumulative sum of ModAckCount. - // It is EXPERIMENTAL and subject to change or removal without notice. - ModAckCountView *view.View - - // StreamOpenCountView is a cumulative sum of StreamOpenCount. - // It is EXPERIMENTAL and subject to change or removal without notice. - StreamOpenCountView *view.View - - // StreamRetryCountView is a cumulative sum of StreamRetryCount. - // It is EXPERIMENTAL and subject to change or removal without notice. - StreamRetryCountView *view.View - - // StreamRequestCountView is a cumulative sum of StreamRequestCount. - // It is EXPERIMENTAL and subject to change or removal without notice. - StreamRequestCountView *view.View - - // StreamResponseCountView is a cumulative sum of StreamResponseCount. - // It is EXPERIMENTAL and subject to change or removal without notice. - StreamResponseCountView *view.View -) - -func init() { - PullCountView = countView(PullCount) - AckCountView = countView(AckCount) - NackCountView = countView(NackCount) - ModAckCountView = countView(ModAckCount) - StreamOpenCountView = countView(StreamOpenCount) - StreamRetryCountView = countView(StreamRetryCount) - StreamRequestCountView = countView(StreamRequestCount) - StreamResponseCountView = countView(StreamResponseCount) -} - -func countView(m *stats.Int64Measure) *view.View { - return &view.View{ - Name: m.Name(), - Description: m.Description(), - TagKeys: []tag.Key{subscriptionKey}, - Measure: m, - Aggregation: view.Sum(), - } -} - -var logOnce sync.Once - -func withSubscriptionKey(ctx context.Context, subName string) context.Context { - ctx, err := tag.New(ctx, tag.Upsert(subscriptionKey, subName)) - if err != nil { - logOnce.Do(func() { - log.Printf("pubsub: error creating tag map: %v", err) - }) - } - return ctx -} - -func recordStat(ctx context.Context, m *stats.Int64Measure, n int64) { - stats.Record(ctx, m.M(n)) -} diff --git a/vendor/cloud.google.com/go/pubsub/internal/distribution/distribution.go b/vendor/cloud.google.com/go/pubsub/internal/distribution/distribution.go deleted file mode 100644 index c13fd636c72..00000000000 --- a/vendor/cloud.google.com/go/pubsub/internal/distribution/distribution.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package distribution - -import ( - "log" - "math" - "sort" - "sync/atomic" -) - -// D is a distribution. Methods of D can be called concurrently by multiple -// goroutines. -type D struct { - buckets []uint64 -} - -// New creates a new distribution capable of holding values from 0 to n-1. -func New(n int) *D { - return &D{ - buckets: make([]uint64, n), - } -} - -// Record records value v to the distribution. -// To help with distributions with long tails, if v is larger than the maximum value, -// Record records the maximum value instead. -// If v is negative, Record panics. -func (d *D) Record(v int) { - if v < 0 { - log.Panicf("Record: value out of range: %d", v) - } else if v >= len(d.buckets) { - v = len(d.buckets) - 1 - } - atomic.AddUint64(&d.buckets[v], 1) -} - -// Percentile computes the p-th percentile of the distribution where -// p is between 0 and 1. -func (d *D) Percentile(p float64) int { - // NOTE: This implementation uses the nearest-rank method. - // https://en.wikipedia.org/wiki/Percentile#The_nearest-rank_method - - if p < 0 || p > 1 { - log.Panicf("Percentile: percentile out of range: %f", p) - } - - bucketSums := make([]uint64, len(d.buckets)) - var sum uint64 - for i := range bucketSums { - sum += atomic.LoadUint64(&d.buckets[i]) - bucketSums[i] = sum - } - - total := bucketSums[len(bucketSums)-1] - target := uint64(math.Ceil(float64(total) * p)) - return sort.Search(len(bucketSums), func(i int) bool { return bucketSums[i] >= target }) -} diff --git a/vendor/cloud.google.com/go/pubsub/iterator.go b/vendor/cloud.google.com/go/pubsub/iterator.go deleted file mode 100644 index 78934e2c89f..00000000000 --- a/vendor/cloud.google.com/go/pubsub/iterator.go +++ /dev/null @@ -1,294 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package pubsub - -import ( - "sync" - "time" - - vkit "cloud.google.com/go/pubsub/apiv1" - "cloud.google.com/go/pubsub/internal/distribution" - "golang.org/x/net/context" - pb "google.golang.org/genproto/googleapis/pubsub/v1" -) - -// newMessageIterator starts a new streamingMessageIterator. Stop must be called on the messageIterator -// when it is no longer needed. -// subName is the full name of the subscription to pull messages from. -// ctx is the context to use for acking messages and extending message deadlines. -func newMessageIterator(ctx context.Context, subc *vkit.SubscriberClient, subName string, po *pullOptions) *streamingMessageIterator { - ps := newPullStream(ctx, subc, subName, int32(po.ackDeadline.Seconds())) - return newStreamingMessageIterator(ctx, ps, po) -} - -type streamingMessageIterator struct { - ctx context.Context - po *pullOptions - ps *pullStream - kaTicker *time.Ticker // keep-alive (deadline extensions) - ackTicker *time.Ticker // message acks - nackTicker *time.Ticker // message nacks (more frequent than acks) - failed chan struct{} // closed on stream error - stopped chan struct{} // closed when Stop is called - drained chan struct{} // closed when stopped && no more pending messages - wg sync.WaitGroup - - mu sync.Mutex - ackTimeDist *distribution.D - keepAliveDeadlines map[string]time.Time - pendingReq *pb.StreamingPullRequest - pendingModAcks map[string]int32 // ack IDs whose ack deadline is to be modified - err error // error from stream failure -} - -func newStreamingMessageIterator(ctx context.Context, ps *pullStream, po *pullOptions) *streamingMessageIterator { - // TODO: make kaTicker frequency more configurable. (ackDeadline - 5s) is a - // reasonable default for now, because the minimum ack period is 10s. This - // gives us 5s grace. - keepAlivePeriod := po.ackDeadline - 5*time.Second - kaTicker := time.NewTicker(keepAlivePeriod) - - // Ack promptly so users don't lose work if client crashes. - ackTicker := time.NewTicker(100 * time.Millisecond) - nackTicker := time.NewTicker(100 * time.Millisecond) - it := &streamingMessageIterator{ - ctx: ctx, - ps: ps, - po: po, - kaTicker: kaTicker, - ackTicker: ackTicker, - nackTicker: nackTicker, - failed: make(chan struct{}), - stopped: make(chan struct{}), - drained: make(chan struct{}), - ackTimeDist: distribution.New(int(maxAckDeadline/time.Second) + 1), - keepAliveDeadlines: map[string]time.Time{}, - pendingReq: &pb.StreamingPullRequest{}, - pendingModAcks: map[string]int32{}, - } - it.wg.Add(1) - go it.sender() - return it -} - -// Subscription.receive will call stop on its messageIterator when finished with it. -// Stop will block until Done has been called on all Messages that have been -// returned by Next, or until the context with which the messageIterator was created -// is cancelled or exceeds its deadline. -func (it *streamingMessageIterator) stop() { - it.mu.Lock() - select { - case <-it.stopped: - default: - close(it.stopped) - } - it.checkDrained() - it.mu.Unlock() - it.wg.Wait() -} - -// checkDrained closes the drained channel if the iterator has been stopped and all -// pending messages have either been n/acked or expired. -// -// Called with the lock held. -func (it *streamingMessageIterator) checkDrained() { - select { - case <-it.drained: - return - default: - } - select { - case <-it.stopped: - if len(it.keepAliveDeadlines) == 0 { - close(it.drained) - } - default: - } -} - -// Called when a message is acked/nacked. -func (it *streamingMessageIterator) done(ackID string, ack bool, receiveTime time.Time) { - it.ackTimeDist.Record(int(time.Since(receiveTime) / time.Second)) - it.mu.Lock() - defer it.mu.Unlock() - delete(it.keepAliveDeadlines, ackID) - if ack { - it.pendingReq.AckIds = append(it.pendingReq.AckIds, ackID) - } else { - it.pendingModAcks[ackID] = 0 // Nack indicated by modifying the deadline to zero. - } - it.checkDrained() -} - -// fail is called when a stream method returns a permanent error. -func (it *streamingMessageIterator) fail(err error) { - it.mu.Lock() - if it.err == nil { - it.err = err - close(it.failed) - } - it.mu.Unlock() -} - -// receive makes a call to the stream's Recv method and returns -// its messages. -func (it *streamingMessageIterator) receive() ([]*Message, error) { - // Stop retrieving messages if the context is done, the stream - // failed, or the iterator's Stop method was called. - select { - case <-it.ctx.Done(): - return nil, it.ctx.Err() - default: - } - it.mu.Lock() - err := it.err - it.mu.Unlock() - if err != nil { - return nil, err - } - // Receive messages from stream. This may block indefinitely. - res, err := it.ps.Recv() - // The pullStream handles retries, so any error here is fatal. - if err != nil { - it.fail(err) - return nil, err - } - msgs, err := convertMessages(res.ReceivedMessages) - if err != nil { - it.fail(err) - return nil, err - } - - // We received some messages. Remember them so we can keep them alive. Also, - // arrange for a receipt mod-ack (which will occur at the next firing of - // nackTicker). - maxExt := time.Now().Add(it.po.maxExtension) - deadline := trunc32(int64(it.po.ackDeadline.Seconds())) - it.mu.Lock() - now := time.Now() - for _, m := range msgs { - m.receiveTime = now - m.doneFunc = it.done - it.keepAliveDeadlines[m.ackID] = maxExt - // The receipt mod-ack uses the subscription's configured ack deadline. Don't - // change the mod-ack if one is already pending. This is possible if there - // are retries. - if _, ok := it.pendingModAcks[m.ackID]; !ok { - it.pendingModAcks[m.ackID] = deadline - } - } - it.mu.Unlock() - return msgs, nil -} - -// sender runs in a goroutine and handles all sends to the stream. -func (it *streamingMessageIterator) sender() { - defer it.wg.Done() - defer it.kaTicker.Stop() - defer it.ackTicker.Stop() - defer it.nackTicker.Stop() - defer it.ps.CloseSend() - - done := false - for !done { - send := false - select { - case <-it.ctx.Done(): - // Context canceled or timed out: stop immediately, without - // another RPC. - return - - case <-it.failed: - // Stream failed: nothing to do, so stop immediately. - return - - case <-it.drained: - // All outstanding messages have been marked done: - // nothing left to do except send the final request. - it.mu.Lock() - send = (len(it.pendingReq.AckIds) > 0 || len(it.pendingModAcks) > 0) - done = true - - case <-it.kaTicker.C: - it.mu.Lock() - it.handleKeepAlives() - send = (len(it.pendingModAcks) > 0) - - case <-it.nackTicker.C: - it.mu.Lock() - send = (len(it.pendingModAcks) > 0) - - case <-it.ackTicker.C: - it.mu.Lock() - send = (len(it.pendingReq.AckIds) > 0) - } - // Lock is held here. - if send { - req := it.pendingReq - it.pendingReq = &pb.StreamingPullRequest{} - modAcks := it.pendingModAcks - it.pendingModAcks = map[string]int32{} - it.mu.Unlock() - for id, s := range modAcks { - req.ModifyDeadlineAckIds = append(req.ModifyDeadlineAckIds, id) - req.ModifyDeadlineSeconds = append(req.ModifyDeadlineSeconds, s) - } - err := it.send(req) - if err != nil { - // The streamingPuller handles retries, so any error here - // is fatal to the iterator. - it.fail(err) - return - } - } else { - it.mu.Unlock() - } - } -} - -func (it *streamingMessageIterator) send(req *pb.StreamingPullRequest) error { - // Note: len(modAckIDs) == len(modSecs) - var rest *pb.StreamingPullRequest - for len(req.AckIds) > 0 || len(req.ModifyDeadlineAckIds) > 0 { - req, rest = splitRequest(req, maxPayload) - if err := it.ps.Send(req); err != nil { - return err - } - req = rest - } - return nil -} - -// handleKeepAlives modifies the pending request to include deadline extensions -// for live messages. It also purges expired messages. -// -// Called with the lock held. -func (it *streamingMessageIterator) handleKeepAlives() { - now := time.Now() - dl := trunc32(int64(it.po.ackDeadline.Seconds())) - for id, expiry := range it.keepAliveDeadlines { - if expiry.Before(now) { - // This delete will not result in skipping any map items, as implied by - // the spec at https://golang.org/ref/spec#For_statements, "For - // statements with range clause", note 3, and stated explicitly at - // https://groups.google.com/forum/#!msg/golang-nuts/UciASUb03Js/pzSq5iVFAQAJ. - delete(it.keepAliveDeadlines, id) - } else { - // This will not overwrite a nack, because nacking removes the ID from keepAliveDeadlines. - it.pendingModAcks[id] = dl - } - } - it.checkDrained() -} diff --git a/vendor/cloud.google.com/go/pubsub/message.go b/vendor/cloud.google.com/go/pubsub/message.go deleted file mode 100644 index ac2cecca32b..00000000000 --- a/vendor/cloud.google.com/go/pubsub/message.go +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package pubsub - -import ( - "time" - - "github.com/golang/protobuf/ptypes" - pb "google.golang.org/genproto/googleapis/pubsub/v1" -) - -// Message represents a Pub/Sub message. -type Message struct { - // ID identifies this message. - // This ID is assigned by the server and is populated for Messages obtained from a subscription. - // This field is read-only. - ID string - - // Data is the actual data in the message. - Data []byte - - // Attributes represents the key-value pairs the current message - // is labelled with. - Attributes map[string]string - - // ackID is the identifier to acknowledge this message. - ackID string - - // The time at which the message was published. - // This is populated by the server for Messages obtained from a subscription. - // This field is read-only. - PublishTime time.Time - - // receiveTime is the time the message was received by the client. - receiveTime time.Time - - // size is the approximate size of the message's data and attributes. - size int - - calledDone bool - - // The done method of the iterator that created this Message. - doneFunc func(string, bool, time.Time) -} - -func toMessage(resp *pb.ReceivedMessage) (*Message, error) { - if resp.Message == nil { - return &Message{ackID: resp.AckId}, nil - } - - pubTime, err := ptypes.Timestamp(resp.Message.PublishTime) - if err != nil { - return nil, err - } - return &Message{ - ackID: resp.AckId, - Data: resp.Message.Data, - Attributes: resp.Message.Attributes, - ID: resp.Message.MessageId, - PublishTime: pubTime, - }, nil -} - -// Ack indicates successful processing of a Message passed to the Subscriber.Receive callback. -// It should not be called on any other Message value. -// If message acknowledgement fails, the Message will be redelivered. -// Client code must call Ack or Nack when finished for each received Message. -// Calls to Ack or Nack have no effect after the first call. -func (m *Message) Ack() { - m.done(true) -} - -// Nack indicates that the client will not or cannot process a Message passed to the Subscriber.Receive callback. -// It should not be called on any other Message value. -// Nack will result in the Message being redelivered more quickly than if it were allowed to expire. -// Client code must call Ack or Nack when finished for each received Message. -// Calls to Ack or Nack have no effect after the first call. -func (m *Message) Nack() { - m.done(false) -} - -func (m *Message) done(ack bool) { - if m.calledDone { - return - } - m.calledDone = true - m.doneFunc(m.ackID, ack, m.receiveTime) -} diff --git a/vendor/cloud.google.com/go/pubsub/not_go18.go b/vendor/cloud.google.com/go/pubsub/not_go18.go deleted file mode 100644 index 09fd4bf5806..00000000000 --- a/vendor/cloud.google.com/go/pubsub/not_go18.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2018 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build !go1.8 - -package pubsub - -import ( - "golang.org/x/net/context" - "google.golang.org/api/option" -) - -// OpenCensus only supports go 1.8 and higher. - -func openCensusOptions() []option.ClientOption { return nil } - -func withSubscriptionKey(ctx context.Context, _ string) context.Context { - return ctx -} - -type dummy struct{} - -var ( - // Not supported below Go 1.8. - PullCount dummy - // Not supported below Go 1.8. - AckCount dummy - // Not supported below Go 1.8. - NackCount dummy - // Not supported below Go 1.8. - ModAckCount dummy - // Not supported below Go 1.8. - StreamOpenCount dummy - // Not supported below Go 1.8. - StreamRetryCount dummy - // Not supported below Go 1.8. - StreamRequestCount dummy - // Not supported below Go 1.8. - StreamResponseCount dummy -) - -func recordStat(context.Context, dummy, int64) { -} diff --git a/vendor/cloud.google.com/go/pubsub/pubsub.go b/vendor/cloud.google.com/go/pubsub/pubsub.go deleted file mode 100644 index 8475186d739..00000000000 --- a/vendor/cloud.google.com/go/pubsub/pubsub.go +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package pubsub // import "cloud.google.com/go/pubsub" - -import ( - "fmt" - "os" - "runtime" - "time" - - "cloud.google.com/go/internal/version" - vkit "cloud.google.com/go/pubsub/apiv1" - "golang.org/x/net/context" - "google.golang.org/api/option" - "google.golang.org/grpc" - "google.golang.org/grpc/keepalive" -) - -const ( - // ScopePubSub grants permissions to view and manage Pub/Sub - // topics and subscriptions. - ScopePubSub = "https://www.googleapis.com/auth/pubsub" - - // ScopeCloudPlatform grants permissions to view and manage your data - // across Google Cloud Platform services. - ScopeCloudPlatform = "https://www.googleapis.com/auth/cloud-platform" -) - -const ( - prodAddr = "https://pubsub.googleapis.com/" - minAckDeadline = 10 * time.Second - maxAckDeadline = 10 * time.Minute -) - -// Client is a Google Pub/Sub client scoped to a single project. -// -// Clients should be reused rather than being created as needed. -// A Client may be shared by multiple goroutines. -type Client struct { - projectID string - pubc *vkit.PublisherClient - subc *vkit.SubscriberClient -} - -// NewClient creates a new PubSub client. -func NewClient(ctx context.Context, projectID string, opts ...option.ClientOption) (c *Client, err error) { - var o []option.ClientOption - // Environment variables for gcloud emulator: - // https://cloud.google.com/sdk/gcloud/reference/beta/emulators/pubsub/ - if addr := os.Getenv("PUBSUB_EMULATOR_HOST"); addr != "" { - conn, err := grpc.Dial(addr, grpc.WithInsecure()) - if err != nil { - return nil, fmt.Errorf("grpc.Dial: %v", err) - } - o = []option.ClientOption{option.WithGRPCConn(conn)} - } else { - o = []option.ClientOption{ - // Create multiple connections to increase throughput. - option.WithGRPCConnectionPool(runtime.GOMAXPROCS(0)), - option.WithGRPCDialOption(grpc.WithKeepaliveParams(keepalive.ClientParameters{ - Time: 5 * time.Minute, - })), - } - o = append(o, openCensusOptions()...) - } - o = append(o, opts...) - pubc, err := vkit.NewPublisherClient(ctx, o...) - if err != nil { - return nil, fmt.Errorf("pubsub: %v", err) - } - subc, err := vkit.NewSubscriberClient(ctx, option.WithGRPCConn(pubc.Connection())) - if err != nil { - // Should never happen, since we are passing in the connection. - // If it does, we cannot close, because the user may have passed in their - // own connection originally. - return nil, fmt.Errorf("pubsub: %v", err) - } - pubc.SetGoogleClientInfo("gccl", version.Repo) - subc.SetGoogleClientInfo("gccl", version.Repo) - return &Client{ - projectID: projectID, - pubc: pubc, - subc: subc, - }, nil -} - -// Close releases any resources held by the client, -// such as memory and goroutines. -// -// If the client is available for the lifetime of the program, then Close need not be -// called at exit. -func (c *Client) Close() error { - // Return the first error, because the first call closes the connection. - err := c.pubc.Close() - _ = c.subc.Close() - return err -} - -func (c *Client) fullyQualifiedProjectName() string { - return fmt.Sprintf("projects/%s", c.projectID) -} diff --git a/vendor/cloud.google.com/go/pubsub/pullstream.go b/vendor/cloud.google.com/go/pubsub/pullstream.go deleted file mode 100644 index 4aea1d501b9..00000000000 --- a/vendor/cloud.google.com/go/pubsub/pullstream.go +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright 2018 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package pubsub - -import ( - "io" - "sync" - "time" - - vkit "cloud.google.com/go/pubsub/apiv1" - gax "github.com/googleapis/gax-go" - "golang.org/x/net/context" - pb "google.golang.org/genproto/googleapis/pubsub/v1" - "google.golang.org/grpc" -) - -// A pullStream supports the methods of a StreamingPullClient, but re-opens -// the stream on a retryable error. -type pullStream struct { - ctx context.Context - open func() (pb.Subscriber_StreamingPullClient, error) - - mu sync.Mutex - spc *pb.Subscriber_StreamingPullClient - err error // permanent error -} - -func newPullStream(ctx context.Context, subc *vkit.SubscriberClient, subName string, ackDeadlineSecs int32) *pullStream { - ctx = withSubscriptionKey(ctx, subName) - return &pullStream{ - ctx: ctx, - open: func() (pb.Subscriber_StreamingPullClient, error) { - spc, err := subc.StreamingPull(ctx, gax.WithGRPCOptions(grpc.MaxCallRecvMsgSize(maxSendRecvBytes))) - if err == nil { - recordStat(ctx, StreamRequestCount, 1) - err = spc.Send(&pb.StreamingPullRequest{ - Subscription: subName, - StreamAckDeadlineSeconds: ackDeadlineSecs, - }) - } - if err != nil { - return nil, err - } - return spc, nil - }, - } -} - -// get returns either a valid *StreamingPullClient (SPC), or a permanent error. -// If the argument is nil, this is the first call for an RPC, and the current -// SPC will be returned (or a new one will be opened). Otherwise, this call is a -// request to re-open the stream because of a retryable error, and the argument -// is a pointer to the SPC that returned the error. -func (s *pullStream) get(spc *pb.Subscriber_StreamingPullClient) (*pb.Subscriber_StreamingPullClient, error) { - s.mu.Lock() - defer s.mu.Unlock() - // A stored error is permanent. - if s.err != nil { - return nil, s.err - } - // If the context is done, so are we. - select { - case <-s.ctx.Done(): - s.err = s.ctx.Err() - return nil, s.err - default: - } - // TODO(jba): We can use the following instead of the above after we drop support for 1.8: - // s.err = s.ctx.Err() - // if s.err != nil { - // return nil, s.err - // } - - // If the current and argument SPCs differ, return the current one. This subsumes two cases: - // 1. We have an SPC and the caller is getting the stream for the first time. - // 2. The caller wants to retry, but they have an older SPC; we've already retried. - if spc != s.spc { - return s.spc, nil - } - // Either this is the very first call on this stream (s.spc == nil), or we have a valid - // retry request. Either way, open a new stream. - // The lock is held here for a long time, but it doesn't matter because no callers could get - // anything done anyway. - s.spc = new(pb.Subscriber_StreamingPullClient) - recordStat(s.ctx, StreamOpenCount, 1) - *s.spc, s.err = s.open() // Setting s.err means any error from open is permanent. Reconsider. - return s.spc, s.err -} - -func (s *pullStream) call(f func(pb.Subscriber_StreamingPullClient) error) error { - var ( - spc *pb.Subscriber_StreamingPullClient - err error - bo gax.Backoff - ) - for i := 0; ; i++ { - spc, err = s.get(spc) - if err != nil { - // Preserve the existing behavior of not retrying on open. Is that a bug? - // (If we do decide to retry, don't retry after we're closed.) - return err - } - start := time.Now() - err = f(*spc) - if err != nil { - if isRetryable(err) { - recordStat(s.ctx, StreamRetryCount, 1) - if time.Since(start) < 30*time.Second { // don't sleep if we've been blocked for a while - if err := gax.Sleep(s.ctx, bo.Pause()); err != nil { - return err - } - } - continue - } - s.mu.Lock() - s.err = err - s.mu.Unlock() - } - return err - } -} - -func (s *pullStream) Send(req *pb.StreamingPullRequest) error { - return s.call(func(spc pb.Subscriber_StreamingPullClient) error { - recordStat(s.ctx, AckCount, int64(len(req.AckIds))) - zeroes := 0 - for _, mds := range req.ModifyDeadlineSeconds { - if mds == 0 { - zeroes++ - } - } - recordStat(s.ctx, NackCount, int64(zeroes)) - recordStat(s.ctx, ModAckCount, int64(len(req.ModifyDeadlineSeconds)-zeroes)) - recordStat(s.ctx, StreamRequestCount, 1) - return spc.Send(req) - }) -} - -func (s *pullStream) Recv() (*pb.StreamingPullResponse, error) { - var res *pb.StreamingPullResponse - err := s.call(func(spc pb.Subscriber_StreamingPullClient) error { - var err error - recordStat(s.ctx, StreamResponseCount, 1) - res, err = spc.Recv() - if err == nil { - recordStat(s.ctx, PullCount, int64(len(res.ReceivedMessages))) - } - return err - }) - return res, err -} - -func (s *pullStream) CloseSend() error { - err := s.call(func(spc pb.Subscriber_StreamingPullClient) error { - return spc.CloseSend() - }) - s.mu.Lock() - s.err = io.EOF // should not be retried - s.mu.Unlock() - return err -} diff --git a/vendor/cloud.google.com/go/pubsub/service.go b/vendor/cloud.google.com/go/pubsub/service.go deleted file mode 100644 index c63e4d92dcc..00000000000 --- a/vendor/cloud.google.com/go/pubsub/service.go +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package pubsub - -import ( - "fmt" - "math" - "strings" - - pb "google.golang.org/genproto/googleapis/pubsub/v1" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -// maxPayload is the maximum number of bytes to devote to actual ids in -// acknowledgement or modifyAckDeadline requests. A serialized -// AcknowledgeRequest proto has a small constant overhead, plus the size of the -// subscription name, plus 3 bytes per ID (a tag byte and two size bytes). A -// ModifyAckDeadlineRequest has an additional few bytes for the deadline. We -// don't know the subscription name here, so we just assume the size exclusive -// of ids is 100 bytes. -// -// With gRPC there is no way for the client to know the server's max message size (it is -// configurable on the server). We know from experience that it -// it 512K. -const ( - maxPayload = 512 * 1024 - reqFixedOverhead = 100 - overheadPerID = 3 - maxSendRecvBytes = 20 * 1024 * 1024 // 20M -) - -func convertMessages(rms []*pb.ReceivedMessage) ([]*Message, error) { - msgs := make([]*Message, 0, len(rms)) - for i, m := range rms { - msg, err := toMessage(m) - if err != nil { - return nil, fmt.Errorf("pubsub: cannot decode the retrieved message at index: %d, message: %+v", i, m) - } - msgs = append(msgs, msg) - } - return msgs, nil -} - -func trunc32(i int64) int32 { - if i > math.MaxInt32 { - i = math.MaxInt32 - } - return int32(i) -} - -// Logic from https://github.com/GoogleCloudPlatform/google-cloud-java/blob/master/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/v1/StatusUtil.java. -func isRetryable(err error) bool { - s, ok := status.FromError(err) - if !ok { // includes io.EOF, normal stream close, which causes us to reopen - return true - } - switch s.Code() { - case codes.DeadlineExceeded, codes.Internal, codes.Canceled, codes.ResourceExhausted: - return true - case codes.Unavailable: - return !strings.Contains(s.Message(), "Server shutdownNow invoked") - default: - return false - } -} - -// Split req into a prefix that is smaller than maxSize, and a remainder. -func splitRequest(req *pb.StreamingPullRequest, maxSize int) (prefix, remainder *pb.StreamingPullRequest) { - const int32Bytes = 4 - - // Copy all fields before splitting the variable-sized ones. - remainder = &pb.StreamingPullRequest{} - *remainder = *req - // Split message so it isn't too big. - size := reqFixedOverhead - i := 0 - for size < maxSize && (i < len(req.AckIds) || i < len(req.ModifyDeadlineAckIds)) { - if i < len(req.AckIds) { - size += overheadPerID + len(req.AckIds[i]) - } - if i < len(req.ModifyDeadlineAckIds) { - size += overheadPerID + len(req.ModifyDeadlineAckIds[i]) + int32Bytes - } - i++ - } - - min := func(a, b int) int { - if a < b { - return a - } - return b - } - - j := i - if size > maxSize { - j-- - } - k := min(j, len(req.AckIds)) - remainder.AckIds = req.AckIds[k:] - req.AckIds = req.AckIds[:k] - k = min(j, len(req.ModifyDeadlineAckIds)) - remainder.ModifyDeadlineAckIds = req.ModifyDeadlineAckIds[k:] - remainder.ModifyDeadlineSeconds = req.ModifyDeadlineSeconds[k:] - req.ModifyDeadlineAckIds = req.ModifyDeadlineAckIds[:k] - req.ModifyDeadlineSeconds = req.ModifyDeadlineSeconds[:k] - return req, remainder -} diff --git a/vendor/cloud.google.com/go/pubsub/snapshot.go b/vendor/cloud.google.com/go/pubsub/snapshot.go deleted file mode 100644 index 7140e96627a..00000000000 --- a/vendor/cloud.google.com/go/pubsub/snapshot.go +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package pubsub - -import ( - "fmt" - "strings" - "time" - - "github.com/golang/protobuf/ptypes" - "golang.org/x/net/context" - pb "google.golang.org/genproto/googleapis/pubsub/v1" -) - -// Snapshot is a reference to a PubSub snapshot. -type Snapshot struct { - c *Client - - // The fully qualified identifier for the snapshot, in the format "projects//snapshots/" - name string -} - -// ID returns the unique identifier of the snapshot within its project. -func (s *Snapshot) ID() string { - slash := strings.LastIndex(s.name, "/") - if slash == -1 { - // name is not a fully-qualified name. - panic("bad snapshot name") - } - return s.name[slash+1:] -} - -// SnapshotConfig contains the details of a Snapshot. -type SnapshotConfig struct { - *Snapshot - Topic *Topic - Expiration time.Time -} - -// Snapshot creates a reference to a snapshot. -func (c *Client) Snapshot(id string) *Snapshot { - return &Snapshot{ - c: c, - name: fmt.Sprintf("projects/%s/snapshots/%s", c.projectID, id), - } -} - -// Snapshots returns an iterator which returns snapshots for this project. -func (c *Client) Snapshots(ctx context.Context) *SnapshotConfigIterator { - it := c.subc.ListSnapshots(ctx, &pb.ListSnapshotsRequest{ - Project: c.fullyQualifiedProjectName(), - }) - next := func() (*SnapshotConfig, error) { - snap, err := it.Next() - if err != nil { - return nil, err - } - return toSnapshotConfig(snap, c) - } - return &SnapshotConfigIterator{next: next} -} - -// SnapshotConfigIterator is an iterator that returns a series of snapshots. -type SnapshotConfigIterator struct { - next func() (*SnapshotConfig, error) -} - -// Next returns the next SnapshotConfig. Its second return value is iterator.Done if there are no more results. -// Once Next returns iterator.Done, all subsequent calls will return iterator.Done. -func (snaps *SnapshotConfigIterator) Next() (*SnapshotConfig, error) { - return snaps.next() -} - -// Delete deletes a snapshot. -func (snap *Snapshot) Delete(ctx context.Context) error { - return snap.c.subc.DeleteSnapshot(ctx, &pb.DeleteSnapshotRequest{Snapshot: snap.name}) -} - -// SeekToTime seeks the subscription to a point in time. -// -// Messages retained in the subscription that were published before this -// time are marked as acknowledged, and messages retained in the -// subscription that were published after this time are marked as -// unacknowledged. Note that this operation affects only those messages -// retained in the subscription (configured by SnapshotConfig). For example, -// if `time` corresponds to a point before the message retention -// window (or to a point before the system's notion of the subscription -// creation time), only retained messages will be marked as unacknowledged, -// and already-expunged messages will not be restored. -func (s *Subscription) SeekToTime(ctx context.Context, t time.Time) error { - ts, err := ptypes.TimestampProto(t) - if err != nil { - return err - } - _, err = s.c.subc.Seek(ctx, &pb.SeekRequest{ - Subscription: s.name, - Target: &pb.SeekRequest_Time{ts}, - }) - return err -} - -// CreateSnapshot creates a new snapshot from this subscription. -// The snapshot will be for the topic this subscription is subscribed to. -// If the name is empty string, a unique name is assigned. -// -// The created snapshot is guaranteed to retain: -// (a) The existing backlog on the subscription. More precisely, this is -// defined as the messages in the subscription's backlog that are -// unacknowledged when Snapshot returns without error. -// (b) Any messages published to the subscription's topic following -// Snapshot returning without error. -func (s *Subscription) CreateSnapshot(ctx context.Context, name string) (*SnapshotConfig, error) { - if name != "" { - name = fmt.Sprintf("projects/%s/snapshots/%s", strings.Split(s.name, "/")[1], name) - } - snap, err := s.c.subc.CreateSnapshot(ctx, &pb.CreateSnapshotRequest{ - Name: name, - Subscription: s.name, - }) - if err != nil { - return nil, err - } - return toSnapshotConfig(snap, s.c) -} - -// SeekToSnapshot seeks the subscription to a snapshot. -// -// The snapshot need not be created from this subscription, -// but it must be for the topic this subscription is subscribed to. -func (s *Subscription) SeekToSnapshot(ctx context.Context, snap *Snapshot) error { - _, err := s.c.subc.Seek(ctx, &pb.SeekRequest{ - Subscription: s.name, - Target: &pb.SeekRequest_Snapshot{snap.name}, - }) - return err -} - -func toSnapshotConfig(snap *pb.Snapshot, c *Client) (*SnapshotConfig, error) { - exp, err := ptypes.Timestamp(snap.ExpireTime) - if err != nil { - return nil, err - } - return &SnapshotConfig{ - Snapshot: &Snapshot{c: c, name: snap.Name}, - Topic: newTopic(c, snap.Topic), - Expiration: exp, - }, nil -} diff --git a/vendor/cloud.google.com/go/pubsub/subscription.go b/vendor/cloud.google.com/go/pubsub/subscription.go deleted file mode 100644 index 93054d536a0..00000000000 --- a/vendor/cloud.google.com/go/pubsub/subscription.go +++ /dev/null @@ -1,522 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package pubsub - -import ( - "errors" - "fmt" - "io" - "strings" - "sync" - "time" - - "cloud.google.com/go/iam" - "cloud.google.com/go/internal/optional" - "github.com/golang/protobuf/ptypes" - durpb "github.com/golang/protobuf/ptypes/duration" - "golang.org/x/net/context" - "golang.org/x/sync/errgroup" - pb "google.golang.org/genproto/googleapis/pubsub/v1" - fmpb "google.golang.org/genproto/protobuf/field_mask" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" -) - -// Subscription is a reference to a PubSub subscription. -type Subscription struct { - c *Client - - // The fully qualified identifier for the subscription, in the format "projects//subscriptions/" - name string - - // Settings for pulling messages. Configure these before calling Receive. - ReceiveSettings ReceiveSettings - - mu sync.Mutex - receiveActive bool -} - -// Subscription creates a reference to a subscription. -func (c *Client) Subscription(id string) *Subscription { - return c.SubscriptionInProject(id, c.projectID) -} - -// SubscriptionInProject creates a reference to a subscription in a given project. -func (c *Client) SubscriptionInProject(id, projectID string) *Subscription { - return &Subscription{ - c: c, - name: fmt.Sprintf("projects/%s/subscriptions/%s", projectID, id), - } -} - -// String returns the globally unique printable name of the subscription. -func (s *Subscription) String() string { - return s.name -} - -// ID returns the unique identifier of the subscription within its project. -func (s *Subscription) ID() string { - slash := strings.LastIndex(s.name, "/") - if slash == -1 { - // name is not a fully-qualified name. - panic("bad subscription name") - } - return s.name[slash+1:] -} - -// Subscriptions returns an iterator which returns all of the subscriptions for the client's project. -func (c *Client) Subscriptions(ctx context.Context) *SubscriptionIterator { - it := c.subc.ListSubscriptions(ctx, &pb.ListSubscriptionsRequest{ - Project: c.fullyQualifiedProjectName(), - }) - return &SubscriptionIterator{ - c: c, - next: func() (string, error) { - sub, err := it.Next() - if err != nil { - return "", err - } - return sub.Name, nil - }, - } -} - -// SubscriptionIterator is an iterator that returns a series of subscriptions. -type SubscriptionIterator struct { - c *Client - next func() (string, error) -} - -// Next returns the next subscription. If there are no more subscriptions, iterator.Done will be returned. -func (subs *SubscriptionIterator) Next() (*Subscription, error) { - subName, err := subs.next() - if err != nil { - return nil, err - } - return &Subscription{c: subs.c, name: subName}, nil -} - -// PushConfig contains configuration for subscriptions that operate in push mode. -type PushConfig struct { - // A URL locating the endpoint to which messages should be pushed. - Endpoint string - - // Endpoint configuration attributes. See https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions#pushconfig for more details. - Attributes map[string]string -} - -func (pc *PushConfig) toProto() *pb.PushConfig { - return &pb.PushConfig{ - Attributes: pc.Attributes, - PushEndpoint: pc.Endpoint, - } -} - -// Subscription config contains the configuration of a subscription. -type SubscriptionConfig struct { - Topic *Topic - PushConfig PushConfig - - // The default maximum time after a subscriber receives a message before - // the subscriber should acknowledge the message. Note: messages which are - // obtained via Subscription.Receive need not be acknowledged within this - // deadline, as the deadline will be automatically extended. - AckDeadline time.Duration - - // Whether to retain acknowledged messages. If true, acknowledged messages - // will not be expunged until they fall out of the RetentionDuration window. - RetainAckedMessages bool - - // How long to retain messages in backlog, from the time of publish. If - // RetainAckedMessages is true, this duration affects the retention of - // acknowledged messages, otherwise only unacknowledged messages are retained. - // Defaults to 7 days. Cannot be longer than 7 days or shorter than 10 minutes. - RetentionDuration time.Duration -} - -func (cfg *SubscriptionConfig) toProto(name string) *pb.Subscription { - var pbPushConfig *pb.PushConfig - if cfg.PushConfig.Endpoint != "" || len(cfg.PushConfig.Attributes) != 0 { - pbPushConfig = &pb.PushConfig{ - Attributes: cfg.PushConfig.Attributes, - PushEndpoint: cfg.PushConfig.Endpoint, - } - } - var retentionDuration *durpb.Duration - if cfg.RetentionDuration != 0 { - retentionDuration = ptypes.DurationProto(cfg.RetentionDuration) - } - return &pb.Subscription{ - Name: name, - Topic: cfg.Topic.name, - PushConfig: pbPushConfig, - AckDeadlineSeconds: trunc32(int64(cfg.AckDeadline.Seconds())), - RetainAckedMessages: cfg.RetainAckedMessages, - MessageRetentionDuration: retentionDuration, - } -} - -func protoToSubscriptionConfig(pbSub *pb.Subscription, c *Client) (SubscriptionConfig, error) { - rd := time.Hour * 24 * 7 - var err error - if pbSub.MessageRetentionDuration != nil { - rd, err = ptypes.Duration(pbSub.MessageRetentionDuration) - if err != nil { - return SubscriptionConfig{}, err - } - } - return SubscriptionConfig{ - Topic: newTopic(c, pbSub.Topic), - AckDeadline: time.Second * time.Duration(pbSub.AckDeadlineSeconds), - PushConfig: PushConfig{ - Endpoint: pbSub.PushConfig.PushEndpoint, - Attributes: pbSub.PushConfig.Attributes, - }, - RetainAckedMessages: pbSub.RetainAckedMessages, - RetentionDuration: rd, - }, nil -} - -// ReceiveSettings configure the Receive method. -// A zero ReceiveSettings will result in values equivalent to DefaultReceiveSettings. -type ReceiveSettings struct { - // MaxExtension is the maximum period for which the Subscription should - // automatically extend the ack deadline for each message. - // - // The Subscription will automatically extend the ack deadline of all - // fetched Messages for the duration specified. Automatic deadline - // extension may be disabled by specifying a duration less than 0. - // - // Connections may be terminated if they last longer than 30m, which - // effectively makes that the ceiling for this value. For longer message - // processing, see the example at https://godoc.org/cloud.google.com/go/pubsub/apiv1#example_SubscriberClient_Pull_lengthyClientProcessing - MaxExtension time.Duration - - // MaxOutstandingMessages is the maximum number of unprocessed messages - // (unacknowledged but not yet expired). If MaxOutstandingMessages is 0, it - // will be treated as if it were DefaultReceiveSettings.MaxOutstandingMessages. - // If the value is negative, then there will be no limit on the number of - // unprocessed messages. - MaxOutstandingMessages int - - // MaxOutstandingBytes is the maximum size of unprocessed messages - // (unacknowledged but not yet expired). If MaxOutstandingBytes is 0, it will - // be treated as if it were DefaultReceiveSettings.MaxOutstandingBytes. If - // the value is negative, then there will be no limit on the number of bytes - // for unprocessed messages. - MaxOutstandingBytes int - - // NumGoroutines is the number of goroutines Receive will spawn to pull - // messages concurrently. If NumGoroutines is less than 1, it will be treated - // as if it were DefaultReceiveSettings.NumGoroutines. - // - // NumGoroutines does not limit the number of messages that can be processed - // concurrently. Even with one goroutine, many messages might be processed at - // once, because that goroutine may continually receive messages and invoke the - // function passed to Receive on them. To limit the number of messages being - // processed concurrently, set MaxOutstandingMessages. - NumGoroutines int -} - -// DefaultReceiveSettings holds the default values for ReceiveSettings. -var DefaultReceiveSettings = ReceiveSettings{ - MaxExtension: 10 * time.Minute, - MaxOutstandingMessages: 1000, - MaxOutstandingBytes: 1e9, // 1G - NumGoroutines: 1, -} - -// Delete deletes the subscription. -func (s *Subscription) Delete(ctx context.Context) error { - return s.c.subc.DeleteSubscription(ctx, &pb.DeleteSubscriptionRequest{Subscription: s.name}) -} - -// Exists reports whether the subscription exists on the server. -func (s *Subscription) Exists(ctx context.Context) (bool, error) { - _, err := s.c.subc.GetSubscription(ctx, &pb.GetSubscriptionRequest{Subscription: s.name}) - if err == nil { - return true, nil - } - if grpc.Code(err) == codes.NotFound { - return false, nil - } - return false, err -} - -// Config fetches the current configuration for the subscription. -func (s *Subscription) Config(ctx context.Context) (SubscriptionConfig, error) { - pbSub, err := s.c.subc.GetSubscription(ctx, &pb.GetSubscriptionRequest{Subscription: s.name}) - if err != nil { - return SubscriptionConfig{}, err - } - cfg, err := protoToSubscriptionConfig(pbSub, s.c) - if err != nil { - return SubscriptionConfig{}, err - } - return cfg, nil -} - -// SubscriptionConfigToUpdate describes how to update a subscription. -type SubscriptionConfigToUpdate struct { - // If non-nil, the push config is changed. - PushConfig *PushConfig - - // If non-zero, the ack deadline is changed. - AckDeadline time.Duration - - // If set, RetainAckedMessages is changed. - RetainAckedMessages optional.Bool - - // If non-zero, RetentionDuration is changed. - RetentionDuration time.Duration -} - -// Update changes an existing subscription according to the fields set in cfg. -// It returns the new SubscriptionConfig. -// -// Update returns an error if no fields were modified. -func (s *Subscription) Update(ctx context.Context, cfg SubscriptionConfigToUpdate) (SubscriptionConfig, error) { - req := s.updateRequest(&cfg) - if len(req.UpdateMask.Paths) == 0 { - return SubscriptionConfig{}, errors.New("pubsub: UpdateSubscription call with nothing to update") - } - rpsub, err := s.c.subc.UpdateSubscription(ctx, req) - if err != nil { - return SubscriptionConfig{}, err - } - return protoToSubscriptionConfig(rpsub, s.c) -} - -func (s *Subscription) updateRequest(cfg *SubscriptionConfigToUpdate) *pb.UpdateSubscriptionRequest { - psub := &pb.Subscription{Name: s.name} - var paths []string - if cfg.PushConfig != nil { - psub.PushConfig = cfg.PushConfig.toProto() - paths = append(paths, "push_config") - } - if cfg.AckDeadline != 0 { - psub.AckDeadlineSeconds = trunc32(int64(cfg.AckDeadline.Seconds())) - paths = append(paths, "ack_deadline_seconds") - } - if cfg.RetainAckedMessages != nil { - psub.RetainAckedMessages = optional.ToBool(cfg.RetainAckedMessages) - paths = append(paths, "retain_acked_messages") - } - if cfg.RetentionDuration != 0 { - psub.MessageRetentionDuration = ptypes.DurationProto(cfg.RetentionDuration) - paths = append(paths, "message_retention_duration") - } - return &pb.UpdateSubscriptionRequest{ - Subscription: psub, - UpdateMask: &fmpb.FieldMask{Paths: paths}, - } -} - -func (s *Subscription) IAM() *iam.Handle { - return iam.InternalNewHandle(s.c.subc.Connection(), s.name) -} - -// CreateSubscription creates a new subscription on a topic. -// -// id is the name of the subscription to create. It must start with a letter, -// and contain only letters ([A-Za-z]), numbers ([0-9]), dashes (-), -// underscores (_), periods (.), tildes (~), plus (+) or percent signs (%). It -// must be between 3 and 255 characters in length, and must not start with -// "goog". -// -// cfg.Topic is the topic from which the subscription should receive messages. It -// need not belong to the same project as the subscription. This field is required. -// -// cfg.AckDeadline is the maximum time after a subscriber receives a message before -// the subscriber should acknowledge the message. It must be between 10 and 600 -// seconds (inclusive), and is rounded down to the nearest second. If the -// provided ackDeadline is 0, then the default value of 10 seconds is used. -// Note: messages which are obtained via Subscription.Receive need not be -// acknowledged within this deadline, as the deadline will be automatically -// extended. -// -// cfg.PushConfig may be set to configure this subscription for push delivery. -// -// If the subscription already exists an error will be returned. -func (c *Client) CreateSubscription(ctx context.Context, id string, cfg SubscriptionConfig) (*Subscription, error) { - if cfg.Topic == nil { - return nil, errors.New("pubsub: require non-nil Topic") - } - if cfg.AckDeadline == 0 { - cfg.AckDeadline = 10 * time.Second - } - if d := cfg.AckDeadline; d < 10*time.Second || d > 600*time.Second { - return nil, fmt.Errorf("ack deadline must be between 10 and 600 seconds; got: %v", d) - } - - sub := c.Subscription(id) - _, err := c.subc.CreateSubscription(ctx, cfg.toProto(sub.name)) - if err != nil { - return nil, err - } - return sub, nil -} - -var errReceiveInProgress = errors.New("pubsub: Receive already in progress for this subscription") - -// Receive calls f with the outstanding messages from the subscription. -// It blocks until ctx is done, or the service returns a non-retryable error. -// -// The standard way to terminate a Receive is to cancel its context: -// -// cctx, cancel := context.WithCancel(ctx) -// err := sub.Receive(cctx, callback) -// // Call cancel from callback, or another goroutine. -// -// If the service returns a non-retryable error, Receive returns that error after -// all of the outstanding calls to f have returned. If ctx is done, Receive -// returns nil after all of the outstanding calls to f have returned and -// all messages have been acknowledged or have expired. -// -// Receive calls f concurrently from multiple goroutines. It is encouraged to -// process messages synchronously in f, even if that processing is relatively -// time-consuming; Receive will spawn new goroutines for incoming messages, -// limited by MaxOutstandingMessages and MaxOutstandingBytes in ReceiveSettings. -// -// The context passed to f will be canceled when ctx is Done or there is a -// fatal service error. -// -// Receive will automatically extend the ack deadline of all fetched Messages for the -// period specified by s.ReceiveSettings.MaxExtension. -// -// Each Subscription may have only one invocation of Receive active at a time. -func (s *Subscription) Receive(ctx context.Context, f func(context.Context, *Message)) error { - s.mu.Lock() - if s.receiveActive { - s.mu.Unlock() - return errReceiveInProgress - } - s.receiveActive = true - s.mu.Unlock() - defer func() { s.mu.Lock(); s.receiveActive = false; s.mu.Unlock() }() - - config, err := s.Config(ctx) - if err != nil { - if grpc.Code(err) == codes.Canceled { - return nil - } - return err - } - maxCount := s.ReceiveSettings.MaxOutstandingMessages - if maxCount == 0 { - maxCount = DefaultReceiveSettings.MaxOutstandingMessages - } - maxBytes := s.ReceiveSettings.MaxOutstandingBytes - if maxBytes == 0 { - maxBytes = DefaultReceiveSettings.MaxOutstandingBytes - } - maxExt := s.ReceiveSettings.MaxExtension - if maxExt == 0 { - maxExt = DefaultReceiveSettings.MaxExtension - } else if maxExt < 0 { - // If MaxExtension is negative, disable automatic extension. - maxExt = 0 - } - numGoroutines := s.ReceiveSettings.NumGoroutines - if numGoroutines < 1 { - numGoroutines = DefaultReceiveSettings.NumGoroutines - } - // TODO(jba): add tests that verify that ReceiveSettings are correctly processed. - po := &pullOptions{ - maxExtension: maxExt, - maxPrefetch: trunc32(int64(maxCount)), - ackDeadline: config.AckDeadline, - } - fc := newFlowController(maxCount, maxBytes) - - // Wait for all goroutines started by Receive to return, so instead of an - // obscure goroutine leak we have an obvious blocked call to Receive. - group, gctx := errgroup.WithContext(ctx) - for i := 0; i < numGoroutines; i++ { - group.Go(func() error { - return s.receive(gctx, po, fc, f) - }) - } - return group.Wait() -} - -func (s *Subscription) receive(ctx context.Context, po *pullOptions, fc *flowController, f func(context.Context, *Message)) error { - // Cancel a sub-context when we return, to kick the context-aware callbacks - // and the goroutine below. - ctx2, cancel := context.WithCancel(ctx) - // Call stop when Receive's context is done. - // Stop will block until all outstanding messages have been acknowledged - // or there was a fatal service error. - // The iterator does not use the context passed to Receive. If it did, canceling - // that context would immediately stop the iterator without waiting for unacked - // messages. - iter := newMessageIterator(context.Background(), s.c.subc, s.name, po) - - // We cannot use errgroup from Receive here. Receive might already be calling group.Wait, - // and group.Wait cannot be called concurrently with group.Go. We give each receive() its - // own WaitGroup instead. - // Since wg.Add is only called from the main goroutine, wg.Wait is guaranteed - // to be called after all Adds. - var wg sync.WaitGroup - wg.Add(1) - go func() { - <-ctx2.Done() - iter.stop() - wg.Done() - }() - defer wg.Wait() - - defer cancel() - for { - msgs, err := iter.receive() - if err == io.EOF { - return nil - } - if err != nil { - return err - } - for i, msg := range msgs { - msg := msg - // TODO(jba): call acquire closer to when the message is allocated. - if err := fc.acquire(ctx, len(msg.Data)); err != nil { - // TODO(jba): test that these "orphaned" messages are nacked immediately when ctx is done. - for _, m := range msgs[i:] { - m.Nack() - } - return nil - } - old := msg.doneFunc - msgLen := len(msg.Data) - msg.doneFunc = func(ackID string, ack bool, receiveTime time.Time) { - defer fc.release(msgLen) - old(ackID, ack, receiveTime) - } - wg.Add(1) - go func() { - defer wg.Done() - f(ctx2, msg) - }() - } - } -} - -// TODO(jba): remove when we delete messageIterator. -type pullOptions struct { - maxExtension time.Duration - maxPrefetch int32 - // ackDeadline is the default ack deadline for the subscription. Not - // configurable. - ackDeadline time.Duration -} diff --git a/vendor/cloud.google.com/go/pubsub/topic.go b/vendor/cloud.google.com/go/pubsub/topic.go deleted file mode 100644 index 388d4510e6b..00000000000 --- a/vendor/cloud.google.com/go/pubsub/topic.go +++ /dev/null @@ -1,397 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package pubsub - -import ( - "errors" - "fmt" - "runtime" - "strings" - "sync" - "time" - - "cloud.google.com/go/iam" - "github.com/golang/protobuf/proto" - gax "github.com/googleapis/gax-go" - "golang.org/x/net/context" - "google.golang.org/api/support/bundler" - pb "google.golang.org/genproto/googleapis/pubsub/v1" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" -) - -const ( - // The maximum number of messages that can be in a single publish request, as - // determined by the PubSub service. - MaxPublishRequestCount = 1000 - - // The maximum size of a single publish request in bytes, as determined by the PubSub service. - MaxPublishRequestBytes = 1e7 - - maxInt = int(^uint(0) >> 1) -) - -// ErrOversizedMessage indicates that a message's size exceeds MaxPublishRequestBytes. -var ErrOversizedMessage = bundler.ErrOversizedItem - -// Topic is a reference to a PubSub topic. -// -// The methods of Topic are safe for use by multiple goroutines. -type Topic struct { - c *Client - // The fully qualified identifier for the topic, in the format "projects//topics/" - name string - - // Settings for publishing messages. All changes must be made before the - // first call to Publish. The default is DefaultPublishSettings. - PublishSettings PublishSettings - - mu sync.RWMutex - stopped bool - bundler *bundler.Bundler - - wg sync.WaitGroup - - // Channel for message bundles to be published. Close to indicate that Stop was called. - bundlec chan []*bundledMessage -} - -// PublishSettings control the bundling of published messages. -type PublishSettings struct { - - // Publish a non-empty batch after this delay has passed. - DelayThreshold time.Duration - - // Publish a batch when it has this many messages. The maximum is - // MaxPublishRequestCount. - CountThreshold int - - // Publish a batch when its size in bytes reaches this value. - ByteThreshold int - - // The number of goroutines that invoke the Publish RPC concurrently. - // Defaults to a multiple of GOMAXPROCS. - NumGoroutines int - - // The maximum time that the client will attempt to publish a bundle of messages. - Timeout time.Duration -} - -// DefaultPublishSettings holds the default values for topics' PublishSettings. -var DefaultPublishSettings = PublishSettings{ - DelayThreshold: 1 * time.Millisecond, - CountThreshold: 100, - ByteThreshold: 1e6, - Timeout: 60 * time.Second, -} - -// CreateTopic creates a new topic. -// The specified topic ID must start with a letter, and contain only letters -// ([A-Za-z]), numbers ([0-9]), dashes (-), underscores (_), periods (.), -// tildes (~), plus (+) or percent signs (%). It must be between 3 and 255 -// characters in length, and must not start with "goog". -// If the topic already exists an error will be returned. -func (c *Client) CreateTopic(ctx context.Context, id string) (*Topic, error) { - t := c.Topic(id) - _, err := c.pubc.CreateTopic(ctx, &pb.Topic{Name: t.name}) - if err != nil { - return nil, err - } - return t, nil -} - -// Topic creates a reference to a topic in the client's project. -// -// If a Topic's Publish method is called, it has background goroutines -// associated with it. Clean them up by calling Topic.Stop. -// -// Avoid creating many Topic instances if you use them to publish. -func (c *Client) Topic(id string) *Topic { - return c.TopicInProject(id, c.projectID) -} - -// TopicInProject creates a reference to a topic in the given project. -// -// If a Topic's Publish method is called, it has background goroutines -// associated with it. Clean them up by calling Topic.Stop. -// -// Avoid creating many Topic instances if you use them to publish. -func (c *Client) TopicInProject(id, projectID string) *Topic { - return newTopic(c, fmt.Sprintf("projects/%s/topics/%s", projectID, id)) -} - -func newTopic(c *Client, name string) *Topic { - // bundlec is unbuffered. A buffer would occupy memory not - // accounted for by the bundler, so BufferedByteLimit would be a lie: - // the actual memory consumed would be higher. - return &Topic{ - c: c, - name: name, - PublishSettings: DefaultPublishSettings, - bundlec: make(chan []*bundledMessage), - } -} - -// Topics returns an iterator which returns all of the topics for the client's project. -func (c *Client) Topics(ctx context.Context) *TopicIterator { - it := c.pubc.ListTopics(ctx, &pb.ListTopicsRequest{Project: c.fullyQualifiedProjectName()}) - return &TopicIterator{ - c: c, - next: func() (string, error) { - topic, err := it.Next() - if err != nil { - return "", err - } - return topic.Name, nil - }, - } -} - -// TopicIterator is an iterator that returns a series of topics. -type TopicIterator struct { - c *Client - next func() (string, error) -} - -// Next returns the next topic. If there are no more topics, iterator.Done will be returned. -func (tps *TopicIterator) Next() (*Topic, error) { - topicName, err := tps.next() - if err != nil { - return nil, err - } - return newTopic(tps.c, topicName), nil -} - -// ID returns the unique idenfier of the topic within its project. -func (t *Topic) ID() string { - slash := strings.LastIndex(t.name, "/") - if slash == -1 { - // name is not a fully-qualified name. - panic("bad topic name") - } - return t.name[slash+1:] -} - -// String returns the printable globally unique name for the topic. -func (t *Topic) String() string { - return t.name -} - -// Delete deletes the topic. -func (t *Topic) Delete(ctx context.Context) error { - return t.c.pubc.DeleteTopic(ctx, &pb.DeleteTopicRequest{Topic: t.name}) -} - -// Exists reports whether the topic exists on the server. -func (t *Topic) Exists(ctx context.Context) (bool, error) { - if t.name == "_deleted-topic_" { - return false, nil - } - _, err := t.c.pubc.GetTopic(ctx, &pb.GetTopicRequest{Topic: t.name}) - if err == nil { - return true, nil - } - if grpc.Code(err) == codes.NotFound { - return false, nil - } - return false, err -} - -func (t *Topic) IAM() *iam.Handle { - return iam.InternalNewHandle(t.c.pubc.Connection(), t.name) -} - -// Subscriptions returns an iterator which returns the subscriptions for this topic. -// -// Some of the returned subscriptions may belong to a project other than t. -func (t *Topic) Subscriptions(ctx context.Context) *SubscriptionIterator { - it := t.c.pubc.ListTopicSubscriptions(ctx, &pb.ListTopicSubscriptionsRequest{ - Topic: t.name, - }) - return &SubscriptionIterator{ - c: t.c, - next: it.Next, - } -} - -var errTopicStopped = errors.New("pubsub: Stop has been called for this topic") - -// Publish publishes msg to the topic asynchronously. Messages are batched and -// sent according to the topic's PublishSettings. Publish never blocks. -// -// Publish returns a non-nil PublishResult which will be ready when the -// message has been sent (or has failed to be sent) to the server. -// -// Publish creates goroutines for batching and sending messages. These goroutines -// need to be stopped by calling t.Stop(). Once stopped, future calls to Publish -// will immediately return a PublishResult with an error. -func (t *Topic) Publish(ctx context.Context, msg *Message) *PublishResult { - // TODO(jba): if this turns out to take significant time, try to approximate it. - // Or, convert the messages to protos in Publish, instead of in the service. - msg.size = proto.Size(&pb.PubsubMessage{ - Data: msg.Data, - Attributes: msg.Attributes, - }) - r := &PublishResult{ready: make(chan struct{})} - t.initBundler() - t.mu.RLock() - defer t.mu.RUnlock() - // TODO(aboulhosn) [from bcmills] consider changing the semantics of bundler to perform this logic so we don't have to do it here - if t.stopped { - r.set("", errTopicStopped) - return r - } - - // TODO(jba) [from bcmills] consider using a shared channel per bundle - // (requires Bundler API changes; would reduce allocations) - // The call to Add should never return an error because the bundler's - // BufferedByteLimit is set to maxInt; we do not perform any flow - // control in the client. - err := t.bundler.Add(&bundledMessage{msg, r}, msg.size) - if err != nil { - r.set("", err) - } - return r -} - -// Send all remaining published messages and stop goroutines created for handling -// publishing. Returns once all outstanding messages have been sent or have -// failed to be sent. -func (t *Topic) Stop() { - t.mu.Lock() - noop := t.stopped || t.bundler == nil - t.stopped = true - t.mu.Unlock() - if noop { - return - } - t.bundler.Flush() - // At this point, all pending bundles have been published and the bundler's - // goroutines have exited, so it is OK for this goroutine to close bundlec. - close(t.bundlec) - t.wg.Wait() -} - -// A PublishResult holds the result from a call to Publish. -type PublishResult struct { - ready chan struct{} - serverID string - err error -} - -// Ready returns a channel that is closed when the result is ready. -// When the Ready channel is closed, Get is guaranteed not to block. -func (r *PublishResult) Ready() <-chan struct{} { return r.ready } - -// Get returns the server-generated message ID and/or error result of a Publish call. -// Get blocks until the Publish call completes or the context is done. -func (r *PublishResult) Get(ctx context.Context) (serverID string, err error) { - // If the result is already ready, return it even if the context is done. - select { - case <-r.Ready(): - return r.serverID, r.err - default: - } - select { - case <-ctx.Done(): - return "", ctx.Err() - case <-r.Ready(): - return r.serverID, r.err - } -} - -func (r *PublishResult) set(sid string, err error) { - r.serverID = sid - r.err = err - close(r.ready) -} - -type bundledMessage struct { - msg *Message - res *PublishResult -} - -func (t *Topic) initBundler() { - t.mu.RLock() - noop := t.stopped || t.bundler != nil - t.mu.RUnlock() - if noop { - return - } - t.mu.Lock() - defer t.mu.Unlock() - // Must re-check, since we released the lock. - if t.stopped || t.bundler != nil { - return - } - - // TODO(jba): use a context detached from the one passed to NewClient. - ctx := context.TODO() - // Unless overridden, run several goroutines per CPU to call the Publish RPC. - n := t.PublishSettings.NumGoroutines - if n <= 0 { - n = 25 * runtime.GOMAXPROCS(0) - } - timeout := t.PublishSettings.Timeout - t.wg.Add(n) - for i := 0; i < n; i++ { - go func() { - defer t.wg.Done() - for b := range t.bundlec { - bctx := ctx - cancel := func() {} - if timeout != 0 { - bctx, cancel = context.WithTimeout(ctx, timeout) - } - t.publishMessageBundle(bctx, b) - cancel() - } - }() - } - t.bundler = bundler.NewBundler(&bundledMessage{}, func(items interface{}) { - t.bundlec <- items.([]*bundledMessage) - - }) - t.bundler.DelayThreshold = t.PublishSettings.DelayThreshold - t.bundler.BundleCountThreshold = t.PublishSettings.CountThreshold - if t.bundler.BundleCountThreshold > MaxPublishRequestCount { - t.bundler.BundleCountThreshold = MaxPublishRequestCount - } - t.bundler.BundleByteThreshold = t.PublishSettings.ByteThreshold - t.bundler.BufferedByteLimit = maxInt - t.bundler.BundleByteLimit = MaxPublishRequestBytes -} - -func (t *Topic) publishMessageBundle(ctx context.Context, bms []*bundledMessage) { - pbMsgs := make([]*pb.PubsubMessage, len(bms)) - for i, bm := range bms { - pbMsgs[i] = &pb.PubsubMessage{ - Data: bm.msg.Data, - Attributes: bm.msg.Attributes, - } - bm.msg = nil // release bm.msg for GC - } - res, err := t.c.pubc.Publish(ctx, &pb.PublishRequest{ - Topic: t.name, - Messages: pbMsgs, - }, gax.WithGRPCOptions(grpc.MaxCallSendMsgSize(maxSendRecvBytes))) - for i, bm := range bms { - if err != nil { - bm.res.set("", err) - } else { - bm.res.set(res.MessageIds[i], nil) - } - } -} diff --git a/vendor/github.com/Shopify/sarama/admin.go b/vendor/github.com/Shopify/sarama/admin.go index 68284641c82..52725758d21 100644 --- a/vendor/github.com/Shopify/sarama/admin.go +++ b/vendor/github.com/Shopify/sarama/admin.go @@ -118,6 +118,7 @@ func (ca *clusterAdmin) CreateTopic(topic string, detail *TopicDetail, validateO request := &CreateTopicsRequest{ TopicDetails: topicDetails, ValidateOnly: validateOnly, + Timeout: ca.conf.Admin.Timeout, } if ca.conf.Version.IsAtLeast(V0_11_0_0) { @@ -155,7 +156,10 @@ func (ca *clusterAdmin) DeleteTopic(topic string) error { return ErrInvalidTopic } - request := &DeleteTopicsRequest{Topics: []string{topic}} + request := &DeleteTopicsRequest{ + Topics: []string{topic}, + Timeout: ca.conf.Admin.Timeout, + } if ca.conf.Version.IsAtLeast(V0_11_0_0) { request.Version = 1 @@ -192,6 +196,7 @@ func (ca *clusterAdmin) CreatePartitions(topic string, count int32, assignment [ request := &CreatePartitionsRequest{ TopicPartitions: topicPartitions, + Timeout: ca.conf.Admin.Timeout, } b, err := ca.Controller() @@ -225,7 +230,9 @@ func (ca *clusterAdmin) DeleteRecords(topic string, partitionOffsets map[int32]i topics := make(map[string]*DeleteRecordsRequestTopic) topics[topic] = &DeleteRecordsRequestTopic{PartitionOffsets: partitionOffsets} request := &DeleteRecordsRequest{ - Topics: topics} + Topics: topics, + Timeout: ca.conf.Admin.Timeout, + } b, err := ca.Controller() if err != nil { diff --git a/vendor/github.com/Shopify/sarama/balance_strategy.go b/vendor/github.com/Shopify/sarama/balance_strategy.go new file mode 100644 index 00000000000..e78988d7181 --- /dev/null +++ b/vendor/github.com/Shopify/sarama/balance_strategy.go @@ -0,0 +1,129 @@ +package sarama + +import ( + "math" + "sort" +) + +// BalanceStrategyPlan is the results of any BalanceStrategy.Plan attempt. +// It contains an allocation of topic/partitions by memberID in the form of +// a `memberID -> topic -> partitions` map. +type BalanceStrategyPlan map[string]map[string][]int32 + +// Add assigns a topic with a number partitions to a member. +func (p BalanceStrategyPlan) Add(memberID, topic string, partitions ...int32) { + if len(partitions) == 0 { + return + } + if _, ok := p[memberID]; !ok { + p[memberID] = make(map[string][]int32, 1) + } + p[memberID][topic] = append(p[memberID][topic], partitions...) +} + +// -------------------------------------------------------------------- + +// BalanceStrategy is used to balance topics and partitions +// across memebers of a consumer group +type BalanceStrategy interface { + // Name uniquely identifies the strategy. + Name() string + + // Plan accepts a map of `memberID -> metadata` and a map of `topic -> partitions` + // and returns a distribution plan. + Plan(members map[string]ConsumerGroupMemberMetadata, topics map[string][]int32) (BalanceStrategyPlan, error) +} + +// -------------------------------------------------------------------- + +// BalanceStrategyRange is the default and assigns partitions as ranges to consumer group members. +// Example with one topic T with six partitions (0..5) and two members (M1, M2): +// M1: {T: [0, 1, 2]} +// M2: {T: [3, 4, 5]} +var BalanceStrategyRange = &balanceStrategy{ + name: "range", + coreFn: func(plan BalanceStrategyPlan, memberIDs []string, topic string, partitions []int32) { + step := float64(len(partitions)) / float64(len(memberIDs)) + + for i, memberID := range memberIDs { + pos := float64(i) + min := int(math.Floor(pos*step + 0.5)) + max := int(math.Floor((pos+1)*step + 0.5)) + plan.Add(memberID, topic, partitions[min:max]...) + } + }, +} + +// BalanceStrategyRoundRobin assigns partitions to members in alternating order. +// Example with topic T with six partitions (0..5) and two members (M1, M2): +// M1: {T: [0, 2, 4]} +// M2: {T: [1, 3, 5]} +var BalanceStrategyRoundRobin = &balanceStrategy{ + name: "roundrobin", + coreFn: func(plan BalanceStrategyPlan, memberIDs []string, topic string, partitions []int32) { + for i, part := range partitions { + memberID := memberIDs[i%len(memberIDs)] + plan.Add(memberID, topic, part) + } + }, +} + +// -------------------------------------------------------------------- + +type balanceStrategy struct { + name string + coreFn func(plan BalanceStrategyPlan, memberIDs []string, topic string, partitions []int32) +} + +// Name implements BalanceStrategy. +func (s *balanceStrategy) Name() string { return s.name } + +// Balance implements BalanceStrategy. +func (s *balanceStrategy) Plan(members map[string]ConsumerGroupMemberMetadata, topics map[string][]int32) (BalanceStrategyPlan, error) { + // Build members by topic map + mbt := make(map[string][]string) + for memberID, meta := range members { + for _, topic := range meta.Topics { + mbt[topic] = append(mbt[topic], memberID) + } + } + + // Sort members for each topic + for topic, memberIDs := range mbt { + sort.Sort(&balanceStrategySortable{ + topic: topic, + memberIDs: memberIDs, + }) + } + + // Assemble plan + plan := make(BalanceStrategyPlan, len(members)) + for topic, memberIDs := range mbt { + s.coreFn(plan, memberIDs, topic, topics[topic]) + } + return plan, nil +} + +type balanceStrategySortable struct { + topic string + memberIDs []string +} + +func (p balanceStrategySortable) Len() int { return len(p.memberIDs) } +func (p balanceStrategySortable) Swap(i, j int) { + p.memberIDs[i], p.memberIDs[j] = p.memberIDs[j], p.memberIDs[i] +} +func (p balanceStrategySortable) Less(i, j int) bool { + return balanceStrategyHashValue(p.topic, p.memberIDs[i]) < balanceStrategyHashValue(p.topic, p.memberIDs[j]) +} + +func balanceStrategyHashValue(vv ...string) uint32 { + h := uint32(2166136261) + for _, s := range vv { + for _, c := range s { + h ^= uint32(c) + h *= 16777619 + } + } + return h +} diff --git a/vendor/github.com/Shopify/sarama/broker.go b/vendor/github.com/Shopify/sarama/broker.go index 6430fd999fa..26f63d51d6d 100644 --- a/vendor/github.com/Shopify/sarama/broker.go +++ b/vendor/github.com/Shopify/sarama/broker.go @@ -86,6 +86,7 @@ func (b *Broker) Open(conf *Config) error { dialer := net.Dialer{ Timeout: conf.Net.DialTimeout, KeepAlive: conf.Net.KeepAlive, + LocalAddr: conf.Net.LocalAddr, } if conf.Net.TLS.Enable { diff --git a/vendor/github.com/Shopify/sarama/client.go b/vendor/github.com/Shopify/sarama/client.go index 019cb43735a..ad805346b4b 100644 --- a/vendor/github.com/Shopify/sarama/client.go +++ b/vendor/github.com/Shopify/sarama/client.go @@ -17,7 +17,7 @@ type Client interface { // altered after it has been created. Config() *Config - // Controller returns the cluster controller broker. + // Controller returns the cluster controller broker. Requires Kafka 0.10 or higher. Controller() (*Broker, error) // Brokers returns the current set of active brokers as retrieved from cluster metadata. @@ -100,10 +100,11 @@ type client struct { seedBrokers []*Broker deadSeeds []*Broker - controllerID int32 // cluster controller broker id - brokers map[int32]*Broker // maps broker ids to brokers - metadata map[string]map[int32]*PartitionMetadata // maps topics to partition ids to metadata - coordinators map[string]int32 // Maps consumer group names to coordinating broker IDs + controllerID int32 // cluster controller broker id + brokers map[int32]*Broker // maps broker ids to brokers + metadata map[string]map[int32]*PartitionMetadata // maps topics to partition ids to metadata + metadataTopics map[string]none // topics that need to collect metadata + coordinators map[string]int32 // Maps consumer group names to coordinating broker IDs // If the number of partitions is large, we can get some churn calling cachedPartitions, // so the result is cached. It is important to update this value whenever metadata is changed @@ -136,6 +137,7 @@ func NewClient(addrs []string, conf *Config) (Client, error) { closed: make(chan none), brokers: make(map[int32]*Broker), metadata: make(map[string]map[int32]*PartitionMetadata), + metadataTopics: make(map[string]none), cachedPartitionsResults: make(map[string][maxPartitionIndex][]int32), coordinators: make(map[string]int32), } @@ -207,6 +209,7 @@ func (client *client) Close() error { client.brokers = nil client.metadata = nil + client.metadataTopics = nil return nil } @@ -231,6 +234,22 @@ func (client *client) Topics() ([]string, error) { return ret, nil } +func (client *client) MetadataTopics() ([]string, error) { + if client.Closed() { + return nil, ErrClosedClient + } + + client.lock.RLock() + defer client.lock.RUnlock() + + ret := make([]string, 0, len(client.metadataTopics)) + for topic := range client.metadataTopics { + ret = append(ret, topic) + } + + return ret, nil +} + func (client *client) Partitions(topic string) ([]int32, error) { if client.Closed() { return nil, ErrClosedClient @@ -388,6 +407,10 @@ func (client *client) Controller() (*Broker, error) { return nil, ErrClosedClient } + if !client.conf.Version.IsAtLeast(V0_10_0_0) { + return nil, ErrUnsupportedVersion + } + controller := client.cachedController() if controller == nil { if err := client.refreshMetadata(); err != nil { @@ -645,7 +668,7 @@ func (client *client) refreshMetadata() error { topics := []string{} if !client.conf.Metadata.Full { - if specificTopics, err := client.Topics(); err != nil { + if specificTopics, err := client.MetadataTopics(); err != nil { return err } else if len(specificTopics) == 0 { return ErrNoTopicsToUpdateMetadata @@ -728,9 +751,16 @@ func (client *client) updateMetadata(data *MetadataResponse, allKnownMetaData bo if allKnownMetaData { client.metadata = make(map[string]map[int32]*PartitionMetadata) + client.metadataTopics = make(map[string]none) client.cachedPartitionsResults = make(map[string][maxPartitionIndex][]int32) } for _, topic := range data.Topics { + // topics must be added firstly to `metadataTopics` to guarantee that all + // requested topics must be recorded to keep them trackable for periodically + // metadata refresh. + if _, exists := client.metadataTopics[topic.Name]; !exists { + client.metadataTopics[topic.Name] = none{} + } delete(client.metadata, topic.Name) delete(client.cachedPartitionsResults, topic.Name) diff --git a/vendor/github.com/Shopify/sarama/config.go b/vendor/github.com/Shopify/sarama/config.go index a564b5c23e4..faf11e83839 100644 --- a/vendor/github.com/Shopify/sarama/config.go +++ b/vendor/github.com/Shopify/sarama/config.go @@ -5,6 +5,7 @@ import ( "crypto/tls" "fmt" "io/ioutil" + "net" "regexp" "time" @@ -17,6 +18,13 @@ var validID = regexp.MustCompile(`\A[A-Za-z0-9._-]+\z`) // Config is used to pass multiple configuration options to Sarama's constructors. type Config struct { + // Admin is the namespace for ClusterAdmin properties used by the administrative Kafka client. + Admin struct { + // The maximum duration the administrative Kafka client will wait for ClusterAdmin operations, + // including topics, brokers, configurations and ACLs (defaults to 3 seconds). + Timeout time.Duration + } + // Net is the namespace for network-level properties used by the Broker, and // shared by the Client/Producer/Consumer. Net struct { @@ -58,6 +66,12 @@ type Config struct { // KeepAlive specifies the keep-alive period for an active network connection. // If zero, keep-alives are disabled. (default is 0: disabled). KeepAlive time.Duration + + // LocalAddr is the local address to use when dialing an + // address. The address must be of a compatible type for the + // network being dialed. + // If nil, a local address is automatically chosen. + LocalAddr net.Addr } // Metadata is the namespace for metadata management properties used by the @@ -159,14 +173,55 @@ type Config struct { // Consumer is the namespace for configuration related to consuming messages, // used by the Consumer. - // - // Note that Sarama's Consumer type does not currently support automatic - // consumer-group rebalancing and offset tracking. For Zookeeper-based - // tracking (Kafka 0.8.2 and earlier), the https://github.com/wvanbergen/kafka - // library builds on Sarama to add this support. For Kafka-based tracking - // (Kafka 0.9 and later), the https://github.com/bsm/sarama-cluster library - // builds on Sarama to add this support. Consumer struct { + + // Group is the namespace for configuring consumer group. + Group struct { + Session struct { + // The timeout used to detect consumer failures when using Kafka's group management facility. + // The consumer sends periodic heartbeats to indicate its liveness to the broker. + // If no heartbeats are received by the broker before the expiration of this session timeout, + // then the broker will remove this consumer from the group and initiate a rebalance. + // Note that the value must be in the allowable range as configured in the broker configuration + // by `group.min.session.timeout.ms` and `group.max.session.timeout.ms` (default 10s) + Timeout time.Duration + } + Heartbeat struct { + // The expected time between heartbeats to the consumer coordinator when using Kafka's group + // management facilities. Heartbeats are used to ensure that the consumer's session stays active and + // to facilitate rebalancing when new consumers join or leave the group. + // The value must be set lower than Consumer.Group.Session.Timeout, but typically should be set no + // higher than 1/3 of that value. + // It can be adjusted even lower to control the expected time for normal rebalances (default 3s) + Interval time.Duration + } + Rebalance struct { + // Strategy for allocating topic partitions to members (default BalanceStrategyRange) + Strategy BalanceStrategy + // The maximum allowed time for each worker to join the group once a rebalance has begun. + // This is basically a limit on the amount of time needed for all tasks to flush any pending + // data and commit offsets. If the timeout is exceeded, then the worker will be removed from + // the group, which will cause offset commit failures (default 60s). + Timeout time.Duration + + Retry struct { + // When a new consumer joins a consumer group the set of consumers attempt to "rebalance" + // the load to assign partitions to each consumer. If the set of consumers changes while + // this assignment is taking place the rebalance will fail and retry. This setting controls + // the maximum number of attempts before giving up (default 4). + Max int + // Backoff time between retries during rebalance (default 2s) + Backoff time.Duration + } + } + Member struct { + // Custom metadata to include when joining the group. The user data for all joined members + // can be retrieved by sending a DescribeGroupRequest to the broker that is the + // coordinator for the group. + UserData []byte + } + } + Retry struct { // How long to wait after a failing to read from a partition before // trying again (default 2s). @@ -248,6 +303,12 @@ type Config struct { // broker version 0.9.0 or later. // (default is 0: disabled). Retention time.Duration + + Retry struct { + // The total number of times to retry failing commit + // requests during OffsetManager shutdown (default 3). + Max int + } } } @@ -279,6 +340,8 @@ type Config struct { func NewConfig() *Config { c := &Config{} + c.Admin.Timeout = 3 * time.Second + c.Net.MaxOpenRequests = 5 c.Net.DialTimeout = 30 * time.Second c.Net.ReadTimeout = 30 * time.Second @@ -307,6 +370,14 @@ func NewConfig() *Config { c.Consumer.Return.Errors = false c.Consumer.Offsets.CommitInterval = 1 * time.Second c.Consumer.Offsets.Initial = OffsetNewest + c.Consumer.Offsets.Retry.Max = 3 + + c.Consumer.Group.Session.Timeout = 10 * time.Second + c.Consumer.Group.Heartbeat.Interval = 3 * time.Second + c.Consumer.Group.Rebalance.Strategy = BalanceStrategyRange + c.Consumer.Group.Rebalance.Timeout = 60 * time.Second + c.Consumer.Group.Rebalance.Retry.Max = 4 + c.Consumer.Group.Rebalance.Retry.Backoff = 2 * time.Second c.ClientID = defaultClientID c.ChannelBufferSize = 256 @@ -355,6 +426,15 @@ func (c *Config) Validate() error { if c.Consumer.Offsets.Retention%time.Millisecond != 0 { Logger.Println("Consumer.Offsets.Retention only supports millisecond precision; nanoseconds will be truncated.") } + if c.Consumer.Group.Session.Timeout%time.Millisecond != 0 { + Logger.Println("Consumer.Group.Session.Timeout only supports millisecond precision; nanoseconds will be truncated.") + } + if c.Consumer.Group.Heartbeat.Interval%time.Millisecond != 0 { + Logger.Println("Consumer.Group.Heartbeat.Interval only supports millisecond precision; nanoseconds will be truncated.") + } + if c.Consumer.Group.Rebalance.Timeout%time.Millisecond != 0 { + Logger.Println("Consumer.Group.Rebalance.Timeout only supports millisecond precision; nanoseconds will be truncated.") + } if c.ClientID == defaultClientID { Logger.Println("ClientID is the default of 'sarama', you should consider setting it to something application-specific.") } @@ -377,6 +457,12 @@ func (c *Config) Validate() error { return ConfigurationError("Net.SASL.Password must not be empty when SASL is enabled") } + // validate the Admin values + switch { + case c.Admin.Timeout <= 0: + return ConfigurationError("Admin.Timeout must be > 0") + } + // validate the Metadata values switch { case c.Metadata.Retry.Max < 0: @@ -443,7 +529,26 @@ func (c *Config) Validate() error { return ConfigurationError("Consumer.Offsets.CommitInterval must be > 0") case c.Consumer.Offsets.Initial != OffsetOldest && c.Consumer.Offsets.Initial != OffsetNewest: return ConfigurationError("Consumer.Offsets.Initial must be OffsetOldest or OffsetNewest") + case c.Consumer.Offsets.Retry.Max < 0: + return ConfigurationError("Consumer.Offsets.Retry.Max must be >= 0") + } + // validate the Consumer Group values + switch { + case c.Consumer.Group.Session.Timeout <= 2*time.Millisecond: + return ConfigurationError("Consumer.Group.Session.Timeout must be >= 2ms") + case c.Consumer.Group.Heartbeat.Interval < 1*time.Millisecond: + return ConfigurationError("Consumer.Group.Heartbeat.Interval must be >= 1ms") + case c.Consumer.Group.Heartbeat.Interval >= c.Consumer.Group.Session.Timeout: + return ConfigurationError("Consumer.Group.Heartbeat.Interval must be < Consumer.Group.Session.Timeout") + case c.Consumer.Group.Rebalance.Strategy == nil: + return ConfigurationError("Consumer.Group.Rebalance.Strategy must not be empty") + case c.Consumer.Group.Rebalance.Timeout <= time.Millisecond: + return ConfigurationError("Consumer.Group.Rebalance.Timeout must be >= 1ms") + case c.Consumer.Group.Rebalance.Retry.Max < 0: + return ConfigurationError("Consumer.Group.Rebalance.Retry.Max must be >= 0") + case c.Consumer.Group.Rebalance.Retry.Backoff < 0: + return ConfigurationError("Consumer.Group.Rebalance.Retry.Backoff must be >= 0") } // validate misc shared values diff --git a/vendor/github.com/Shopify/sarama/consumer_group.go b/vendor/github.com/Shopify/sarama/consumer_group.go new file mode 100644 index 00000000000..33a231477f9 --- /dev/null +++ b/vendor/github.com/Shopify/sarama/consumer_group.go @@ -0,0 +1,774 @@ +package sarama + +import ( + "context" + "errors" + "fmt" + "sort" + "sync" + "time" +) + +// ErrClosedConsumerGroup is the error returned when a method is called on a consumer group that has been closed. +var ErrClosedConsumerGroup = errors.New("kafka: tried to use a consumer group that was closed") + +// ConsumerGroup is responsible for dividing up processing of topics and partitions +// over a collection of processes (the members of the consumer group). +type ConsumerGroup interface { + // Consume joins a cluster of consumers for a given list of topics and + // starts a blocking ConsumerGroupSession through the ConsumerGroupHandler. + // + // The life-cycle of a session is represented by the following steps: + // + // 1. The consumers join the group (as explained in https://kafka.apache.org/documentation/#intro_consumers) + // and is assigned their "fair share" of partitions, aka 'claims'. + // 2. Before processing starts, the handler's Setup() hook is called to notify the user + // of the claims and allow any necessary preparation or alteration of state. + // 3. For each of the assigned claims the handler's ConsumeClaim() function is then called + // in a separate goroutine which requires it to be thread-safe. Any state must be carefully protected + // from concurrent reads/writes. + // 4. The session will persist until one of the ConsumeClaim() functions exits. This can be either when the + // parent context is cancelled or when a server-side rebalance cycle is initiated. + // 5. Once all the ConsumeClaim() loops have exited, the handler's Cleanup() hook is called + // to allow the user to perform any final tasks before a rebalance. + // 6. Finally, marked offsets are committed one last time before claims are released. + // + // Please note, that once a relance is triggered, sessions must be completed within + // Config.Consumer.Group.Rebalance.Timeout. This means that ConsumeClaim() functions must exit + // as quickly as possible to allow time for Cleanup() and the final offset commit. If the timeout + // is exceeded, the consumer will be removed from the group by Kafka, which will cause offset + // commit failures. + Consume(ctx context.Context, topics []string, handler ConsumerGroupHandler) error + + // Errors returns a read channel of errors that occurred during the consumer life-cycle. + // By default, errors are logged and not returned over this channel. + // If you want to implement any custom error handling, set your config's + // Consumer.Return.Errors setting to true, and read from this channel. + Errors() <-chan error + + // Close stops the ConsumerGroup and detaches any running sessions. It is required to call + // this function before the object passes out of scope, as it will otherwise leak memory. + Close() error +} + +type consumerGroup struct { + client Client + ownClient bool + + config *Config + consumer Consumer + groupID string + memberID string + errors chan error + + lock sync.Mutex + closed chan none + closeOnce sync.Once +} + +// NewConsumerGroup creates a new consumer group the given broker addresses and configuration. +func NewConsumerGroup(addrs []string, groupID string, config *Config) (ConsumerGroup, error) { + client, err := NewClient(addrs, config) + if err != nil { + return nil, err + } + + c, err := NewConsumerGroupFromClient(groupID, client) + if err != nil { + _ = client.Close() + return nil, err + } + + c.(*consumerGroup).ownClient = true + return c, nil +} + +// NewConsumerFromClient creates a new consumer group using the given client. It is still +// necessary to call Close() on the underlying client when shutting down this consumer. +// PLEASE NOTE: consumer groups can only re-use but not share clients. +func NewConsumerGroupFromClient(groupID string, client Client) (ConsumerGroup, error) { + config := client.Config() + if !config.Version.IsAtLeast(V0_10_2_0) { + return nil, ConfigurationError("consumer groups require Version to be >= V0_10_2_0") + } + + consumer, err := NewConsumerFromClient(client) + if err != nil { + return nil, err + } + + return &consumerGroup{ + client: client, + consumer: consumer, + config: config, + groupID: groupID, + errors: make(chan error, config.ChannelBufferSize), + closed: make(chan none), + }, nil +} + +// Errors implements ConsumerGroup. +func (c *consumerGroup) Errors() <-chan error { return c.errors } + +// Close implements ConsumerGroup. +func (c *consumerGroup) Close() (err error) { + c.closeOnce.Do(func() { + close(c.closed) + + c.lock.Lock() + defer c.lock.Unlock() + + // leave group + if e := c.leave(); e != nil { + err = e + } + + // drain errors + go func() { + close(c.errors) + }() + for e := range c.errors { + err = e + } + + if c.ownClient { + if e := c.client.Close(); e != nil { + err = e + } + } + }) + return +} + +// Consume implements ConsumerGroup. +func (c *consumerGroup) Consume(ctx context.Context, topics []string, handler ConsumerGroupHandler) error { + // Ensure group is not closed + select { + case <-c.closed: + return ErrClosedConsumerGroup + default: + } + + c.lock.Lock() + defer c.lock.Unlock() + + // Quick exit when no topics are provided + if len(topics) == 0 { + return fmt.Errorf("no topics provided") + } + + // Refresh metadata for requested topics + if err := c.client.RefreshMetadata(topics...); err != nil { + return err + } + + // Get coordinator + coordinator, err := c.client.Coordinator(c.groupID) + if err != nil { + return err + } + + // Init session + sess, err := c.newSession(ctx, coordinator, topics, handler, c.config.Consumer.Group.Rebalance.Retry.Max) + if err == ErrClosedClient { + return ErrClosedConsumerGroup + } else if err != nil { + return err + } + + // Wait for session exit signal + <-sess.ctx.Done() + + // Gracefully release session claims + return sess.release(true) +} + +func (c *consumerGroup) newSession(ctx context.Context, coordinator *Broker, topics []string, handler ConsumerGroupHandler, retries int) (*consumerGroupSession, error) { + // Join consumer group + join, err := c.joinGroupRequest(coordinator, topics) + if err != nil { + _ = coordinator.Close() + return nil, err + } + switch join.Err { + case ErrNoError: + c.memberID = join.MemberId + case ErrUnknownMemberId, ErrIllegalGeneration: // reset member ID and retry immediately + c.memberID = "" + return c.newSession(ctx, coordinator, topics, handler, retries) + case ErrRebalanceInProgress: // retry after backoff + if retries <= 0 { + return nil, join.Err + } + + select { + case <-c.closed: + return nil, ErrClosedConsumerGroup + case <-time.After(c.config.Consumer.Group.Rebalance.Retry.Backoff): + } + + return c.newSession(ctx, coordinator, topics, handler, retries-1) + default: + return nil, join.Err + } + + // Prepare distribution plan if we joined as the leader + var plan BalanceStrategyPlan + if join.LeaderId == join.MemberId { + members, err := join.GetMembers() + if err != nil { + return nil, err + } + + plan, err = c.balance(members) + if err != nil { + return nil, err + } + } + + // Sync consumer group + sync, err := c.syncGroupRequest(coordinator, plan, join.GenerationId) + if err != nil { + _ = coordinator.Close() + return nil, err + } + switch sync.Err { + case ErrNoError: + case ErrUnknownMemberId, ErrIllegalGeneration: // reset member ID and retry immediately + c.memberID = "" + return c.newSession(ctx, coordinator, topics, handler, retries) + case ErrRebalanceInProgress: // retry after backoff + if retries <= 0 { + return nil, sync.Err + } + + select { + case <-c.closed: + return nil, ErrClosedConsumerGroup + case <-time.After(c.config.Consumer.Group.Rebalance.Retry.Backoff): + } + + return c.newSession(ctx, coordinator, topics, handler, retries-1) + default: + return nil, sync.Err + } + + // Retrieve and sort claims + var claims map[string][]int32 + if len(sync.MemberAssignment) > 0 { + members, err := sync.GetMemberAssignment() + if err != nil { + return nil, err + } + claims = members.Topics + + for _, partitions := range claims { + sort.Sort(int32Slice(partitions)) + } + } + + return newConsumerGroupSession(c, ctx, claims, join.MemberId, join.GenerationId, handler) +} + +func (c *consumerGroup) joinGroupRequest(coordinator *Broker, topics []string) (*JoinGroupResponse, error) { + req := &JoinGroupRequest{ + GroupId: c.groupID, + MemberId: c.memberID, + SessionTimeout: int32(c.config.Consumer.Group.Session.Timeout / time.Millisecond), + ProtocolType: "consumer", + } + if c.config.Version.IsAtLeast(V0_10_1_0) { + req.Version = 1 + req.RebalanceTimeout = int32(c.config.Consumer.Group.Rebalance.Timeout / time.Millisecond) + } + + meta := &ConsumerGroupMemberMetadata{ + Topics: topics, + UserData: c.config.Consumer.Group.Member.UserData, + } + strategy := c.config.Consumer.Group.Rebalance.Strategy + if err := req.AddGroupProtocolMetadata(strategy.Name(), meta); err != nil { + return nil, err + } + + return coordinator.JoinGroup(req) +} + +func (c *consumerGroup) syncGroupRequest(coordinator *Broker, plan BalanceStrategyPlan, generationID int32) (*SyncGroupResponse, error) { + req := &SyncGroupRequest{ + GroupId: c.groupID, + MemberId: c.memberID, + GenerationId: generationID, + } + for memberID, topics := range plan { + err := req.AddGroupAssignmentMember(memberID, &ConsumerGroupMemberAssignment{ + Topics: topics, + }) + if err != nil { + return nil, err + } + } + return coordinator.SyncGroup(req) +} + +func (c *consumerGroup) heartbeatRequest(coordinator *Broker, memberID string, generationID int32) (*HeartbeatResponse, error) { + req := &HeartbeatRequest{ + GroupId: c.groupID, + MemberId: memberID, + GenerationId: generationID, + } + + return coordinator.Heartbeat(req) +} + +func (c *consumerGroup) balance(members map[string]ConsumerGroupMemberMetadata) (BalanceStrategyPlan, error) { + topics := make(map[string][]int32) + for _, meta := range members { + for _, topic := range meta.Topics { + topics[topic] = nil + } + } + + for topic := range topics { + partitions, err := c.client.Partitions(topic) + if err != nil { + return nil, err + } + topics[topic] = partitions + } + + strategy := c.config.Consumer.Group.Rebalance.Strategy + return strategy.Plan(members, topics) +} + +// Leaves the cluster, called by Close, protected by lock. +func (c *consumerGroup) leave() error { + if c.memberID == "" { + return nil + } + + coordinator, err := c.client.Coordinator(c.groupID) + if err != nil { + return err + } + + resp, err := coordinator.LeaveGroup(&LeaveGroupRequest{ + GroupId: c.groupID, + MemberId: c.memberID, + }) + if err != nil { + _ = coordinator.Close() + return err + } + + // Unset memberID + c.memberID = "" + + // Check response + switch resp.Err { + case ErrRebalanceInProgress, ErrUnknownMemberId, ErrNoError: + return nil + default: + return resp.Err + } +} + +func (c *consumerGroup) handleError(err error, topic string, partition int32) { + select { + case <-c.closed: + return + default: + } + + if _, ok := err.(*ConsumerError); !ok && topic != "" && partition > -1 { + err = &ConsumerError{ + Topic: topic, + Partition: partition, + Err: err, + } + } + + if c.config.Consumer.Return.Errors { + select { + case c.errors <- err: + default: + } + } else { + Logger.Println(err) + } +} + +// -------------------------------------------------------------------- + +// ConsumerGroupSession represents a consumer group member session. +type ConsumerGroupSession interface { + // Claims returns information about the claimed partitions by topic. + Claims() map[string][]int32 + + // MemberID returns the cluster member ID. + MemberID() string + + // GenerationID returns the current generation ID. + GenerationID() int32 + + // MarkOffset marks the provided offset, alongside a metadata string + // that represents the state of the partition consumer at that point in time. The + // metadata string can be used by another consumer to restore that state, so it + // can resume consumption. + // + // To follow upstream conventions, you are expected to mark the offset of the + // next message to read, not the last message read. Thus, when calling `MarkOffset` + // you should typically add one to the offset of the last consumed message. + // + // Note: calling MarkOffset does not necessarily commit the offset to the backend + // store immediately for efficiency reasons, and it may never be committed if + // your application crashes. This means that you may end up processing the same + // message twice, and your processing should ideally be idempotent. + MarkOffset(topic string, partition int32, offset int64, metadata string) + + // ResetOffset resets to the provided offset, alongside a metadata string that + // represents the state of the partition consumer at that point in time. Reset + // acts as a counterpart to MarkOffset, the difference being that it allows to + // reset an offset to an earlier or smaller value, where MarkOffset only + // allows incrementing the offset. cf MarkOffset for more details. + ResetOffset(topic string, partition int32, offset int64, metadata string) + + // MarkMessage marks a message as consumed. + MarkMessage(msg *ConsumerMessage, metadata string) + + // Context returns the session context. + Context() context.Context +} + +type consumerGroupSession struct { + parent *consumerGroup + memberID string + generationID int32 + handler ConsumerGroupHandler + + claims map[string][]int32 + offsets *offsetManager + ctx context.Context + cancel func() + + waitGroup sync.WaitGroup + releaseOnce sync.Once + hbDying, hbDead chan none +} + +func newConsumerGroupSession(parent *consumerGroup, ctx context.Context, claims map[string][]int32, memberID string, generationID int32, handler ConsumerGroupHandler) (*consumerGroupSession, error) { + // init offset manager + offsets, err := newOffsetManagerFromClient(parent.groupID, memberID, generationID, parent.client) + if err != nil { + return nil, err + } + + // init context + ctx, cancel := context.WithCancel(ctx) + + // init session + sess := &consumerGroupSession{ + parent: parent, + memberID: memberID, + generationID: generationID, + handler: handler, + offsets: offsets, + claims: claims, + ctx: ctx, + cancel: cancel, + hbDying: make(chan none), + hbDead: make(chan none), + } + + // start heartbeat loop + go sess.heartbeatLoop() + + // create a POM for each claim + for topic, partitions := range claims { + for _, partition := range partitions { + pom, err := offsets.ManagePartition(topic, partition) + if err != nil { + _ = sess.release(false) + return nil, err + } + + // handle POM errors + go func(topic string, partition int32) { + for err := range pom.Errors() { + sess.parent.handleError(err, topic, partition) + } + }(topic, partition) + } + } + + // perform setup + if err := handler.Setup(sess); err != nil { + _ = sess.release(true) + return nil, err + } + + // start consuming + for topic, partitions := range claims { + for _, partition := range partitions { + sess.waitGroup.Add(1) + + go func(topic string, partition int32) { + defer sess.waitGroup.Done() + + // cancel the as session as soon as the first + // goroutine exits + defer sess.cancel() + + // consume a single topic/partition, blocking + sess.consume(topic, partition) + }(topic, partition) + } + } + return sess, nil +} + +func (s *consumerGroupSession) Claims() map[string][]int32 { return s.claims } +func (s *consumerGroupSession) MemberID() string { return s.memberID } +func (s *consumerGroupSession) GenerationID() int32 { return s.generationID } + +func (s *consumerGroupSession) MarkOffset(topic string, partition int32, offset int64, metadata string) { + if pom := s.offsets.findPOM(topic, partition); pom != nil { + pom.MarkOffset(offset, metadata) + } +} + +func (s *consumerGroupSession) ResetOffset(topic string, partition int32, offset int64, metadata string) { + if pom := s.offsets.findPOM(topic, partition); pom != nil { + pom.ResetOffset(offset, metadata) + } +} + +func (s *consumerGroupSession) MarkMessage(msg *ConsumerMessage, metadata string) { + s.MarkOffset(msg.Topic, msg.Partition, msg.Offset+1, metadata) +} + +func (s *consumerGroupSession) Context() context.Context { + return s.ctx +} + +func (s *consumerGroupSession) consume(topic string, partition int32) { + // quick exit if rebalance is due + select { + case <-s.ctx.Done(): + return + case <-s.parent.closed: + return + default: + } + + // get next offset + offset := s.parent.config.Consumer.Offsets.Initial + if pom := s.offsets.findPOM(topic, partition); pom != nil { + offset, _ = pom.NextOffset() + } + + // create new claim + claim, err := newConsumerGroupClaim(s, topic, partition, offset) + if err != nil { + s.parent.handleError(err, topic, partition) + return + } + + // handle errors + go func() { + for err := range claim.Errors() { + s.parent.handleError(err, topic, partition) + } + }() + + // trigger close when session is done + go func() { + select { + case <-s.ctx.Done(): + case <-s.parent.closed: + } + claim.AsyncClose() + }() + + // start processing + if err := s.handler.ConsumeClaim(s, claim); err != nil { + s.parent.handleError(err, topic, partition) + } + + // ensure consumer is clased & drained + claim.AsyncClose() + for _, err := range claim.waitClosed() { + s.parent.handleError(err, topic, partition) + } +} + +func (s *consumerGroupSession) release(withCleanup bool) (err error) { + // signal release, stop heartbeat + s.cancel() + + // wait for consumers to exit + s.waitGroup.Wait() + + // perform release + s.releaseOnce.Do(func() { + if withCleanup { + if e := s.handler.Cleanup(s); e != nil { + s.parent.handleError(err, "", -1) + err = e + } + } + + if e := s.offsets.Close(); e != nil { + err = e + } + + close(s.hbDying) + <-s.hbDead + }) + + return +} + +func (s *consumerGroupSession) heartbeatLoop() { + defer close(s.hbDead) + defer s.cancel() // trigger the end of the session on exit + + pause := time.NewTicker(s.parent.config.Consumer.Group.Heartbeat.Interval) + defer pause.Stop() + + retries := s.parent.config.Metadata.Retry.Max + for { + coordinator, err := s.parent.client.Coordinator(s.parent.groupID) + if err != nil { + if retries <= 0 { + s.parent.handleError(err, "", -1) + return + } + + select { + case <-s.hbDying: + return + case <-time.After(s.parent.config.Metadata.Retry.Backoff): + retries-- + } + continue + } + + resp, err := s.parent.heartbeatRequest(coordinator, s.memberID, s.generationID) + if err != nil { + _ = coordinator.Close() + retries-- + continue + } + + switch resp.Err { + case ErrNoError: + retries = s.parent.config.Metadata.Retry.Max + case ErrRebalanceInProgress, ErrUnknownMemberId, ErrIllegalGeneration: + return + default: + s.parent.handleError(err, "", -1) + return + } + + select { + case <-pause.C: + case <-s.hbDying: + return + } + } +} + +// -------------------------------------------------------------------- + +// ConsumerGroupHandler instances are used to handle individual topic/partition claims. +// It also provides hooks for your consumer group session life-cycle and allow you to +// trigger logic before or after the consume loop(s). +// +// PLEASE NOTE that handlers are likely be called from several goroutines concurrently, +// ensure that all state is safely protected against race conditions. +type ConsumerGroupHandler interface { + // Setup is run at the beginning of a new session, before ConsumeClaim. + Setup(ConsumerGroupSession) error + + // Cleanup is run at the end of a session, once all ConsumeClaim goroutines have exites + // but before the offsets are committed for the very last time. + Cleanup(ConsumerGroupSession) error + + // ConsumeClaim must start a consumer loop of ConsumerGroupClaim's Messages(). + // Once the Messages() channel is closed, the Handler must finish its processing + // loop and exit. + ConsumeClaim(ConsumerGroupSession, ConsumerGroupClaim) error +} + +// ConsumerGroupClaim processes Kafka messages from a given topic and partition within a consumer group. +type ConsumerGroupClaim interface { + // Topic returns the consumed topic name. + Topic() string + + // Partition returns the consumed partition. + Partition() int32 + + // InitialOffset returns the initial offset that was used as a starting point for this claim. + InitialOffset() int64 + + // HighWaterMarkOffset returns the high water mark offset of the partition, + // i.e. the offset that will be used for the next message that will be produced. + // You can use this to determine how far behind the processing is. + HighWaterMarkOffset() int64 + + // Messages returns the read channel for the messages that are returned by + // the broker. The messages channel will be closed when a new rebalance cycle + // is due. You must finish processing and mark offsets within + // Config.Consumer.Group.Session.Timeout before the topic/partition is eventually + // re-assigned to another group member. + Messages() <-chan *ConsumerMessage +} + +type consumerGroupClaim struct { + topic string + partition int32 + offset int64 + PartitionConsumer +} + +func newConsumerGroupClaim(sess *consumerGroupSession, topic string, partition int32, offset int64) (*consumerGroupClaim, error) { + pcm, err := sess.parent.consumer.ConsumePartition(topic, partition, offset) + if err == ErrOffsetOutOfRange { + offset = sess.parent.config.Consumer.Offsets.Initial + pcm, err = sess.parent.consumer.ConsumePartition(topic, partition, offset) + } + if err != nil { + return nil, err + } + + go func() { + for err := range pcm.Errors() { + sess.parent.handleError(err, topic, partition) + } + }() + + return &consumerGroupClaim{ + topic: topic, + partition: partition, + offset: offset, + PartitionConsumer: pcm, + }, nil +} + +func (c *consumerGroupClaim) Topic() string { return c.topic } +func (c *consumerGroupClaim) Partition() int32 { return c.partition } +func (c *consumerGroupClaim) InitialOffset() int64 { return c.offset } + +// Drains messages and errors, ensures the claim is fully closed. +func (c *consumerGroupClaim) waitClosed() (errs ConsumerErrors) { + go func() { + for range c.Messages() { + } + }() + + for err := range c.Errors() { + errs = append(errs, err) + } + return +} diff --git a/vendor/github.com/Shopify/sarama/fetch_response.go b/vendor/github.com/Shopify/sarama/fetch_response.go index ae91bb9eb09..dade1c47dac 100644 --- a/vendor/github.com/Shopify/sarama/fetch_response.go +++ b/vendor/github.com/Shopify/sarama/fetch_response.go @@ -104,15 +104,26 @@ func (b *FetchResponseBlock) decode(pd packetDecoder, version int16) (err error) return err } - // If we have at least one full records, we skip incomplete ones - if partial && len(b.RecordsSet) > 0 { - break + n, err := records.numRecords() + if err != nil { + return err } - b.RecordsSet = append(b.RecordsSet, records) + if n > 0 || (partial && len(b.RecordsSet) == 0) { + b.RecordsSet = append(b.RecordsSet, records) + + if b.Records == nil { + b.Records = records + } + } - if b.Records == nil { - b.Records = records + overflow, err := records.isOverflow() + if err != nil { + return err + } + + if partial || overflow { + break } } diff --git a/vendor/github.com/Shopify/sarama/length_field.go b/vendor/github.com/Shopify/sarama/length_field.go index 576b1a6f6f8..da199a70a0e 100644 --- a/vendor/github.com/Shopify/sarama/length_field.go +++ b/vendor/github.com/Shopify/sarama/length_field.go @@ -5,6 +5,19 @@ import "encoding/binary" // LengthField implements the PushEncoder and PushDecoder interfaces for calculating 4-byte lengths. type lengthField struct { startOffset int + length int32 +} + +func (l *lengthField) decode(pd packetDecoder) error { + var err error + l.length, err = pd.getInt32() + if err != nil { + return err + } + if l.length > int32(pd.remaining()) { + return ErrInsufficientData + } + return nil } func (l *lengthField) saveOffset(in int) { @@ -21,7 +34,7 @@ func (l *lengthField) run(curOffset int, buf []byte) error { } func (l *lengthField) check(curOffset int, buf []byte) error { - if uint32(curOffset-l.startOffset-4) != binary.BigEndian.Uint32(buf[l.startOffset:]) { + if int32(curOffset-l.startOffset-4) != l.length { return PacketDecodingError{"length field invalid"} } diff --git a/vendor/github.com/Shopify/sarama/message_set.go b/vendor/github.com/Shopify/sarama/message_set.go index 27db52fdf1f..600c7c4dfb7 100644 --- a/vendor/github.com/Shopify/sarama/message_set.go +++ b/vendor/github.com/Shopify/sarama/message_set.go @@ -47,6 +47,7 @@ func (msb *MessageBlock) decode(pd packetDecoder) (err error) { type MessageSet struct { PartialTrailingMessage bool // whether the set on the wire contained an incomplete trailing MessageBlock + OverflowMessage bool // whether the set on the wire contained an overflow message Messages []*MessageBlock } @@ -85,7 +86,12 @@ func (ms *MessageSet) decode(pd packetDecoder) (err error) { case ErrInsufficientData: // As an optimization the server is allowed to return a partial message at the // end of the message set. Clients should handle this case. So we just ignore such things. - ms.PartialTrailingMessage = true + if msb.Offset == -1 { + // This is an overflow message caused by chunked down conversion + ms.OverflowMessage = true + } else { + ms.PartialTrailingMessage = true + } return nil default: return err diff --git a/vendor/github.com/Shopify/sarama/metadata_request.go b/vendor/github.com/Shopify/sarama/metadata_request.go index 48adfa28cb9..17dc4289a3a 100644 --- a/vendor/github.com/Shopify/sarama/metadata_request.go +++ b/vendor/github.com/Shopify/sarama/metadata_request.go @@ -10,7 +10,7 @@ func (r *MetadataRequest) encode(pe packetEncoder) error { if r.Version < 0 || r.Version > 5 { return PacketEncodingError{"invalid or unsupported MetadataRequest version field"} } - if r.Version == 0 || r.Topics != nil || len(r.Topics) > 0 { + if r.Version == 0 || len(r.Topics) > 0 { err := pe.putArrayLength(len(r.Topics)) if err != nil { return err diff --git a/vendor/github.com/Shopify/sarama/metadata_response.go b/vendor/github.com/Shopify/sarama/metadata_response.go index bf8a67bbc52..c402d05fa37 100644 --- a/vendor/github.com/Shopify/sarama/metadata_response.go +++ b/vendor/github.com/Shopify/sarama/metadata_response.go @@ -207,6 +207,10 @@ func (r *MetadataResponse) decode(pd packetDecoder, version int16) (err error) { } func (r *MetadataResponse) encode(pe packetEncoder) error { + if r.Version >= 3 { + pe.putInt32(r.ThrottleTimeMs) + } + err := pe.putArrayLength(len(r.Brokers)) if err != nil { return err @@ -218,6 +222,13 @@ func (r *MetadataResponse) encode(pe packetEncoder) error { } } + if r.Version >= 2 { + err := pe.putNullableString(r.ClusterID) + if err != nil { + return err + } + } + if r.Version >= 1 { pe.putInt32(r.ControllerID) } diff --git a/vendor/github.com/Shopify/sarama/offset_manager.go b/vendor/github.com/Shopify/sarama/offset_manager.go index 6c01f959e99..8ea857f8351 100644 --- a/vendor/github.com/Shopify/sarama/offset_manager.go +++ b/vendor/github.com/Shopify/sarama/offset_manager.go @@ -25,27 +25,49 @@ type offsetManager struct { client Client conf *Config group string + ticker *time.Ticker - lock sync.Mutex - poms map[string]map[int32]*partitionOffsetManager - boms map[*Broker]*brokerOffsetManager + memberID string + generation int32 + + broker *Broker + brokerLock sync.RWMutex + + poms map[string]map[int32]*partitionOffsetManager + pomsLock sync.RWMutex + + closeOnce sync.Once + closing chan none + closed chan none } // NewOffsetManagerFromClient creates a new OffsetManager from the given client. // It is still necessary to call Close() on the underlying client when finished with the partition manager. func NewOffsetManagerFromClient(group string, client Client) (OffsetManager, error) { + return newOffsetManagerFromClient(group, "", GroupGenerationUndefined, client) +} + +func newOffsetManagerFromClient(group, memberID string, generation int32, client Client) (*offsetManager, error) { // Check that we are not dealing with a closed Client before processing any other arguments if client.Closed() { return nil, ErrClosedClient } + conf := client.Config() om := &offsetManager{ client: client, - conf: client.Config(), + conf: conf, group: group, + ticker: time.NewTicker(conf.Consumer.Offsets.CommitInterval), poms: make(map[string]map[int32]*partitionOffsetManager), - boms: make(map[*Broker]*brokerOffsetManager), + + memberID: memberID, + generation: generation, + + closing: make(chan none), + closed: make(chan none), } + go withRecover(om.mainLoop) return om, nil } @@ -56,8 +78,8 @@ func (om *offsetManager) ManagePartition(topic string, partition int32) (Partiti return nil, err } - om.lock.Lock() - defer om.lock.Unlock() + om.pomsLock.Lock() + defer om.pomsLock.Unlock() topicManagers := om.poms[topic] if topicManagers == nil { @@ -74,53 +96,307 @@ func (om *offsetManager) ManagePartition(topic string, partition int32) (Partiti } func (om *offsetManager) Close() error { + om.closeOnce.Do(func() { + // exit the mainLoop + close(om.closing) + <-om.closed + + // mark all POMs as closed + om.asyncClosePOMs() + + // flush one last time + for attempt := 0; attempt <= om.conf.Consumer.Offsets.Retry.Max; attempt++ { + om.flushToBroker() + if om.releasePOMs(false) == 0 { + break + } + } + + om.releasePOMs(true) + om.brokerLock.Lock() + om.broker = nil + om.brokerLock.Unlock() + }) return nil } -func (om *offsetManager) refBrokerOffsetManager(broker *Broker) *brokerOffsetManager { - om.lock.Lock() - defer om.lock.Unlock() +func (om *offsetManager) fetchInitialOffset(topic string, partition int32, retries int) (int64, string, error) { + broker, err := om.coordinator() + if err != nil { + if retries <= 0 { + return 0, "", err + } + return om.fetchInitialOffset(topic, partition, retries-1) + } + + req := new(OffsetFetchRequest) + req.Version = 1 + req.ConsumerGroup = om.group + req.AddPartition(topic, partition) + + resp, err := broker.FetchOffset(req) + if err != nil { + if retries <= 0 { + return 0, "", err + } + om.releaseCoordinator(broker) + return om.fetchInitialOffset(topic, partition, retries-1) + } + + block := resp.GetBlock(topic, partition) + if block == nil { + return 0, "", ErrIncompleteResponse + } + + switch block.Err { + case ErrNoError: + return block.Offset, block.Metadata, nil + case ErrNotCoordinatorForConsumer: + if retries <= 0 { + return 0, "", block.Err + } + om.releaseCoordinator(broker) + return om.fetchInitialOffset(topic, partition, retries-1) + case ErrOffsetsLoadInProgress: + if retries <= 0 { + return 0, "", block.Err + } + select { + case <-om.closing: + return 0, "", block.Err + case <-time.After(om.conf.Metadata.Retry.Backoff): + } + return om.fetchInitialOffset(topic, partition, retries-1) + default: + return 0, "", block.Err + } +} + +func (om *offsetManager) coordinator() (*Broker, error) { + om.brokerLock.RLock() + broker := om.broker + om.brokerLock.RUnlock() - bom := om.boms[broker] - if bom == nil { - bom = om.newBrokerOffsetManager(broker) - om.boms[broker] = bom + if broker != nil { + return broker, nil } - bom.refs++ + om.brokerLock.Lock() + defer om.brokerLock.Unlock() - return bom + if broker := om.broker; broker != nil { + return broker, nil + } + + if err := om.client.RefreshCoordinator(om.group); err != nil { + return nil, err + } + + broker, err := om.client.Coordinator(om.group) + if err != nil { + return nil, err + } + + om.broker = broker + return broker, nil } -func (om *offsetManager) unrefBrokerOffsetManager(bom *brokerOffsetManager) { - om.lock.Lock() - defer om.lock.Unlock() +func (om *offsetManager) releaseCoordinator(b *Broker) { + om.brokerLock.Lock() + if om.broker == b { + om.broker = nil + } + om.brokerLock.Unlock() +} - bom.refs-- +func (om *offsetManager) mainLoop() { + defer om.ticker.Stop() + defer close(om.closed) - if bom.refs == 0 { - close(bom.updateSubscriptions) - if om.boms[bom.broker] == bom { - delete(om.boms, bom.broker) + for { + select { + case <-om.ticker.C: + om.flushToBroker() + om.releasePOMs(false) + case <-om.closing: + return } } } -func (om *offsetManager) abandonBroker(bom *brokerOffsetManager) { - om.lock.Lock() - defer om.lock.Unlock() +func (om *offsetManager) flushToBroker() { + req := om.constructRequest() + if req == nil { + return + } + + broker, err := om.coordinator() + if err != nil { + om.handleError(err) + return + } + + resp, err := broker.CommitOffset(req) + if err != nil { + om.handleError(err) + om.releaseCoordinator(broker) + _ = broker.Close() + return + } - delete(om.boms, bom.broker) + om.handleResponse(broker, req, resp) } -func (om *offsetManager) abandonPartitionOffsetManager(pom *partitionOffsetManager) { - om.lock.Lock() - defer om.lock.Unlock() +func (om *offsetManager) constructRequest() *OffsetCommitRequest { + var r *OffsetCommitRequest + var perPartitionTimestamp int64 + if om.conf.Consumer.Offsets.Retention == 0 { + perPartitionTimestamp = ReceiveTime + r = &OffsetCommitRequest{ + Version: 1, + ConsumerGroup: om.group, + ConsumerID: om.memberID, + ConsumerGroupGeneration: om.generation, + } + } else { + r = &OffsetCommitRequest{ + Version: 2, + RetentionTime: int64(om.conf.Consumer.Offsets.Retention / time.Millisecond), + ConsumerGroup: om.group, + ConsumerID: om.memberID, + ConsumerGroupGeneration: om.generation, + } - delete(om.poms[pom.topic], pom.partition) - if len(om.poms[pom.topic]) == 0 { - delete(om.poms, pom.topic) } + + om.pomsLock.RLock() + defer om.pomsLock.RUnlock() + + for _, topicManagers := range om.poms { + for _, pom := range topicManagers { + pom.lock.Lock() + if pom.dirty { + r.AddBlock(pom.topic, pom.partition, pom.offset, perPartitionTimestamp, pom.metadata) + } + pom.lock.Unlock() + } + } + + if len(r.blocks) > 0 { + return r + } + + return nil +} + +func (om *offsetManager) handleResponse(broker *Broker, req *OffsetCommitRequest, resp *OffsetCommitResponse) { + om.pomsLock.RLock() + defer om.pomsLock.RUnlock() + + for _, topicManagers := range om.poms { + for _, pom := range topicManagers { + if req.blocks[pom.topic] == nil || req.blocks[pom.topic][pom.partition] == nil { + continue + } + + var err KError + var ok bool + + if resp.Errors[pom.topic] == nil { + pom.handleError(ErrIncompleteResponse) + continue + } + if err, ok = resp.Errors[pom.topic][pom.partition]; !ok { + pom.handleError(ErrIncompleteResponse) + continue + } + + switch err { + case ErrNoError: + block := req.blocks[pom.topic][pom.partition] + pom.updateCommitted(block.offset, block.metadata) + case ErrNotLeaderForPartition, ErrLeaderNotAvailable, + ErrConsumerCoordinatorNotAvailable, ErrNotCoordinatorForConsumer: + // not a critical error, we just need to redispatch + om.releaseCoordinator(broker) + case ErrOffsetMetadataTooLarge, ErrInvalidCommitOffsetSize: + // nothing we can do about this, just tell the user and carry on + pom.handleError(err) + case ErrOffsetsLoadInProgress: + // nothing wrong but we didn't commit, we'll get it next time round + break + case ErrUnknownTopicOrPartition: + // let the user know *and* try redispatching - if topic-auto-create is + // enabled, redispatching should trigger a metadata req and create the + // topic; if not then re-dispatching won't help, but we've let the user + // know and it shouldn't hurt either (see https://github.com/Shopify/sarama/issues/706) + fallthrough + default: + // dunno, tell the user and try redispatching + pom.handleError(err) + om.releaseCoordinator(broker) + } + } + } +} + +func (om *offsetManager) handleError(err error) { + om.pomsLock.RLock() + defer om.pomsLock.RUnlock() + + for _, topicManagers := range om.poms { + for _, pom := range topicManagers { + pom.handleError(err) + } + } +} + +func (om *offsetManager) asyncClosePOMs() { + om.pomsLock.RLock() + defer om.pomsLock.RUnlock() + + for _, topicManagers := range om.poms { + for _, pom := range topicManagers { + pom.AsyncClose() + } + } +} + +// Releases/removes closed POMs once they are clean (or when forced) +func (om *offsetManager) releasePOMs(force bool) (remaining int) { + om.pomsLock.Lock() + defer om.pomsLock.Unlock() + + for topic, topicManagers := range om.poms { + for partition, pom := range topicManagers { + pom.lock.Lock() + releaseDue := pom.done && (force || !pom.dirty) + pom.lock.Unlock() + + if releaseDue { + pom.release() + + delete(om.poms[topic], partition) + if len(om.poms[topic]) == 0 { + delete(om.poms, topic) + } + } + } + remaining += len(om.poms[topic]) + } + return +} + +func (om *offsetManager) findPOM(topic string, partition int32) *partitionOffsetManager { + om.pomsLock.RLock() + defer om.pomsLock.RUnlock() + + if partitions, ok := om.poms[topic]; ok { + if pom, ok := partitions[partition]; ok { + return pom + } + } + return nil } // Partition Offset Manager @@ -187,138 +463,26 @@ type partitionOffsetManager struct { offset int64 metadata string dirty bool - clean sync.Cond - broker *brokerOffsetManager + done bool - errors chan *ConsumerError - rebalance chan none - dying chan none + releaseOnce sync.Once + errors chan *ConsumerError } func (om *offsetManager) newPartitionOffsetManager(topic string, partition int32) (*partitionOffsetManager, error) { - pom := &partitionOffsetManager{ + offset, metadata, err := om.fetchInitialOffset(topic, partition, om.conf.Metadata.Retry.Max) + if err != nil { + return nil, err + } + + return &partitionOffsetManager{ parent: om, topic: topic, partition: partition, errors: make(chan *ConsumerError, om.conf.ChannelBufferSize), - rebalance: make(chan none, 1), - dying: make(chan none), - } - pom.clean.L = &pom.lock - - if err := pom.selectBroker(); err != nil { - return nil, err - } - - if err := pom.fetchInitialOffset(om.conf.Metadata.Retry.Max); err != nil { - return nil, err - } - - pom.broker.updateSubscriptions <- pom - - go withRecover(pom.mainLoop) - - return pom, nil -} - -func (pom *partitionOffsetManager) mainLoop() { - for { - select { - case <-pom.rebalance: - if err := pom.selectBroker(); err != nil { - pom.handleError(err) - pom.rebalance <- none{} - } else { - pom.broker.updateSubscriptions <- pom - } - case <-pom.dying: - if pom.broker != nil { - select { - case <-pom.rebalance: - case pom.broker.updateSubscriptions <- pom: - } - pom.parent.unrefBrokerOffsetManager(pom.broker) - } - pom.parent.abandonPartitionOffsetManager(pom) - close(pom.errors) - return - } - } -} - -func (pom *partitionOffsetManager) selectBroker() error { - if pom.broker != nil { - pom.parent.unrefBrokerOffsetManager(pom.broker) - pom.broker = nil - } - - var broker *Broker - var err error - - if err = pom.parent.client.RefreshCoordinator(pom.parent.group); err != nil { - return err - } - - if broker, err = pom.parent.client.Coordinator(pom.parent.group); err != nil { - return err - } - - pom.broker = pom.parent.refBrokerOffsetManager(broker) - return nil -} - -func (pom *partitionOffsetManager) fetchInitialOffset(retries int) error { - request := new(OffsetFetchRequest) - request.Version = 1 - request.ConsumerGroup = pom.parent.group - request.AddPartition(pom.topic, pom.partition) - - response, err := pom.broker.broker.FetchOffset(request) - if err != nil { - return err - } - - block := response.GetBlock(pom.topic, pom.partition) - if block == nil { - return ErrIncompleteResponse - } - - switch block.Err { - case ErrNoError: - pom.offset = block.Offset - pom.metadata = block.Metadata - return nil - case ErrNotCoordinatorForConsumer: - if retries <= 0 { - return block.Err - } - if err := pom.selectBroker(); err != nil { - return err - } - return pom.fetchInitialOffset(retries - 1) - case ErrOffsetsLoadInProgress: - if retries <= 0 { - return block.Err - } - time.Sleep(pom.parent.conf.Metadata.Retry.Backoff) - return pom.fetchInitialOffset(retries - 1) - default: - return block.Err - } -} - -func (pom *partitionOffsetManager) handleError(err error) { - cErr := &ConsumerError{ - Topic: pom.topic, - Partition: pom.partition, - Err: err, - } - - if pom.parent.conf.Consumer.Return.Errors { - pom.errors <- cErr - } else { - Logger.Println(cErr) - } + offset: offset, + metadata: metadata, + }, nil } func (pom *partitionOffsetManager) Errors() <-chan *ConsumerError { @@ -353,7 +517,6 @@ func (pom *partitionOffsetManager) updateCommitted(offset int64, metadata string if pom.offset == offset && pom.metadata == metadata { pom.dirty = false - pom.clean.Signal() } } @@ -369,16 +532,9 @@ func (pom *partitionOffsetManager) NextOffset() (int64, string) { } func (pom *partitionOffsetManager) AsyncClose() { - go func() { - pom.lock.Lock() - defer pom.lock.Unlock() - - for pom.dirty { - pom.clean.Wait() - } - - close(pom.dying) - }() + pom.lock.Lock() + pom.done = true + pom.lock.Unlock() } func (pom *partitionOffsetManager) Close() error { @@ -395,166 +551,22 @@ func (pom *partitionOffsetManager) Close() error { return nil } -// Broker Offset Manager - -type brokerOffsetManager struct { - parent *offsetManager - broker *Broker - timer *time.Ticker - updateSubscriptions chan *partitionOffsetManager - subscriptions map[*partitionOffsetManager]none - refs int -} - -func (om *offsetManager) newBrokerOffsetManager(broker *Broker) *brokerOffsetManager { - bom := &brokerOffsetManager{ - parent: om, - broker: broker, - timer: time.NewTicker(om.conf.Consumer.Offsets.CommitInterval), - updateSubscriptions: make(chan *partitionOffsetManager), - subscriptions: make(map[*partitionOffsetManager]none), - } - - go withRecover(bom.mainLoop) - - return bom -} - -func (bom *brokerOffsetManager) mainLoop() { - for { - select { - case <-bom.timer.C: - if len(bom.subscriptions) > 0 { - bom.flushToBroker() - } - case s, ok := <-bom.updateSubscriptions: - if !ok { - bom.timer.Stop() - return - } - if _, ok := bom.subscriptions[s]; ok { - delete(bom.subscriptions, s) - } else { - bom.subscriptions[s] = none{} - } - } - } -} - -func (bom *brokerOffsetManager) flushToBroker() { - request := bom.constructRequest() - if request == nil { - return - } - - response, err := bom.broker.CommitOffset(request) - - if err != nil { - bom.abort(err) - return - } - - for s := range bom.subscriptions { - if request.blocks[s.topic] == nil || request.blocks[s.topic][s.partition] == nil { - continue - } - - var err KError - var ok bool - - if response.Errors[s.topic] == nil { - s.handleError(ErrIncompleteResponse) - delete(bom.subscriptions, s) - s.rebalance <- none{} - continue - } - if err, ok = response.Errors[s.topic][s.partition]; !ok { - s.handleError(ErrIncompleteResponse) - delete(bom.subscriptions, s) - s.rebalance <- none{} - continue - } - - switch err { - case ErrNoError: - block := request.blocks[s.topic][s.partition] - s.updateCommitted(block.offset, block.metadata) - case ErrNotLeaderForPartition, ErrLeaderNotAvailable, - ErrConsumerCoordinatorNotAvailable, ErrNotCoordinatorForConsumer: - // not a critical error, we just need to redispatch - delete(bom.subscriptions, s) - s.rebalance <- none{} - case ErrOffsetMetadataTooLarge, ErrInvalidCommitOffsetSize: - // nothing we can do about this, just tell the user and carry on - s.handleError(err) - case ErrOffsetsLoadInProgress: - // nothing wrong but we didn't commit, we'll get it next time round - break - case ErrUnknownTopicOrPartition: - // let the user know *and* try redispatching - if topic-auto-create is - // enabled, redispatching should trigger a metadata request and create the - // topic; if not then re-dispatching won't help, but we've let the user - // know and it shouldn't hurt either (see https://github.com/Shopify/sarama/issues/706) - fallthrough - default: - // dunno, tell the user and try redispatching - s.handleError(err) - delete(bom.subscriptions, s) - s.rebalance <- none{} - } +func (pom *partitionOffsetManager) handleError(err error) { + cErr := &ConsumerError{ + Topic: pom.topic, + Partition: pom.partition, + Err: err, } -} -func (bom *brokerOffsetManager) constructRequest() *OffsetCommitRequest { - var r *OffsetCommitRequest - var perPartitionTimestamp int64 - if bom.parent.conf.Consumer.Offsets.Retention == 0 { - perPartitionTimestamp = ReceiveTime - r = &OffsetCommitRequest{ - Version: 1, - ConsumerGroup: bom.parent.group, - ConsumerGroupGeneration: GroupGenerationUndefined, - } + if pom.parent.conf.Consumer.Return.Errors { + pom.errors <- cErr } else { - r = &OffsetCommitRequest{ - Version: 2, - RetentionTime: int64(bom.parent.conf.Consumer.Offsets.Retention / time.Millisecond), - ConsumerGroup: bom.parent.group, - ConsumerGroupGeneration: GroupGenerationUndefined, - } - - } - - for s := range bom.subscriptions { - s.lock.Lock() - if s.dirty { - r.AddBlock(s.topic, s.partition, s.offset, perPartitionTimestamp, s.metadata) - } - s.lock.Unlock() - } - - if len(r.blocks) > 0 { - return r + Logger.Println(cErr) } - - return nil } -func (bom *brokerOffsetManager) abort(err error) { - _ = bom.broker.Close() // we don't care about the error this might return, we already have one - bom.parent.abandonBroker(bom) - - for pom := range bom.subscriptions { - pom.handleError(err) - pom.rebalance <- none{} - } - - for s := range bom.updateSubscriptions { - if _, ok := bom.subscriptions[s]; !ok { - s.handleError(err) - s.rebalance <- none{} - } - } - - bom.subscriptions = make(map[*partitionOffsetManager]none) +func (pom *partitionOffsetManager) release() { + pom.releaseOnce.Do(func() { + go close(pom.errors) + }) } diff --git a/vendor/github.com/Shopify/sarama/records.go b/vendor/github.com/Shopify/sarama/records.go index 301055bb070..192f5927b21 100644 --- a/vendor/github.com/Shopify/sarama/records.go +++ b/vendor/github.com/Shopify/sarama/records.go @@ -163,6 +163,27 @@ func (r *Records) isControl() (bool, error) { return false, fmt.Errorf("unknown records type: %v", r.recordsType) } +func (r *Records) isOverflow() (bool, error) { + if r.recordsType == unknownRecords { + if empty, err := r.setTypeFromFields(); err != nil || empty { + return false, err + } + } + + switch r.recordsType { + case unknownRecords: + return false, nil + case legacyRecords: + if r.MsgSet == nil { + return false, nil + } + return r.MsgSet.OverflowMessage, nil + case defaultRecords: + return false, nil + } + return false, fmt.Errorf("unknown records type: %v", r.recordsType) +} + func magicValue(pd packetDecoder) (int8, error) { dec, err := pd.peek(magicOffset, magicLength) if err != nil { diff --git a/vendor/github.com/Shopify/sarama/utils.go b/vendor/github.com/Shopify/sarama/utils.go index 702e2262701..1bb00d761a4 100644 --- a/vendor/github.com/Shopify/sarama/utils.go +++ b/vendor/github.com/Shopify/sarama/utils.go @@ -155,6 +155,7 @@ var ( V0_11_0_2 = newKafkaVersion(0, 11, 0, 2) V1_0_0_0 = newKafkaVersion(1, 0, 0, 0) V1_1_0_0 = newKafkaVersion(1, 1, 0, 0) + V2_0_0_0 = newKafkaVersion(2, 0, 0, 0) SupportedVersions = []KafkaVersion{ V0_8_2_0, @@ -173,9 +174,10 @@ var ( V0_11_0_2, V1_0_0_0, V1_1_0_0, + V2_0_0_0, } MinVersion = V0_8_2_0 - MaxVersion = V1_1_0_0 + MaxVersion = V2_0_0_0 ) func ParseKafkaVersion(s string) (KafkaVersion, error) { diff --git a/vendor/github.com/bsm/sarama-cluster/balancer.go b/vendor/github.com/bsm/sarama-cluster/balancer.go index 0f9b445ee45..3aeaecef7a3 100644 --- a/vendor/github.com/bsm/sarama-cluster/balancer.go +++ b/vendor/github.com/bsm/sarama-cluster/balancer.go @@ -157,10 +157,6 @@ func (r *balancer) Topic(name string, memberID string) error { } func (r *balancer) Perform(s Strategy) map[string]map[string][]int32 { - if r == nil { - return nil - } - res := make(map[string]map[string][]int32, 1) for topic, info := range r.topics { for memberID, partitions := range info.Perform(s) { diff --git a/vendor/github.com/bsm/sarama-cluster/consumer.go b/vendor/github.com/bsm/sarama-cluster/consumer.go index 13500cc8e75..e7a67dac8b6 100644 --- a/vendor/github.com/bsm/sarama-cluster/consumer.go +++ b/vendor/github.com/bsm/sarama-cluster/consumer.go @@ -140,18 +140,16 @@ func (c *Consumer) HighWaterMarks() map[string]map[int32]int64 { return c.consum // your application crashes. This means that you may end up processing the same // message twice, and your processing should ideally be idempotent. func (c *Consumer) MarkOffset(msg *sarama.ConsumerMessage, metadata string) { - sub := c.subs.Fetch(msg.Topic, msg.Partition) - if sub != nil { - sub.MarkOffset(msg.Offset+1, metadata) + if sub := c.subs.Fetch(msg.Topic, msg.Partition); sub != nil { + sub.MarkOffset(msg.Offset, metadata) } } // MarkPartitionOffset marks an offset of the provided topic/partition as processed. // See MarkOffset for additional explanation. func (c *Consumer) MarkPartitionOffset(topic string, partition int32, offset int64, metadata string) { - sub := c.subs.Fetch(topic, partition) - if sub != nil { - sub.MarkOffset(offset+1, metadata) + if sub := c.subs.Fetch(topic, partition); sub != nil { + sub.MarkOffset(offset, metadata) } } @@ -162,9 +160,8 @@ func (c *Consumer) MarkOffsets(s *OffsetStash) { defer s.mu.Unlock() for tp, info := range s.offsets { - sub := c.subs.Fetch(tp.Topic, tp.Partition) - if sub != nil { - sub.MarkOffset(info.Offset+1, info.Metadata) + if sub := c.subs.Fetch(tp.Topic, tp.Partition); sub != nil { + sub.MarkOffset(info.Offset, info.Metadata) } delete(s.offsets, tp) } @@ -177,9 +174,8 @@ func (c *Consumer) MarkOffsets(s *OffsetStash) { // // Difference between ResetOffset and MarkOffset is that it allows to rewind to an earlier offset func (c *Consumer) ResetOffset(msg *sarama.ConsumerMessage, metadata string) { - sub := c.subs.Fetch(msg.Topic, msg.Partition) - if sub != nil { - sub.ResetOffset(msg.Offset+1, metadata) + if sub := c.subs.Fetch(msg.Topic, msg.Partition); sub != nil { + sub.ResetOffset(msg.Offset, metadata) } } @@ -188,7 +184,7 @@ func (c *Consumer) ResetOffset(msg *sarama.ConsumerMessage, metadata string) { func (c *Consumer) ResetPartitionOffset(topic string, partition int32, offset int64, metadata string) { sub := c.subs.Fetch(topic, partition) if sub != nil { - sub.ResetOffset(offset+1, metadata) + sub.ResetOffset(offset, metadata) } } @@ -199,9 +195,8 @@ func (c *Consumer) ResetOffsets(s *OffsetStash) { defer s.mu.Unlock() for tp, info := range s.offsets { - sub := c.subs.Fetch(tp.Topic, tp.Partition) - if sub != nil { - sub.ResetOffset(info.Offset+1, info.Metadata) + if sub := c.subs.Fetch(tp.Topic, tp.Partition); sub != nil { + sub.ResetOffset(info.Offset, info.Metadata) } delete(s.offsets, tp) } @@ -264,9 +259,8 @@ func (c *Consumer) CommitOffsets() error { if kerr != sarama.ErrNoError { err = kerr } else if state, ok := snap[topicPartition{topic, partition}]; ok { - sub := c.subs.Fetch(topic, partition) - if sub != nil { - sub.MarkCommitted(state.Info.Offset) + if sub := c.subs.Fetch(topic, partition); sub != nil { + sub.markCommitted(state.Info.Offset) } } } @@ -706,12 +700,13 @@ func (c *Consumer) syncGroup(strategy *balancer) (map[string][]int32, error) { GenerationId: generationID, } - for memberID, topics := range strategy.Perform(c.client.config.Group.PartitionStrategy) { - if err := req.AddGroupAssignmentMember(memberID, &sarama.ConsumerGroupMemberAssignment{ - Version: 1, - Topics: topics, - }); err != nil { - return nil, err + if strategy != nil { + for memberID, topics := range strategy.Perform(c.client.config.Group.PartitionStrategy) { + if err := req.AddGroupAssignmentMember(memberID, &sarama.ConsumerGroupMemberAssignment{ + Topics: topics, + }); err != nil { + return nil, err + } } } @@ -829,9 +824,9 @@ func (c *Consumer) createConsumer(tomb *loopTomb, topic string, partition int32, // Start partition consumer goroutine tomb.Go(func(stopper <-chan none) { if c.client.config.Group.Mode == ConsumerModePartitions { - pc.WaitFor(stopper, c.errors) + pc.waitFor(stopper, c.errors) } else { - pc.Multiplex(stopper, c.messages, c.errors) + pc.multiplex(stopper, c.messages, c.errors) } }) diff --git a/vendor/github.com/bsm/sarama-cluster/partitions.go b/vendor/github.com/bsm/sarama-cluster/partitions.go index 987780bde1e..bfaa587830d 100644 --- a/vendor/github.com/bsm/sarama-cluster/partitions.go +++ b/vendor/github.com/bsm/sarama-cluster/partitions.go @@ -19,6 +19,16 @@ type PartitionConsumer interface { // Partition returns the consumed partition Partition() int32 + + // InitialOffset returns the offset used for creating the PartitionConsumer instance. + // The returned offset can be a literal offset, or OffsetNewest, or OffsetOldest + InitialOffset() int64 + + // MarkOffset marks the offset of a message as preocessed. + MarkOffset(offset int64, metadata string) + + // ResetOffset resets the offset to a previously processed message. + ResetOffset(offset int64, metadata string) } type partitionConsumer struct { @@ -27,8 +37,9 @@ type partitionConsumer struct { state partitionState mu sync.Mutex - topic string - partition int32 + topic string + partition int32 + initialOffset int64 closeOnce sync.Once closeErr error @@ -37,12 +48,14 @@ type partitionConsumer struct { } func newPartitionConsumer(manager sarama.Consumer, topic string, partition int32, info offsetInfo, defaultOffset int64) (*partitionConsumer, error) { - pcm, err := manager.ConsumePartition(topic, partition, info.NextOffset(defaultOffset)) + offset := info.NextOffset(defaultOffset) + pcm, err := manager.ConsumePartition(topic, partition, offset) // Resume from default offset, if requested offset is out-of-range if err == sarama.ErrOffsetOutOfRange { info.Offset = -1 - pcm, err = manager.ConsumePartition(topic, partition, defaultOffset) + offset = defaultOffset + pcm, err = manager.ConsumePartition(topic, partition, offset) } if err != nil { return nil, err @@ -52,8 +65,9 @@ func newPartitionConsumer(manager sarama.Consumer, topic string, partition int32 PartitionConsumer: pcm, state: partitionState{Info: info}, - topic: topic, - partition: partition, + topic: topic, + partition: partition, + initialOffset: offset, dying: make(chan none), dead: make(chan none), @@ -66,6 +80,9 @@ func (c *partitionConsumer) Topic() string { return c.topic } // Partition implements PartitionConsumer func (c *partitionConsumer) Partition() int32 { return c.partition } +// InitialOffset implements PartitionConsumer +func (c *partitionConsumer) InitialOffset() int64 { return c.initialOffset } + // AsyncClose implements PartitionConsumer func (c *partitionConsumer) AsyncClose() { c.closeOnce.Do(func() { @@ -81,7 +98,7 @@ func (c *partitionConsumer) Close() error { return c.closeErr } -func (c *partitionConsumer) WaitFor(stopper <-chan none, errors chan<- error) { +func (c *partitionConsumer) waitFor(stopper <-chan none, errors chan<- error) { defer close(c.dead) for { @@ -105,7 +122,7 @@ func (c *partitionConsumer) WaitFor(stopper <-chan none, errors chan<- error) { } } -func (c *partitionConsumer) Multiplex(stopper <-chan none, messages chan<- *sarama.ConsumerMessage, errors chan<- error) { +func (c *partitionConsumer) multiplex(stopper <-chan none, messages chan<- *sarama.ConsumerMessage, errors chan<- error) { defer close(c.dead) for { @@ -140,11 +157,7 @@ func (c *partitionConsumer) Multiplex(stopper <-chan none, messages chan<- *sara } } -func (c *partitionConsumer) State() partitionState { - if c == nil { - return partitionState{} - } - +func (c *partitionConsumer) getState() partitionState { c.mu.Lock() state := c.state c.mu.Unlock() @@ -152,11 +165,7 @@ func (c *partitionConsumer) State() partitionState { return state } -func (c *partitionConsumer) MarkCommitted(offset int64) { - if c == nil { - return - } - +func (c *partitionConsumer) markCommitted(offset int64) { c.mu.Lock() if offset == c.state.Info.Offset { c.state.Dirty = false @@ -164,28 +173,22 @@ func (c *partitionConsumer) MarkCommitted(offset int64) { c.mu.Unlock() } +// MarkOffset implements PartitionConsumer func (c *partitionConsumer) MarkOffset(offset int64, metadata string) { - if c == nil { - return - } - c.mu.Lock() - if offset > c.state.Info.Offset { - c.state.Info.Offset = offset + if next := offset + 1; next > c.state.Info.Offset { + c.state.Info.Offset = next c.state.Info.Metadata = metadata c.state.Dirty = true } c.mu.Unlock() } +// ResetOffset implements PartitionConsumer func (c *partitionConsumer) ResetOffset(offset int64, metadata string) { - if c == nil { - return - } - c.mu.Lock() - if offset <= c.state.Info.Offset { - c.state.Info.Offset = offset + if next := offset + 1; next <= c.state.Info.Offset { + c.state.Info.Offset = next c.state.Info.Metadata = metadata c.state.Dirty = true } @@ -244,7 +247,7 @@ func (m *partitionMap) Snapshot() map[topicPartition]partitionState { snap := make(map[topicPartition]partitionState, len(m.data)) for tp, pc := range m.data { - snap[tp] = pc.State() + snap[tp] = pc.getState() } return snap } diff --git a/vendor/github.com/eapache/go-xerial-snappy/fuzz.go b/vendor/github.com/eapache/go-xerial-snappy/fuzz.go new file mode 100644 index 00000000000..6a46f4784e1 --- /dev/null +++ b/vendor/github.com/eapache/go-xerial-snappy/fuzz.go @@ -0,0 +1,16 @@ +// +build gofuzz + +package snappy + +func Fuzz(data []byte) int { + decode, err := Decode(data) + if decode == nil && err == nil { + panic("nil error with nil result") + } + + if err != nil { + return 0 + } + + return 1 +} diff --git a/vendor/github.com/eapache/go-xerial-snappy/snappy.go b/vendor/github.com/eapache/go-xerial-snappy/snappy.go index b8f8b51fcef..ea8f7afeb33 100644 --- a/vendor/github.com/eapache/go-xerial-snappy/snappy.go +++ b/vendor/github.com/eapache/go-xerial-snappy/snappy.go @@ -3,40 +3,128 @@ package snappy import ( "bytes" "encoding/binary" + "errors" master "github.com/golang/snappy" ) -var xerialHeader = []byte{130, 83, 78, 65, 80, 80, 89, 0} +const ( + sizeOffset = 16 + sizeBytes = 4 +) + +var ( + xerialHeader = []byte{130, 83, 78, 65, 80, 80, 89, 0} + + // This is xerial version 1 and minimally compatible with version 1 + xerialVersionInfo = []byte{0, 0, 0, 1, 0, 0, 0, 1} + + // ErrMalformed is returned by the decoder when the xerial framing + // is malformed + ErrMalformed = errors.New("malformed xerial framing") +) + +func min(x, y int) int { + if x < y { + return x + } + return y +} // Encode encodes data as snappy with no framing header. func Encode(src []byte) []byte { return master.Encode(nil, src) } +// EncodeStream *appends* to the specified 'dst' the compressed +// 'src' in xerial framing format. If 'dst' does not have enough +// capacity, then a new slice will be allocated. If 'dst' has +// non-zero length, then if *must* have been built using this function. +func EncodeStream(dst, src []byte) []byte { + if len(dst) == 0 { + dst = append(dst, xerialHeader...) + dst = append(dst, xerialVersionInfo...) + } + + // Snappy encode in blocks of maximum 32KB + var ( + max = len(src) + blockSize = 32 * 1024 + pos = 0 + chunk []byte + ) + + for pos < max { + newPos := min(pos + blockSize, max) + chunk = master.Encode(chunk[:cap(chunk)], src[pos:newPos]) + + // First encode the compressed size (big-endian) + // Put* panics if the buffer is too small, so pad 4 bytes first + origLen := len(dst) + dst = append(dst, dst[0:4]...) + binary.BigEndian.PutUint32(dst[origLen:], uint32(len(chunk))) + + // And now the compressed data + dst = append(dst, chunk...) + pos = newPos + } + return dst +} + // Decode decodes snappy data whether it is traditional unframed // or includes the xerial framing format. func Decode(src []byte) ([]byte, error) { + return DecodeInto(nil, src) +} + +// DecodeInto decodes snappy data whether it is traditional unframed +// or includes the xerial framing format into the specified `dst`. +// It is assumed that the entirety of `dst` including all capacity is available +// for use by this function. If `dst` is nil *or* insufficiently large to hold +// the decoded `src`, new space will be allocated. +func DecodeInto(dst, src []byte) ([]byte, error) { + var max = len(src) + if max < len(xerialHeader) { + return nil, ErrMalformed + } + if !bytes.Equal(src[:8], xerialHeader) { - return master.Decode(nil, src) + return master.Decode(dst[:cap(dst)], src) + } + + if max < sizeOffset+sizeBytes { + return nil, ErrMalformed + } + + if dst == nil { + dst = make([]byte, 0, len(src)) } + dst = dst[:0] var ( - pos = uint32(16) - max = uint32(len(src)) - dst = make([]byte, 0, len(src)) + pos = sizeOffset chunk []byte - err error + err error ) - for pos < max { - size := binary.BigEndian.Uint32(src[pos : pos+4]) - pos += 4 - chunk, err = master.Decode(chunk, src[pos:pos+size]) + for pos+sizeBytes <= max { + size := int(binary.BigEndian.Uint32(src[pos : pos+sizeBytes])) + pos += sizeBytes + + nextPos := pos + size + // On architectures where int is 32-bytes wide size + pos could + // overflow so we need to check the low bound as well as the + // high + if nextPos < pos || nextPos > max { + return nil, ErrMalformed + } + + chunk, err = master.Decode(chunk[:cap(chunk)], src[pos:nextPos]) + if err != nil { return nil, err } - pos += size + pos = nextPos dst = append(dst, chunk...) } return dst, nil diff --git a/vendor/github.com/evanphx/json-patch/LICENSE b/vendor/github.com/evanphx/json-patch/LICENSE new file mode 100644 index 00000000000..0eb9b72d84d --- /dev/null +++ b/vendor/github.com/evanphx/json-patch/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) 2014, Evan Phoenix +All rights reserved. + +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 the Evan Phoenix 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. diff --git a/vendor/github.com/evanphx/json-patch/merge.go b/vendor/github.com/evanphx/json-patch/merge.go new file mode 100644 index 00000000000..6806c4c200b --- /dev/null +++ b/vendor/github.com/evanphx/json-patch/merge.go @@ -0,0 +1,383 @@ +package jsonpatch + +import ( + "bytes" + "encoding/json" + "fmt" + "reflect" +) + +func merge(cur, patch *lazyNode, mergeMerge bool) *lazyNode { + curDoc, err := cur.intoDoc() + + if err != nil { + pruneNulls(patch) + return patch + } + + patchDoc, err := patch.intoDoc() + + if err != nil { + return patch + } + + mergeDocs(curDoc, patchDoc, mergeMerge) + + return cur +} + +func mergeDocs(doc, patch *partialDoc, mergeMerge bool) { + for k, v := range *patch { + if v == nil { + if mergeMerge { + (*doc)[k] = nil + } else { + delete(*doc, k) + } + } else { + cur, ok := (*doc)[k] + + if !ok || cur == nil { + pruneNulls(v) + (*doc)[k] = v + } else { + (*doc)[k] = merge(cur, v, mergeMerge) + } + } + } +} + +func pruneNulls(n *lazyNode) { + sub, err := n.intoDoc() + + if err == nil { + pruneDocNulls(sub) + } else { + ary, err := n.intoAry() + + if err == nil { + pruneAryNulls(ary) + } + } +} + +func pruneDocNulls(doc *partialDoc) *partialDoc { + for k, v := range *doc { + if v == nil { + delete(*doc, k) + } else { + pruneNulls(v) + } + } + + return doc +} + +func pruneAryNulls(ary *partialArray) *partialArray { + newAry := []*lazyNode{} + + for _, v := range *ary { + if v != nil { + pruneNulls(v) + newAry = append(newAry, v) + } + } + + *ary = newAry + + return ary +} + +var errBadJSONDoc = fmt.Errorf("Invalid JSON Document") +var errBadJSONPatch = fmt.Errorf("Invalid JSON Patch") +var errBadMergeTypes = fmt.Errorf("Mismatched JSON Documents") + +// MergeMergePatches merges two merge patches together, such that +// applying this resulting merged merge patch to a document yields the same +// as merging each merge patch to the document in succession. +func MergeMergePatches(patch1Data, patch2Data []byte) ([]byte, error) { + return doMergePatch(patch1Data, patch2Data, true) +} + +// MergePatch merges the patchData into the docData. +func MergePatch(docData, patchData []byte) ([]byte, error) { + return doMergePatch(docData, patchData, false) +} + +func doMergePatch(docData, patchData []byte, mergeMerge bool) ([]byte, error) { + doc := &partialDoc{} + + docErr := json.Unmarshal(docData, doc) + + patch := &partialDoc{} + + patchErr := json.Unmarshal(patchData, patch) + + if _, ok := docErr.(*json.SyntaxError); ok { + return nil, errBadJSONDoc + } + + if _, ok := patchErr.(*json.SyntaxError); ok { + return nil, errBadJSONPatch + } + + if docErr == nil && *doc == nil { + return nil, errBadJSONDoc + } + + if patchErr == nil && *patch == nil { + return nil, errBadJSONPatch + } + + if docErr != nil || patchErr != nil { + // Not an error, just not a doc, so we turn straight into the patch + if patchErr == nil { + if mergeMerge { + doc = patch + } else { + doc = pruneDocNulls(patch) + } + } else { + patchAry := &partialArray{} + patchErr = json.Unmarshal(patchData, patchAry) + + if patchErr != nil { + return nil, errBadJSONPatch + } + + pruneAryNulls(patchAry) + + out, patchErr := json.Marshal(patchAry) + + if patchErr != nil { + return nil, errBadJSONPatch + } + + return out, nil + } + } else { + mergeDocs(doc, patch, mergeMerge) + } + + return json.Marshal(doc) +} + +// resemblesJSONArray indicates whether the byte-slice "appears" to be +// a JSON array or not. +// False-positives are possible, as this function does not check the internal +// structure of the array. It only checks that the outer syntax is present and +// correct. +func resemblesJSONArray(input []byte) bool { + input = bytes.TrimSpace(input) + + hasPrefix := bytes.HasPrefix(input, []byte("[")) + hasSuffix := bytes.HasSuffix(input, []byte("]")) + + return hasPrefix && hasSuffix +} + +// CreateMergePatch will return a merge patch document capable of converting +// the original document(s) to the modified document(s). +// The parameters can be bytes of either two JSON Documents, or two arrays of +// JSON documents. +// The merge patch returned follows the specification defined at http://tools.ietf.org/html/draft-ietf-appsawg-json-merge-patch-07 +func CreateMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) { + originalResemblesArray := resemblesJSONArray(originalJSON) + modifiedResemblesArray := resemblesJSONArray(modifiedJSON) + + // Do both byte-slices seem like JSON arrays? + if originalResemblesArray && modifiedResemblesArray { + return createArrayMergePatch(originalJSON, modifiedJSON) + } + + // Are both byte-slices are not arrays? Then they are likely JSON objects... + if !originalResemblesArray && !modifiedResemblesArray { + return createObjectMergePatch(originalJSON, modifiedJSON) + } + + // None of the above? Then return an error because of mismatched types. + return nil, errBadMergeTypes +} + +// createObjectMergePatch will return a merge-patch document capable of +// converting the original document to the modified document. +func createObjectMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) { + originalDoc := map[string]interface{}{} + modifiedDoc := map[string]interface{}{} + + err := json.Unmarshal(originalJSON, &originalDoc) + if err != nil { + return nil, errBadJSONDoc + } + + err = json.Unmarshal(modifiedJSON, &modifiedDoc) + if err != nil { + return nil, errBadJSONDoc + } + + dest, err := getDiff(originalDoc, modifiedDoc) + if err != nil { + return nil, err + } + + return json.Marshal(dest) +} + +// createArrayMergePatch will return an array of merge-patch documents capable +// of converting the original document to the modified document for each +// pair of JSON documents provided in the arrays. +// Arrays of mismatched sizes will result in an error. +func createArrayMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) { + originalDocs := []json.RawMessage{} + modifiedDocs := []json.RawMessage{} + + err := json.Unmarshal(originalJSON, &originalDocs) + if err != nil { + return nil, errBadJSONDoc + } + + err = json.Unmarshal(modifiedJSON, &modifiedDocs) + if err != nil { + return nil, errBadJSONDoc + } + + total := len(originalDocs) + if len(modifiedDocs) != total { + return nil, errBadJSONDoc + } + + result := []json.RawMessage{} + for i := 0; i < len(originalDocs); i++ { + original := originalDocs[i] + modified := modifiedDocs[i] + + patch, err := createObjectMergePatch(original, modified) + if err != nil { + return nil, err + } + + result = append(result, json.RawMessage(patch)) + } + + return json.Marshal(result) +} + +// Returns true if the array matches (must be json types). +// As is idiomatic for go, an empty array is not the same as a nil array. +func matchesArray(a, b []interface{}) bool { + if len(a) != len(b) { + return false + } + if (a == nil && b != nil) || (a != nil && b == nil) { + return false + } + for i := range a { + if !matchesValue(a[i], b[i]) { + return false + } + } + return true +} + +// Returns true if the values matches (must be json types) +// The types of the values must match, otherwise it will always return false +// If two map[string]interface{} are given, all elements must match. +func matchesValue(av, bv interface{}) bool { + if reflect.TypeOf(av) != reflect.TypeOf(bv) { + return false + } + switch at := av.(type) { + case string: + bt := bv.(string) + if bt == at { + return true + } + case float64: + bt := bv.(float64) + if bt == at { + return true + } + case bool: + bt := bv.(bool) + if bt == at { + return true + } + case nil: + // Both nil, fine. + return true + case map[string]interface{}: + bt := bv.(map[string]interface{}) + for key := range at { + if !matchesValue(at[key], bt[key]) { + return false + } + } + for key := range bt { + if !matchesValue(at[key], bt[key]) { + return false + } + } + return true + case []interface{}: + bt := bv.([]interface{}) + return matchesArray(at, bt) + } + return false +} + +// getDiff returns the (recursive) difference between a and b as a map[string]interface{}. +func getDiff(a, b map[string]interface{}) (map[string]interface{}, error) { + into := map[string]interface{}{} + for key, bv := range b { + av, ok := a[key] + // value was added + if !ok { + into[key] = bv + continue + } + // If types have changed, replace completely + if reflect.TypeOf(av) != reflect.TypeOf(bv) { + into[key] = bv + continue + } + // Types are the same, compare values + switch at := av.(type) { + case map[string]interface{}: + bt := bv.(map[string]interface{}) + dst := make(map[string]interface{}, len(bt)) + dst, err := getDiff(at, bt) + if err != nil { + return nil, err + } + if len(dst) > 0 { + into[key] = dst + } + case string, float64, bool: + if !matchesValue(av, bv) { + into[key] = bv + } + case []interface{}: + bt := bv.([]interface{}) + if !matchesArray(at, bt) { + into[key] = bv + } + case nil: + switch bv.(type) { + case nil: + // Both nil, fine. + default: + into[key] = bv + } + default: + panic(fmt.Sprintf("Unknown type:%T in key %s", av, key)) + } + } + // Now add all deleted values as nil + for key := range a { + _, found := b[key] + if !found { + into[key] = nil + } + } + return into, nil +} diff --git a/vendor/github.com/evanphx/json-patch/patch.go b/vendor/github.com/evanphx/json-patch/patch.go new file mode 100644 index 00000000000..f26b6824b6d --- /dev/null +++ b/vendor/github.com/evanphx/json-patch/patch.go @@ -0,0 +1,682 @@ +package jsonpatch + +import ( + "bytes" + "encoding/json" + "fmt" + "strconv" + "strings" +) + +const ( + eRaw = iota + eDoc + eAry +) + +var SupportNegativeIndices bool = true + +type lazyNode struct { + raw *json.RawMessage + doc partialDoc + ary partialArray + which int +} + +type operation map[string]*json.RawMessage + +// Patch is an ordered collection of operations. +type Patch []operation + +type partialDoc map[string]*lazyNode +type partialArray []*lazyNode + +type container interface { + get(key string) (*lazyNode, error) + set(key string, val *lazyNode) error + add(key string, val *lazyNode) error + remove(key string) error +} + +func newLazyNode(raw *json.RawMessage) *lazyNode { + return &lazyNode{raw: raw, doc: nil, ary: nil, which: eRaw} +} + +func (n *lazyNode) MarshalJSON() ([]byte, error) { + switch n.which { + case eRaw: + return json.Marshal(n.raw) + case eDoc: + return json.Marshal(n.doc) + case eAry: + return json.Marshal(n.ary) + default: + return nil, fmt.Errorf("Unknown type") + } +} + +func (n *lazyNode) UnmarshalJSON(data []byte) error { + dest := make(json.RawMessage, len(data)) + copy(dest, data) + n.raw = &dest + n.which = eRaw + return nil +} + +func (n *lazyNode) intoDoc() (*partialDoc, error) { + if n.which == eDoc { + return &n.doc, nil + } + + if n.raw == nil { + return nil, fmt.Errorf("Unable to unmarshal nil pointer as partial document") + } + + err := json.Unmarshal(*n.raw, &n.doc) + + if err != nil { + return nil, err + } + + n.which = eDoc + return &n.doc, nil +} + +func (n *lazyNode) intoAry() (*partialArray, error) { + if n.which == eAry { + return &n.ary, nil + } + + if n.raw == nil { + return nil, fmt.Errorf("Unable to unmarshal nil pointer as partial array") + } + + err := json.Unmarshal(*n.raw, &n.ary) + + if err != nil { + return nil, err + } + + n.which = eAry + return &n.ary, nil +} + +func (n *lazyNode) compact() []byte { + buf := &bytes.Buffer{} + + if n.raw == nil { + return nil + } + + err := json.Compact(buf, *n.raw) + + if err != nil { + return *n.raw + } + + return buf.Bytes() +} + +func (n *lazyNode) tryDoc() bool { + if n.raw == nil { + return false + } + + err := json.Unmarshal(*n.raw, &n.doc) + + if err != nil { + return false + } + + n.which = eDoc + return true +} + +func (n *lazyNode) tryAry() bool { + if n.raw == nil { + return false + } + + err := json.Unmarshal(*n.raw, &n.ary) + + if err != nil { + return false + } + + n.which = eAry + return true +} + +func (n *lazyNode) equal(o *lazyNode) bool { + if n.which == eRaw { + if !n.tryDoc() && !n.tryAry() { + if o.which != eRaw { + return false + } + + return bytes.Equal(n.compact(), o.compact()) + } + } + + if n.which == eDoc { + if o.which == eRaw { + if !o.tryDoc() { + return false + } + } + + if o.which != eDoc { + return false + } + + for k, v := range n.doc { + ov, ok := o.doc[k] + + if !ok { + return false + } + + if v == nil && ov == nil { + continue + } + + if !v.equal(ov) { + return false + } + } + + return true + } + + if o.which != eAry && !o.tryAry() { + return false + } + + if len(n.ary) != len(o.ary) { + return false + } + + for idx, val := range n.ary { + if !val.equal(o.ary[idx]) { + return false + } + } + + return true +} + +func (o operation) kind() string { + if obj, ok := o["op"]; ok && obj != nil { + var op string + + err := json.Unmarshal(*obj, &op) + + if err != nil { + return "unknown" + } + + return op + } + + return "unknown" +} + +func (o operation) path() string { + if obj, ok := o["path"]; ok && obj != nil { + var op string + + err := json.Unmarshal(*obj, &op) + + if err != nil { + return "unknown" + } + + return op + } + + return "unknown" +} + +func (o operation) from() string { + if obj, ok := o["from"]; ok && obj != nil { + var op string + + err := json.Unmarshal(*obj, &op) + + if err != nil { + return "unknown" + } + + return op + } + + return "unknown" +} + +func (o operation) value() *lazyNode { + if obj, ok := o["value"]; ok { + return newLazyNode(obj) + } + + return nil +} + +func isArray(buf []byte) bool { +Loop: + for _, c := range buf { + switch c { + case ' ': + case '\n': + case '\t': + continue + case '[': + return true + default: + break Loop + } + } + + return false +} + +func findObject(pd *container, path string) (container, string) { + doc := *pd + + split := strings.Split(path, "/") + + if len(split) < 2 { + return nil, "" + } + + parts := split[1 : len(split)-1] + + key := split[len(split)-1] + + var err error + + for _, part := range parts { + + next, ok := doc.get(decodePatchKey(part)) + + if next == nil || ok != nil { + return nil, "" + } + + if isArray(*next.raw) { + doc, err = next.intoAry() + + if err != nil { + return nil, "" + } + } else { + doc, err = next.intoDoc() + + if err != nil { + return nil, "" + } + } + } + + return doc, decodePatchKey(key) +} + +func (d *partialDoc) set(key string, val *lazyNode) error { + (*d)[key] = val + return nil +} + +func (d *partialDoc) add(key string, val *lazyNode) error { + (*d)[key] = val + return nil +} + +func (d *partialDoc) get(key string) (*lazyNode, error) { + return (*d)[key], nil +} + +func (d *partialDoc) remove(key string) error { + _, ok := (*d)[key] + if !ok { + return fmt.Errorf("Unable to remove nonexistent key: %s", key) + } + + delete(*d, key) + return nil +} + +func (d *partialArray) set(key string, val *lazyNode) error { + if key == "-" { + *d = append(*d, val) + return nil + } + + idx, err := strconv.Atoi(key) + if err != nil { + return err + } + + sz := len(*d) + if idx+1 > sz { + sz = idx + 1 + } + + ary := make([]*lazyNode, sz) + + cur := *d + + copy(ary, cur) + + if idx >= len(ary) { + return fmt.Errorf("Unable to access invalid index: %d", idx) + } + + ary[idx] = val + + *d = ary + return nil +} + +func (d *partialArray) add(key string, val *lazyNode) error { + if key == "-" { + *d = append(*d, val) + return nil + } + + idx, err := strconv.Atoi(key) + if err != nil { + return err + } + + ary := make([]*lazyNode, len(*d)+1) + + cur := *d + + if idx >= len(ary) { + return fmt.Errorf("Unable to access invalid index: %d", idx) + } + + if SupportNegativeIndices { + if idx < -len(ary) { + return fmt.Errorf("Unable to access invalid index: %d", idx) + } + + if idx < 0 { + idx += len(ary) + } + } + + copy(ary[0:idx], cur[0:idx]) + ary[idx] = val + copy(ary[idx+1:], cur[idx:]) + + *d = ary + return nil +} + +func (d *partialArray) get(key string) (*lazyNode, error) { + idx, err := strconv.Atoi(key) + + if err != nil { + return nil, err + } + + if idx >= len(*d) { + return nil, fmt.Errorf("Unable to access invalid index: %d", idx) + } + + return (*d)[idx], nil +} + +func (d *partialArray) remove(key string) error { + idx, err := strconv.Atoi(key) + if err != nil { + return err + } + + cur := *d + + if idx >= len(cur) { + return fmt.Errorf("Unable to access invalid index: %d", idx) + } + + if SupportNegativeIndices { + if idx < -len(cur) { + return fmt.Errorf("Unable to access invalid index: %d", idx) + } + + if idx < 0 { + idx += len(cur) + } + } + + ary := make([]*lazyNode, len(cur)-1) + + copy(ary[0:idx], cur[0:idx]) + copy(ary[idx:], cur[idx+1:]) + + *d = ary + return nil + +} + +func (p Patch) add(doc *container, op operation) error { + path := op.path() + + con, key := findObject(doc, path) + + if con == nil { + return fmt.Errorf("jsonpatch add operation does not apply: doc is missing path: \"%s\"", path) + } + + return con.add(key, op.value()) +} + +func (p Patch) remove(doc *container, op operation) error { + path := op.path() + + con, key := findObject(doc, path) + + if con == nil { + return fmt.Errorf("jsonpatch remove operation does not apply: doc is missing path: \"%s\"", path) + } + + return con.remove(key) +} + +func (p Patch) replace(doc *container, op operation) error { + path := op.path() + + con, key := findObject(doc, path) + + if con == nil { + return fmt.Errorf("jsonpatch replace operation does not apply: doc is missing path: %s", path) + } + + _, ok := con.get(key) + if ok != nil { + return fmt.Errorf("jsonpatch replace operation does not apply: doc is missing key: %s", path) + } + + return con.set(key, op.value()) +} + +func (p Patch) move(doc *container, op operation) error { + from := op.from() + + con, key := findObject(doc, from) + + if con == nil { + return fmt.Errorf("jsonpatch move operation does not apply: doc is missing from path: %s", from) + } + + val, err := con.get(key) + if err != nil { + return err + } + + err = con.remove(key) + if err != nil { + return err + } + + path := op.path() + + con, key = findObject(doc, path) + + if con == nil { + return fmt.Errorf("jsonpatch move operation does not apply: doc is missing destination path: %s", path) + } + + return con.set(key, val) +} + +func (p Patch) test(doc *container, op operation) error { + path := op.path() + + con, key := findObject(doc, path) + + if con == nil { + return fmt.Errorf("jsonpatch test operation does not apply: is missing path: %s", path) + } + + val, err := con.get(key) + + if err != nil { + return err + } + + if val == nil { + if op.value().raw == nil { + return nil + } + return fmt.Errorf("Testing value %s failed", path) + } else if op.value() == nil { + return fmt.Errorf("Testing value %s failed", path) + } + + if val.equal(op.value()) { + return nil + } + + return fmt.Errorf("Testing value %s failed", path) +} + +func (p Patch) copy(doc *container, op operation) error { + from := op.from() + + con, key := findObject(doc, from) + + if con == nil { + return fmt.Errorf("jsonpatch copy operation does not apply: doc is missing from path: %s", from) + } + + val, err := con.get(key) + if err != nil { + return err + } + + path := op.path() + + con, key = findObject(doc, path) + + if con == nil { + return fmt.Errorf("jsonpatch copy operation does not apply: doc is missing destination path: %s", path) + } + + return con.set(key, val) +} + +// Equal indicates if 2 JSON documents have the same structural equality. +func Equal(a, b []byte) bool { + ra := make(json.RawMessage, len(a)) + copy(ra, a) + la := newLazyNode(&ra) + + rb := make(json.RawMessage, len(b)) + copy(rb, b) + lb := newLazyNode(&rb) + + return la.equal(lb) +} + +// DecodePatch decodes the passed JSON document as an RFC 6902 patch. +func DecodePatch(buf []byte) (Patch, error) { + var p Patch + + err := json.Unmarshal(buf, &p) + + if err != nil { + return nil, err + } + + return p, nil +} + +// Apply mutates a JSON document according to the patch, and returns the new +// document. +func (p Patch) Apply(doc []byte) ([]byte, error) { + return p.ApplyIndent(doc, "") +} + +// ApplyIndent mutates a JSON document according to the patch, and returns the new +// document indented. +func (p Patch) ApplyIndent(doc []byte, indent string) ([]byte, error) { + var pd container + if doc[0] == '[' { + pd = &partialArray{} + } else { + pd = &partialDoc{} + } + + err := json.Unmarshal(doc, pd) + + if err != nil { + return nil, err + } + + err = nil + + for _, op := range p { + switch op.kind() { + case "add": + err = p.add(&pd, op) + case "remove": + err = p.remove(&pd, op) + case "replace": + err = p.replace(&pd, op) + case "move": + err = p.move(&pd, op) + case "test": + err = p.test(&pd, op) + case "copy": + err = p.copy(&pd, op) + default: + err = fmt.Errorf("Unexpected kind: %s", op.kind()) + } + + if err != nil { + return nil, err + } + } + + if indent != "" { + return json.MarshalIndent(pd, "", indent) + } + + return json.Marshal(pd) +} + +// From http://tools.ietf.org/html/rfc6901#section-4 : +// +// Evaluation of each reference token begins by decoding any escaped +// character sequence. This is performed by first transforming any +// occurrence of the sequence '~1' to '/', and then transforming any +// occurrence of the sequence '~0' to '~'. + +var ( + rfc6901Decoder = strings.NewReplacer("~1", "/", "~0", "~") +) + +func decodePatchKey(k string) string { + return rfc6901Decoder.Replace(k) +} diff --git a/vendor/github.com/gobuffalo/envy/LICENSE.txt b/vendor/github.com/gobuffalo/envy/LICENSE.txt new file mode 100644 index 00000000000..123ddc0d804 --- /dev/null +++ b/vendor/github.com/gobuffalo/envy/LICENSE.txt @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright (c) 2018 Mark Bates + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/gobuffalo/envy/envy.go b/vendor/github.com/gobuffalo/envy/envy.go new file mode 100644 index 00000000000..84c1e726654 --- /dev/null +++ b/vendor/github.com/gobuffalo/envy/envy.go @@ -0,0 +1,249 @@ +/* +package envy makes working with ENV variables in Go trivial. + +* Get ENV variables with default values. +* Set ENV variables safely without affecting the underlying system. +* Temporarily change ENV vars; useful for testing. +* Map all of the key/values in the ENV. +* Loads .env files (by using [godotenv](https://github.com/joho/godotenv/)) +* More! +*/ +package envy + +import ( + "flag" + "fmt" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" + + "github.com/joho/godotenv" +) + +var gil = &sync.RWMutex{} +var env = map[string]string{} + +// GO111MODULE is ENV for turning mods on/off +const GO111MODULE = "GO111MODULE" + +func init() { + Load() + loadEnv() +} + +// Load the ENV variables to the env map +func loadEnv() { + gil.Lock() + defer gil.Unlock() + // Detect the Go version on the user system, not the one that was used to compile the binary + v := "" + out, err := exec.Command("go", "version").Output() + if err == nil { + // This will break when Go 2 lands + v = strings.Split(string(out), " ")[2][4:] + } else { + v = runtime.Version()[4:] + } + + goRuntimeVersion, _ := strconv.ParseFloat(runtime.Version()[4:], 64) + + goVersion, err := strconv.ParseFloat(v, 64) + if err != nil { + goVersion = goRuntimeVersion + } + + if os.Getenv("GO_ENV") == "" { + // if the flag "test.v" is *defined*, we're running as a unit test. Note that we don't care + // about v.Value (verbose test mode); we just want to know if the test environment has defined + // it. It's also possible that the flags are not yet fully parsed (i.e. flag.Parsed() == false), + // so we could not depend on v.Value anyway. + // + if v := flag.Lookup("test.v"); v != nil { + env["GO_ENV"] = "test" + } + } + + // set the GOPATH if using >= 1.8 and the GOPATH isn't set + if goVersion >= 8 && os.Getenv("GOPATH") == "" { + out, err := exec.Command("go", "env", "GOPATH").Output() + if err == nil { + gp := strings.TrimSpace(string(out)) + os.Setenv("GOPATH", gp) + } + } + + for _, e := range os.Environ() { + pair := strings.Split(e, "=") + env[pair[0]] = os.Getenv(pair[0]) + } +} + +func Mods() bool { + return Get(GO111MODULE, "off") == "on" +} + +// Reload the ENV variables. Useful if +// an external ENV manager has been used +func Reload() { + env = map[string]string{} + loadEnv() +} + +// Load .env files. Files will be loaded in the same order that are received. +// Redefined vars will override previously existing values. +// IE: envy.Load(".env", "test_env/.env") will result in DIR=test_env +// If no arg passed, it will try to load a .env file. +func Load(files ...string) error { + + // If no files received, load the default one + if len(files) == 0 { + err := godotenv.Overload() + if err == nil { + Reload() + } + return err + } + + // We received a list of files + for _, file := range files { + + // Check if it exists or we can access + if _, err := os.Stat(file); err != nil { + // It does not exist or we can not access. + // Return and stop loading + return err + } + + // It exists and we have permission. Load it + if err := godotenv.Overload(file); err != nil { + return err + } + + // Reload the env so all new changes are noticed + Reload() + + } + return nil +} + +// Get a value from the ENV. If it doesn't exist the +// default value will be returned. +func Get(key string, value string) string { + gil.RLock() + defer gil.RUnlock() + if v, ok := env[key]; ok { + return v + } + return value +} + +// Get a value from the ENV. If it doesn't exist +// an error will be returned +func MustGet(key string) (string, error) { + gil.RLock() + defer gil.RUnlock() + if v, ok := env[key]; ok { + return v, nil + } + return "", fmt.Errorf("could not find ENV var with %s", key) +} + +// Set a value into the ENV. This is NOT permanent. It will +// only affect values accessed through envy. +func Set(key string, value string) { + gil.Lock() + defer gil.Unlock() + env[key] = value +} + +// MustSet the value into the underlying ENV, as well as envy. +// This may return an error if there is a problem setting the +// underlying ENV value. +func MustSet(key string, value string) error { + gil.Lock() + defer gil.Unlock() + err := os.Setenv(key, value) + if err != nil { + return err + } + env[key] = value + return nil +} + +// Map all of the keys/values set in envy. +func Map() map[string]string { + gil.RLock() + defer gil.RUnlock() + cp := map[string]string{} + for k, v := range env { + cp[k] = v + } + return env +} + +// Temp makes a copy of the values and allows operation on +// those values temporarily during the run of the function. +// At the end of the function run the copy is discarded and +// the original values are replaced. This is useful for testing. +// Warning: This function is NOT safe to use from a goroutine or +// from code which may access any Get or Set function from a goroutine +func Temp(f func()) { + oenv := env + env = map[string]string{} + for k, v := range oenv { + env[k] = v + } + defer func() { env = oenv }() + f() +} + +func GoPath() string { + return Get("GOPATH", "") +} + +func GoBin() string { + return Get("GO_BIN", "go") +} + +// GoPaths returns all possible GOPATHS that are set. +func GoPaths() []string { + gp := Get("GOPATH", "") + if runtime.GOOS == "windows" { + return strings.Split(gp, ";") // Windows uses a different separator + } + return strings.Split(gp, ":") +} + +func importPath(path string) string { + for _, gopath := range GoPaths() { + srcpath := filepath.Join(gopath, "src") + rel, err := filepath.Rel(srcpath, path) + if err == nil { + return filepath.ToSlash(rel) + } + } + + // fallback to trim + rel := strings.TrimPrefix(path, filepath.Join(GoPath(), "src")) + rel = strings.TrimPrefix(rel, string(filepath.Separator)) + return filepath.ToSlash(rel) +} + +func CurrentPackage() string { + pwd, _ := os.Getwd() + return importPath(pwd) +} + +func Environ() []string { + gil.RLock() + defer gil.RUnlock() + var e []string + for k, v := range env { + e = append(e, fmt.Sprintf("%s=%s", k, v)) + } + return e +} diff --git a/vendor/github.com/gobuffalo/envy/version.go b/vendor/github.com/gobuffalo/envy/version.go new file mode 100644 index 00000000000..f41fdc0746c --- /dev/null +++ b/vendor/github.com/gobuffalo/envy/version.go @@ -0,0 +1,3 @@ +package envy + +const Version = "v1.6.7" diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go deleted file mode 100644 index e855b1f5c4a..00000000000 --- a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go +++ /dev/null @@ -1,2812 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/descriptor.proto - -package descriptor // import "github.com/golang/protobuf/protoc-gen-go/descriptor" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// 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 - -type FieldDescriptorProto_Type int32 - -const ( - // 0 is reserved for errors. - // Order is weird for historical reasons. - FieldDescriptorProto_TYPE_DOUBLE FieldDescriptorProto_Type = 1 - FieldDescriptorProto_TYPE_FLOAT FieldDescriptorProto_Type = 2 - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if - // negative values are likely. - FieldDescriptorProto_TYPE_INT64 FieldDescriptorProto_Type = 3 - FieldDescriptorProto_TYPE_UINT64 FieldDescriptorProto_Type = 4 - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if - // negative values are likely. - FieldDescriptorProto_TYPE_INT32 FieldDescriptorProto_Type = 5 - FieldDescriptorProto_TYPE_FIXED64 FieldDescriptorProto_Type = 6 - FieldDescriptorProto_TYPE_FIXED32 FieldDescriptorProto_Type = 7 - FieldDescriptorProto_TYPE_BOOL FieldDescriptorProto_Type = 8 - FieldDescriptorProto_TYPE_STRING FieldDescriptorProto_Type = 9 - // Tag-delimited aggregate. - // Group type is deprecated and not supported in proto3. However, Proto3 - // implementations should still be able to parse the group wire format and - // treat group fields as unknown fields. - FieldDescriptorProto_TYPE_GROUP FieldDescriptorProto_Type = 10 - FieldDescriptorProto_TYPE_MESSAGE FieldDescriptorProto_Type = 11 - // New in version 2. - FieldDescriptorProto_TYPE_BYTES FieldDescriptorProto_Type = 12 - FieldDescriptorProto_TYPE_UINT32 FieldDescriptorProto_Type = 13 - FieldDescriptorProto_TYPE_ENUM FieldDescriptorProto_Type = 14 - FieldDescriptorProto_TYPE_SFIXED32 FieldDescriptorProto_Type = 15 - FieldDescriptorProto_TYPE_SFIXED64 FieldDescriptorProto_Type = 16 - FieldDescriptorProto_TYPE_SINT32 FieldDescriptorProto_Type = 17 - FieldDescriptorProto_TYPE_SINT64 FieldDescriptorProto_Type = 18 -) - -var FieldDescriptorProto_Type_name = map[int32]string{ - 1: "TYPE_DOUBLE", - 2: "TYPE_FLOAT", - 3: "TYPE_INT64", - 4: "TYPE_UINT64", - 5: "TYPE_INT32", - 6: "TYPE_FIXED64", - 7: "TYPE_FIXED32", - 8: "TYPE_BOOL", - 9: "TYPE_STRING", - 10: "TYPE_GROUP", - 11: "TYPE_MESSAGE", - 12: "TYPE_BYTES", - 13: "TYPE_UINT32", - 14: "TYPE_ENUM", - 15: "TYPE_SFIXED32", - 16: "TYPE_SFIXED64", - 17: "TYPE_SINT32", - 18: "TYPE_SINT64", -} -var FieldDescriptorProto_Type_value = map[string]int32{ - "TYPE_DOUBLE": 1, - "TYPE_FLOAT": 2, - "TYPE_INT64": 3, - "TYPE_UINT64": 4, - "TYPE_INT32": 5, - "TYPE_FIXED64": 6, - "TYPE_FIXED32": 7, - "TYPE_BOOL": 8, - "TYPE_STRING": 9, - "TYPE_GROUP": 10, - "TYPE_MESSAGE": 11, - "TYPE_BYTES": 12, - "TYPE_UINT32": 13, - "TYPE_ENUM": 14, - "TYPE_SFIXED32": 15, - "TYPE_SFIXED64": 16, - "TYPE_SINT32": 17, - "TYPE_SINT64": 18, -} - -func (x FieldDescriptorProto_Type) Enum() *FieldDescriptorProto_Type { - p := new(FieldDescriptorProto_Type) - *p = x - return p -} -func (x FieldDescriptorProto_Type) String() string { - return proto.EnumName(FieldDescriptorProto_Type_name, int32(x)) -} -func (x *FieldDescriptorProto_Type) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Type_value, data, "FieldDescriptorProto_Type") - if err != nil { - return err - } - *x = FieldDescriptorProto_Type(value) - return nil -} -func (FieldDescriptorProto_Type) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{4, 0} -} - -type FieldDescriptorProto_Label int32 - -const ( - // 0 is reserved for errors - FieldDescriptorProto_LABEL_OPTIONAL FieldDescriptorProto_Label = 1 - FieldDescriptorProto_LABEL_REQUIRED FieldDescriptorProto_Label = 2 - FieldDescriptorProto_LABEL_REPEATED FieldDescriptorProto_Label = 3 -) - -var FieldDescriptorProto_Label_name = map[int32]string{ - 1: "LABEL_OPTIONAL", - 2: "LABEL_REQUIRED", - 3: "LABEL_REPEATED", -} -var FieldDescriptorProto_Label_value = map[string]int32{ - "LABEL_OPTIONAL": 1, - "LABEL_REQUIRED": 2, - "LABEL_REPEATED": 3, -} - -func (x FieldDescriptorProto_Label) Enum() *FieldDescriptorProto_Label { - p := new(FieldDescriptorProto_Label) - *p = x - return p -} -func (x FieldDescriptorProto_Label) String() string { - return proto.EnumName(FieldDescriptorProto_Label_name, int32(x)) -} -func (x *FieldDescriptorProto_Label) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Label_value, data, "FieldDescriptorProto_Label") - if err != nil { - return err - } - *x = FieldDescriptorProto_Label(value) - return nil -} -func (FieldDescriptorProto_Label) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{4, 1} -} - -// Generated classes can be optimized for speed or code size. -type FileOptions_OptimizeMode int32 - -const ( - FileOptions_SPEED FileOptions_OptimizeMode = 1 - // etc. - FileOptions_CODE_SIZE FileOptions_OptimizeMode = 2 - FileOptions_LITE_RUNTIME FileOptions_OptimizeMode = 3 -) - -var FileOptions_OptimizeMode_name = map[int32]string{ - 1: "SPEED", - 2: "CODE_SIZE", - 3: "LITE_RUNTIME", -} -var FileOptions_OptimizeMode_value = map[string]int32{ - "SPEED": 1, - "CODE_SIZE": 2, - "LITE_RUNTIME": 3, -} - -func (x FileOptions_OptimizeMode) Enum() *FileOptions_OptimizeMode { - p := new(FileOptions_OptimizeMode) - *p = x - return p -} -func (x FileOptions_OptimizeMode) String() string { - return proto.EnumName(FileOptions_OptimizeMode_name, int32(x)) -} -func (x *FileOptions_OptimizeMode) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FileOptions_OptimizeMode_value, data, "FileOptions_OptimizeMode") - if err != nil { - return err - } - *x = FileOptions_OptimizeMode(value) - return nil -} -func (FileOptions_OptimizeMode) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{10, 0} -} - -type FieldOptions_CType int32 - -const ( - // Default mode. - FieldOptions_STRING FieldOptions_CType = 0 - FieldOptions_CORD FieldOptions_CType = 1 - FieldOptions_STRING_PIECE FieldOptions_CType = 2 -) - -var FieldOptions_CType_name = map[int32]string{ - 0: "STRING", - 1: "CORD", - 2: "STRING_PIECE", -} -var FieldOptions_CType_value = map[string]int32{ - "STRING": 0, - "CORD": 1, - "STRING_PIECE": 2, -} - -func (x FieldOptions_CType) Enum() *FieldOptions_CType { - p := new(FieldOptions_CType) - *p = x - return p -} -func (x FieldOptions_CType) String() string { - return proto.EnumName(FieldOptions_CType_name, int32(x)) -} -func (x *FieldOptions_CType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldOptions_CType_value, data, "FieldOptions_CType") - if err != nil { - return err - } - *x = FieldOptions_CType(value) - return nil -} -func (FieldOptions_CType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{12, 0} -} - -type FieldOptions_JSType int32 - -const ( - // Use the default type. - FieldOptions_JS_NORMAL FieldOptions_JSType = 0 - // Use JavaScript strings. - FieldOptions_JS_STRING FieldOptions_JSType = 1 - // Use JavaScript numbers. - FieldOptions_JS_NUMBER FieldOptions_JSType = 2 -) - -var FieldOptions_JSType_name = map[int32]string{ - 0: "JS_NORMAL", - 1: "JS_STRING", - 2: "JS_NUMBER", -} -var FieldOptions_JSType_value = map[string]int32{ - "JS_NORMAL": 0, - "JS_STRING": 1, - "JS_NUMBER": 2, -} - -func (x FieldOptions_JSType) Enum() *FieldOptions_JSType { - p := new(FieldOptions_JSType) - *p = x - return p -} -func (x FieldOptions_JSType) String() string { - return proto.EnumName(FieldOptions_JSType_name, int32(x)) -} -func (x *FieldOptions_JSType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldOptions_JSType_value, data, "FieldOptions_JSType") - if err != nil { - return err - } - *x = FieldOptions_JSType(value) - return nil -} -func (FieldOptions_JSType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{12, 1} -} - -// Is this method side-effect-free (or safe in HTTP parlance), or idempotent, -// or neither? HTTP based RPC implementation may choose GET verb for safe -// methods, and PUT verb for idempotent methods instead of the default POST. -type MethodOptions_IdempotencyLevel int32 - -const ( - MethodOptions_IDEMPOTENCY_UNKNOWN MethodOptions_IdempotencyLevel = 0 - MethodOptions_NO_SIDE_EFFECTS MethodOptions_IdempotencyLevel = 1 - MethodOptions_IDEMPOTENT MethodOptions_IdempotencyLevel = 2 -) - -var MethodOptions_IdempotencyLevel_name = map[int32]string{ - 0: "IDEMPOTENCY_UNKNOWN", - 1: "NO_SIDE_EFFECTS", - 2: "IDEMPOTENT", -} -var MethodOptions_IdempotencyLevel_value = map[string]int32{ - "IDEMPOTENCY_UNKNOWN": 0, - "NO_SIDE_EFFECTS": 1, - "IDEMPOTENT": 2, -} - -func (x MethodOptions_IdempotencyLevel) Enum() *MethodOptions_IdempotencyLevel { - p := new(MethodOptions_IdempotencyLevel) - *p = x - return p -} -func (x MethodOptions_IdempotencyLevel) String() string { - return proto.EnumName(MethodOptions_IdempotencyLevel_name, int32(x)) -} -func (x *MethodOptions_IdempotencyLevel) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(MethodOptions_IdempotencyLevel_value, data, "MethodOptions_IdempotencyLevel") - if err != nil { - return err - } - *x = MethodOptions_IdempotencyLevel(value) - return nil -} -func (MethodOptions_IdempotencyLevel) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{17, 0} -} - -// The protocol compiler can output a FileDescriptorSet containing the .proto -// files it parses. -type FileDescriptorSet struct { - File []*FileDescriptorProto `protobuf:"bytes,1,rep,name=file" json:"file,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FileDescriptorSet) Reset() { *m = FileDescriptorSet{} } -func (m *FileDescriptorSet) String() string { return proto.CompactTextString(m) } -func (*FileDescriptorSet) ProtoMessage() {} -func (*FileDescriptorSet) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{0} -} -func (m *FileDescriptorSet) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FileDescriptorSet.Unmarshal(m, b) -} -func (m *FileDescriptorSet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FileDescriptorSet.Marshal(b, m, deterministic) -} -func (dst *FileDescriptorSet) XXX_Merge(src proto.Message) { - xxx_messageInfo_FileDescriptorSet.Merge(dst, src) -} -func (m *FileDescriptorSet) XXX_Size() int { - return xxx_messageInfo_FileDescriptorSet.Size(m) -} -func (m *FileDescriptorSet) XXX_DiscardUnknown() { - xxx_messageInfo_FileDescriptorSet.DiscardUnknown(m) -} - -var xxx_messageInfo_FileDescriptorSet proto.InternalMessageInfo - -func (m *FileDescriptorSet) GetFile() []*FileDescriptorProto { - if m != nil { - return m.File - } - return nil -} - -// Describes a complete .proto file. -type FileDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Package *string `protobuf:"bytes,2,opt,name=package" json:"package,omitempty"` - // Names of files imported by this file. - Dependency []string `protobuf:"bytes,3,rep,name=dependency" json:"dependency,omitempty"` - // Indexes of the public imported files in the dependency list above. - PublicDependency []int32 `protobuf:"varint,10,rep,name=public_dependency,json=publicDependency" json:"public_dependency,omitempty"` - // Indexes of the weak imported files in the dependency list. - // For Google-internal migration only. Do not use. - WeakDependency []int32 `protobuf:"varint,11,rep,name=weak_dependency,json=weakDependency" json:"weak_dependency,omitempty"` - // All top-level definitions in this file. - MessageType []*DescriptorProto `protobuf:"bytes,4,rep,name=message_type,json=messageType" json:"message_type,omitempty"` - EnumType []*EnumDescriptorProto `protobuf:"bytes,5,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"` - Service []*ServiceDescriptorProto `protobuf:"bytes,6,rep,name=service" json:"service,omitempty"` - Extension []*FieldDescriptorProto `protobuf:"bytes,7,rep,name=extension" json:"extension,omitempty"` - Options *FileOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` - // This field contains optional information about the original source code. - // You may safely remove this entire field without harming runtime - // functionality of the descriptors -- the information is needed only by - // development tools. - SourceCodeInfo *SourceCodeInfo `protobuf:"bytes,9,opt,name=source_code_info,json=sourceCodeInfo" json:"source_code_info,omitempty"` - // The syntax of the proto file. - // The supported values are "proto2" and "proto3". - Syntax *string `protobuf:"bytes,12,opt,name=syntax" json:"syntax,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FileDescriptorProto) Reset() { *m = FileDescriptorProto{} } -func (m *FileDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*FileDescriptorProto) ProtoMessage() {} -func (*FileDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{1} -} -func (m *FileDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FileDescriptorProto.Unmarshal(m, b) -} -func (m *FileDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FileDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *FileDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_FileDescriptorProto.Merge(dst, src) -} -func (m *FileDescriptorProto) XXX_Size() int { - return xxx_messageInfo_FileDescriptorProto.Size(m) -} -func (m *FileDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_FileDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_FileDescriptorProto proto.InternalMessageInfo - -func (m *FileDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *FileDescriptorProto) GetPackage() string { - if m != nil && m.Package != nil { - return *m.Package - } - return "" -} - -func (m *FileDescriptorProto) GetDependency() []string { - if m != nil { - return m.Dependency - } - return nil -} - -func (m *FileDescriptorProto) GetPublicDependency() []int32 { - if m != nil { - return m.PublicDependency - } - return nil -} - -func (m *FileDescriptorProto) GetWeakDependency() []int32 { - if m != nil { - return m.WeakDependency - } - return nil -} - -func (m *FileDescriptorProto) GetMessageType() []*DescriptorProto { - if m != nil { - return m.MessageType - } - return nil -} - -func (m *FileDescriptorProto) GetEnumType() []*EnumDescriptorProto { - if m != nil { - return m.EnumType - } - return nil -} - -func (m *FileDescriptorProto) GetService() []*ServiceDescriptorProto { - if m != nil { - return m.Service - } - return nil -} - -func (m *FileDescriptorProto) GetExtension() []*FieldDescriptorProto { - if m != nil { - return m.Extension - } - return nil -} - -func (m *FileDescriptorProto) GetOptions() *FileOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *FileDescriptorProto) GetSourceCodeInfo() *SourceCodeInfo { - if m != nil { - return m.SourceCodeInfo - } - return nil -} - -func (m *FileDescriptorProto) GetSyntax() string { - if m != nil && m.Syntax != nil { - return *m.Syntax - } - return "" -} - -// Describes a message type. -type DescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Field []*FieldDescriptorProto `protobuf:"bytes,2,rep,name=field" json:"field,omitempty"` - Extension []*FieldDescriptorProto `protobuf:"bytes,6,rep,name=extension" json:"extension,omitempty"` - NestedType []*DescriptorProto `protobuf:"bytes,3,rep,name=nested_type,json=nestedType" json:"nested_type,omitempty"` - EnumType []*EnumDescriptorProto `protobuf:"bytes,4,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"` - ExtensionRange []*DescriptorProto_ExtensionRange `protobuf:"bytes,5,rep,name=extension_range,json=extensionRange" json:"extension_range,omitempty"` - OneofDecl []*OneofDescriptorProto `protobuf:"bytes,8,rep,name=oneof_decl,json=oneofDecl" json:"oneof_decl,omitempty"` - Options *MessageOptions `protobuf:"bytes,7,opt,name=options" json:"options,omitempty"` - ReservedRange []*DescriptorProto_ReservedRange `protobuf:"bytes,9,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"` - // Reserved field names, which may not be used by fields in the same message. - // A given name may only be reserved once. - ReservedName []string `protobuf:"bytes,10,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DescriptorProto) Reset() { *m = DescriptorProto{} } -func (m *DescriptorProto) String() string { return proto.CompactTextString(m) } -func (*DescriptorProto) ProtoMessage() {} -func (*DescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{2} -} -func (m *DescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DescriptorProto.Unmarshal(m, b) -} -func (m *DescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DescriptorProto.Marshal(b, m, deterministic) -} -func (dst *DescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_DescriptorProto.Merge(dst, src) -} -func (m *DescriptorProto) XXX_Size() int { - return xxx_messageInfo_DescriptorProto.Size(m) -} -func (m *DescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_DescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_DescriptorProto proto.InternalMessageInfo - -func (m *DescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *DescriptorProto) GetField() []*FieldDescriptorProto { - if m != nil { - return m.Field - } - return nil -} - -func (m *DescriptorProto) GetExtension() []*FieldDescriptorProto { - if m != nil { - return m.Extension - } - return nil -} - -func (m *DescriptorProto) GetNestedType() []*DescriptorProto { - if m != nil { - return m.NestedType - } - return nil -} - -func (m *DescriptorProto) GetEnumType() []*EnumDescriptorProto { - if m != nil { - return m.EnumType - } - return nil -} - -func (m *DescriptorProto) GetExtensionRange() []*DescriptorProto_ExtensionRange { - if m != nil { - return m.ExtensionRange - } - return nil -} - -func (m *DescriptorProto) GetOneofDecl() []*OneofDescriptorProto { - if m != nil { - return m.OneofDecl - } - return nil -} - -func (m *DescriptorProto) GetOptions() *MessageOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *DescriptorProto) GetReservedRange() []*DescriptorProto_ReservedRange { - if m != nil { - return m.ReservedRange - } - return nil -} - -func (m *DescriptorProto) GetReservedName() []string { - if m != nil { - return m.ReservedName - } - return nil -} - -type DescriptorProto_ExtensionRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - Options *ExtensionRangeOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DescriptorProto_ExtensionRange) Reset() { *m = DescriptorProto_ExtensionRange{} } -func (m *DescriptorProto_ExtensionRange) String() string { return proto.CompactTextString(m) } -func (*DescriptorProto_ExtensionRange) ProtoMessage() {} -func (*DescriptorProto_ExtensionRange) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{2, 0} -} -func (m *DescriptorProto_ExtensionRange) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DescriptorProto_ExtensionRange.Unmarshal(m, b) -} -func (m *DescriptorProto_ExtensionRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DescriptorProto_ExtensionRange.Marshal(b, m, deterministic) -} -func (dst *DescriptorProto_ExtensionRange) XXX_Merge(src proto.Message) { - xxx_messageInfo_DescriptorProto_ExtensionRange.Merge(dst, src) -} -func (m *DescriptorProto_ExtensionRange) XXX_Size() int { - return xxx_messageInfo_DescriptorProto_ExtensionRange.Size(m) -} -func (m *DescriptorProto_ExtensionRange) XXX_DiscardUnknown() { - xxx_messageInfo_DescriptorProto_ExtensionRange.DiscardUnknown(m) -} - -var xxx_messageInfo_DescriptorProto_ExtensionRange proto.InternalMessageInfo - -func (m *DescriptorProto_ExtensionRange) GetStart() int32 { - if m != nil && m.Start != nil { - return *m.Start - } - return 0 -} - -func (m *DescriptorProto_ExtensionRange) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -func (m *DescriptorProto_ExtensionRange) GetOptions() *ExtensionRangeOptions { - if m != nil { - return m.Options - } - return nil -} - -// Range of reserved tag numbers. Reserved tag numbers may not be used by -// fields or extension ranges in the same message. Reserved ranges may -// not overlap. -type DescriptorProto_ReservedRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DescriptorProto_ReservedRange) Reset() { *m = DescriptorProto_ReservedRange{} } -func (m *DescriptorProto_ReservedRange) String() string { return proto.CompactTextString(m) } -func (*DescriptorProto_ReservedRange) ProtoMessage() {} -func (*DescriptorProto_ReservedRange) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{2, 1} -} -func (m *DescriptorProto_ReservedRange) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DescriptorProto_ReservedRange.Unmarshal(m, b) -} -func (m *DescriptorProto_ReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DescriptorProto_ReservedRange.Marshal(b, m, deterministic) -} -func (dst *DescriptorProto_ReservedRange) XXX_Merge(src proto.Message) { - xxx_messageInfo_DescriptorProto_ReservedRange.Merge(dst, src) -} -func (m *DescriptorProto_ReservedRange) XXX_Size() int { - return xxx_messageInfo_DescriptorProto_ReservedRange.Size(m) -} -func (m *DescriptorProto_ReservedRange) XXX_DiscardUnknown() { - xxx_messageInfo_DescriptorProto_ReservedRange.DiscardUnknown(m) -} - -var xxx_messageInfo_DescriptorProto_ReservedRange proto.InternalMessageInfo - -func (m *DescriptorProto_ReservedRange) GetStart() int32 { - if m != nil && m.Start != nil { - return *m.Start - } - return 0 -} - -func (m *DescriptorProto_ReservedRange) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -type ExtensionRangeOptions struct { - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ExtensionRangeOptions) Reset() { *m = ExtensionRangeOptions{} } -func (m *ExtensionRangeOptions) String() string { return proto.CompactTextString(m) } -func (*ExtensionRangeOptions) ProtoMessage() {} -func (*ExtensionRangeOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{3} -} - -var extRange_ExtensionRangeOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*ExtensionRangeOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_ExtensionRangeOptions -} -func (m *ExtensionRangeOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ExtensionRangeOptions.Unmarshal(m, b) -} -func (m *ExtensionRangeOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ExtensionRangeOptions.Marshal(b, m, deterministic) -} -func (dst *ExtensionRangeOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_ExtensionRangeOptions.Merge(dst, src) -} -func (m *ExtensionRangeOptions) XXX_Size() int { - return xxx_messageInfo_ExtensionRangeOptions.Size(m) -} -func (m *ExtensionRangeOptions) XXX_DiscardUnknown() { - xxx_messageInfo_ExtensionRangeOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_ExtensionRangeOptions proto.InternalMessageInfo - -func (m *ExtensionRangeOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -// Describes a field within a message. -type FieldDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Number *int32 `protobuf:"varint,3,opt,name=number" json:"number,omitempty"` - Label *FieldDescriptorProto_Label `protobuf:"varint,4,opt,name=label,enum=google.protobuf.FieldDescriptorProto_Label" json:"label,omitempty"` - // If type_name is set, this need not be set. If both this and type_name - // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. - Type *FieldDescriptorProto_Type `protobuf:"varint,5,opt,name=type,enum=google.protobuf.FieldDescriptorProto_Type" json:"type,omitempty"` - // For message and enum types, this is the name of the type. If the name - // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping - // rules are used to find the type (i.e. first the nested types within this - // message are searched, then within the parent, on up to the root - // namespace). - TypeName *string `protobuf:"bytes,6,opt,name=type_name,json=typeName" json:"type_name,omitempty"` - // For extensions, this is the name of the type being extended. It is - // resolved in the same manner as type_name. - Extendee *string `protobuf:"bytes,2,opt,name=extendee" json:"extendee,omitempty"` - // For numeric types, contains the original text representation of the value. - // For booleans, "true" or "false". - // For strings, contains the default text contents (not escaped in any way). - // For bytes, contains the C escaped value. All bytes >= 128 are escaped. - // TODO(kenton): Base-64 encode? - DefaultValue *string `protobuf:"bytes,7,opt,name=default_value,json=defaultValue" json:"default_value,omitempty"` - // If set, gives the index of a oneof in the containing type's oneof_decl - // list. This field is a member of that oneof. - OneofIndex *int32 `protobuf:"varint,9,opt,name=oneof_index,json=oneofIndex" json:"oneof_index,omitempty"` - // JSON name of this field. The value is set by protocol compiler. If the - // user has set a "json_name" option on this field, that option's value - // will be used. Otherwise, it's deduced from the field's name by converting - // it to camelCase. - JsonName *string `protobuf:"bytes,10,opt,name=json_name,json=jsonName" json:"json_name,omitempty"` - Options *FieldOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FieldDescriptorProto) Reset() { *m = FieldDescriptorProto{} } -func (m *FieldDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*FieldDescriptorProto) ProtoMessage() {} -func (*FieldDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{4} -} -func (m *FieldDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FieldDescriptorProto.Unmarshal(m, b) -} -func (m *FieldDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FieldDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *FieldDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_FieldDescriptorProto.Merge(dst, src) -} -func (m *FieldDescriptorProto) XXX_Size() int { - return xxx_messageInfo_FieldDescriptorProto.Size(m) -} -func (m *FieldDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_FieldDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_FieldDescriptorProto proto.InternalMessageInfo - -func (m *FieldDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *FieldDescriptorProto) GetNumber() int32 { - if m != nil && m.Number != nil { - return *m.Number - } - return 0 -} - -func (m *FieldDescriptorProto) GetLabel() FieldDescriptorProto_Label { - if m != nil && m.Label != nil { - return *m.Label - } - return FieldDescriptorProto_LABEL_OPTIONAL -} - -func (m *FieldDescriptorProto) GetType() FieldDescriptorProto_Type { - if m != nil && m.Type != nil { - return *m.Type - } - return FieldDescriptorProto_TYPE_DOUBLE -} - -func (m *FieldDescriptorProto) GetTypeName() string { - if m != nil && m.TypeName != nil { - return *m.TypeName - } - return "" -} - -func (m *FieldDescriptorProto) GetExtendee() string { - if m != nil && m.Extendee != nil { - return *m.Extendee - } - return "" -} - -func (m *FieldDescriptorProto) GetDefaultValue() string { - if m != nil && m.DefaultValue != nil { - return *m.DefaultValue - } - return "" -} - -func (m *FieldDescriptorProto) GetOneofIndex() int32 { - if m != nil && m.OneofIndex != nil { - return *m.OneofIndex - } - return 0 -} - -func (m *FieldDescriptorProto) GetJsonName() string { - if m != nil && m.JsonName != nil { - return *m.JsonName - } - return "" -} - -func (m *FieldDescriptorProto) GetOptions() *FieldOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes a oneof. -type OneofDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Options *OneofOptions `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *OneofDescriptorProto) Reset() { *m = OneofDescriptorProto{} } -func (m *OneofDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*OneofDescriptorProto) ProtoMessage() {} -func (*OneofDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{5} -} -func (m *OneofDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OneofDescriptorProto.Unmarshal(m, b) -} -func (m *OneofDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OneofDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *OneofDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_OneofDescriptorProto.Merge(dst, src) -} -func (m *OneofDescriptorProto) XXX_Size() int { - return xxx_messageInfo_OneofDescriptorProto.Size(m) -} -func (m *OneofDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_OneofDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_OneofDescriptorProto proto.InternalMessageInfo - -func (m *OneofDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *OneofDescriptorProto) GetOptions() *OneofOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes an enum type. -type EnumDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Value []*EnumValueDescriptorProto `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"` - Options *EnumOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - // Range of reserved numeric values. Reserved numeric values may not be used - // by enum values in the same enum declaration. Reserved ranges may not - // overlap. - ReservedRange []*EnumDescriptorProto_EnumReservedRange `protobuf:"bytes,4,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"` - // Reserved enum value names, which may not be reused. A given name may only - // be reserved once. - ReservedName []string `protobuf:"bytes,5,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumDescriptorProto) Reset() { *m = EnumDescriptorProto{} } -func (m *EnumDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*EnumDescriptorProto) ProtoMessage() {} -func (*EnumDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{6} -} -func (m *EnumDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumDescriptorProto.Unmarshal(m, b) -} -func (m *EnumDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *EnumDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumDescriptorProto.Merge(dst, src) -} -func (m *EnumDescriptorProto) XXX_Size() int { - return xxx_messageInfo_EnumDescriptorProto.Size(m) -} -func (m *EnumDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_EnumDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumDescriptorProto proto.InternalMessageInfo - -func (m *EnumDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *EnumDescriptorProto) GetValue() []*EnumValueDescriptorProto { - if m != nil { - return m.Value - } - return nil -} - -func (m *EnumDescriptorProto) GetOptions() *EnumOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *EnumDescriptorProto) GetReservedRange() []*EnumDescriptorProto_EnumReservedRange { - if m != nil { - return m.ReservedRange - } - return nil -} - -func (m *EnumDescriptorProto) GetReservedName() []string { - if m != nil { - return m.ReservedName - } - return nil -} - -// Range of reserved numeric values. Reserved values may not be used by -// entries in the same enum. Reserved ranges may not overlap. -// -// Note that this is distinct from DescriptorProto.ReservedRange in that it -// is inclusive such that it can appropriately represent the entire int32 -// domain. -type EnumDescriptorProto_EnumReservedRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumDescriptorProto_EnumReservedRange) Reset() { *m = EnumDescriptorProto_EnumReservedRange{} } -func (m *EnumDescriptorProto_EnumReservedRange) String() string { return proto.CompactTextString(m) } -func (*EnumDescriptorProto_EnumReservedRange) ProtoMessage() {} -func (*EnumDescriptorProto_EnumReservedRange) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{6, 0} -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Unmarshal(m, b) -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Marshal(b, m, deterministic) -} -func (dst *EnumDescriptorProto_EnumReservedRange) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Merge(dst, src) -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_Size() int { - return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Size(m) -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_DiscardUnknown() { - xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumDescriptorProto_EnumReservedRange proto.InternalMessageInfo - -func (m *EnumDescriptorProto_EnumReservedRange) GetStart() int32 { - if m != nil && m.Start != nil { - return *m.Start - } - return 0 -} - -func (m *EnumDescriptorProto_EnumReservedRange) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -// Describes a value within an enum. -type EnumValueDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Number *int32 `protobuf:"varint,2,opt,name=number" json:"number,omitempty"` - Options *EnumValueOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumValueDescriptorProto) Reset() { *m = EnumValueDescriptorProto{} } -func (m *EnumValueDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*EnumValueDescriptorProto) ProtoMessage() {} -func (*EnumValueDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{7} -} -func (m *EnumValueDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumValueDescriptorProto.Unmarshal(m, b) -} -func (m *EnumValueDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumValueDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *EnumValueDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumValueDescriptorProto.Merge(dst, src) -} -func (m *EnumValueDescriptorProto) XXX_Size() int { - return xxx_messageInfo_EnumValueDescriptorProto.Size(m) -} -func (m *EnumValueDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_EnumValueDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumValueDescriptorProto proto.InternalMessageInfo - -func (m *EnumValueDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *EnumValueDescriptorProto) GetNumber() int32 { - if m != nil && m.Number != nil { - return *m.Number - } - return 0 -} - -func (m *EnumValueDescriptorProto) GetOptions() *EnumValueOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes a service. -type ServiceDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Method []*MethodDescriptorProto `protobuf:"bytes,2,rep,name=method" json:"method,omitempty"` - Options *ServiceOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServiceDescriptorProto) Reset() { *m = ServiceDescriptorProto{} } -func (m *ServiceDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*ServiceDescriptorProto) ProtoMessage() {} -func (*ServiceDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{8} -} -func (m *ServiceDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServiceDescriptorProto.Unmarshal(m, b) -} -func (m *ServiceDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServiceDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *ServiceDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServiceDescriptorProto.Merge(dst, src) -} -func (m *ServiceDescriptorProto) XXX_Size() int { - return xxx_messageInfo_ServiceDescriptorProto.Size(m) -} -func (m *ServiceDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_ServiceDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_ServiceDescriptorProto proto.InternalMessageInfo - -func (m *ServiceDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *ServiceDescriptorProto) GetMethod() []*MethodDescriptorProto { - if m != nil { - return m.Method - } - return nil -} - -func (m *ServiceDescriptorProto) GetOptions() *ServiceOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes a method of a service. -type MethodDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - // Input and output type names. These are resolved in the same way as - // FieldDescriptorProto.type_name, but must refer to a message type. - InputType *string `protobuf:"bytes,2,opt,name=input_type,json=inputType" json:"input_type,omitempty"` - OutputType *string `protobuf:"bytes,3,opt,name=output_type,json=outputType" json:"output_type,omitempty"` - Options *MethodOptions `protobuf:"bytes,4,opt,name=options" json:"options,omitempty"` - // Identifies if client streams multiple client messages - ClientStreaming *bool `protobuf:"varint,5,opt,name=client_streaming,json=clientStreaming,def=0" json:"client_streaming,omitempty"` - // Identifies if server streams multiple server messages - ServerStreaming *bool `protobuf:"varint,6,opt,name=server_streaming,json=serverStreaming,def=0" json:"server_streaming,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MethodDescriptorProto) Reset() { *m = MethodDescriptorProto{} } -func (m *MethodDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*MethodDescriptorProto) ProtoMessage() {} -func (*MethodDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{9} -} -func (m *MethodDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MethodDescriptorProto.Unmarshal(m, b) -} -func (m *MethodDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MethodDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *MethodDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_MethodDescriptorProto.Merge(dst, src) -} -func (m *MethodDescriptorProto) XXX_Size() int { - return xxx_messageInfo_MethodDescriptorProto.Size(m) -} -func (m *MethodDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_MethodDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_MethodDescriptorProto proto.InternalMessageInfo - -const Default_MethodDescriptorProto_ClientStreaming bool = false -const Default_MethodDescriptorProto_ServerStreaming bool = false - -func (m *MethodDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *MethodDescriptorProto) GetInputType() string { - if m != nil && m.InputType != nil { - return *m.InputType - } - return "" -} - -func (m *MethodDescriptorProto) GetOutputType() string { - if m != nil && m.OutputType != nil { - return *m.OutputType - } - return "" -} - -func (m *MethodDescriptorProto) GetOptions() *MethodOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *MethodDescriptorProto) GetClientStreaming() bool { - if m != nil && m.ClientStreaming != nil { - return *m.ClientStreaming - } - return Default_MethodDescriptorProto_ClientStreaming -} - -func (m *MethodDescriptorProto) GetServerStreaming() bool { - if m != nil && m.ServerStreaming != nil { - return *m.ServerStreaming - } - return Default_MethodDescriptorProto_ServerStreaming -} - -type FileOptions struct { - // Sets the Java package where classes generated from this .proto will be - // placed. By default, the proto package is used, but this is often - // inappropriate because proto packages do not normally start with backwards - // domain names. - JavaPackage *string `protobuf:"bytes,1,opt,name=java_package,json=javaPackage" json:"java_package,omitempty"` - // If set, all the classes from the .proto file are wrapped in a single - // outer class with the given name. This applies to both Proto1 - // (equivalent to the old "--one_java_file" option) and Proto2 (where - // a .proto always translates to a single class, but you may want to - // explicitly choose the class name). - JavaOuterClassname *string `protobuf:"bytes,8,opt,name=java_outer_classname,json=javaOuterClassname" json:"java_outer_classname,omitempty"` - // If set true, then the Java code generator will generate a separate .java - // file for each top-level message, enum, and service defined in the .proto - // file. Thus, these types will *not* be nested inside the outer class - // named by java_outer_classname. However, the outer class will still be - // generated to contain the file's getDescriptor() method as well as any - // top-level extensions defined in the file. - JavaMultipleFiles *bool `protobuf:"varint,10,opt,name=java_multiple_files,json=javaMultipleFiles,def=0" json:"java_multiple_files,omitempty"` - // This option does nothing. - JavaGenerateEqualsAndHash *bool `protobuf:"varint,20,opt,name=java_generate_equals_and_hash,json=javaGenerateEqualsAndHash" json:"java_generate_equals_and_hash,omitempty"` // Deprecated: Do not use. - // If set true, then the Java2 code generator will generate code that - // throws an exception whenever an attempt is made to assign a non-UTF-8 - // byte sequence to a string field. - // Message reflection will do the same. - // However, an extension field still accepts non-UTF-8 byte sequences. - // This option has no effect on when used with the lite runtime. - JavaStringCheckUtf8 *bool `protobuf:"varint,27,opt,name=java_string_check_utf8,json=javaStringCheckUtf8,def=0" json:"java_string_check_utf8,omitempty"` - OptimizeFor *FileOptions_OptimizeMode `protobuf:"varint,9,opt,name=optimize_for,json=optimizeFor,enum=google.protobuf.FileOptions_OptimizeMode,def=1" json:"optimize_for,omitempty"` - // Sets the Go package where structs generated from this .proto will be - // placed. If omitted, the Go package will be derived from the following: - // - The basename of the package import path, if provided. - // - Otherwise, the package statement in the .proto file, if present. - // - Otherwise, the basename of the .proto file, without extension. - GoPackage *string `protobuf:"bytes,11,opt,name=go_package,json=goPackage" json:"go_package,omitempty"` - // Should generic services be generated in each language? "Generic" services - // are not specific to any particular RPC system. They are generated by the - // main code generators in each language (without additional plugins). - // Generic services were the only kind of service generation supported by - // early versions of google.protobuf. - // - // Generic services are now considered deprecated in favor of using plugins - // that generate code specific to your particular RPC system. Therefore, - // these default to false. Old code which depends on generic services should - // explicitly set them to true. - CcGenericServices *bool `protobuf:"varint,16,opt,name=cc_generic_services,json=ccGenericServices,def=0" json:"cc_generic_services,omitempty"` - JavaGenericServices *bool `protobuf:"varint,17,opt,name=java_generic_services,json=javaGenericServices,def=0" json:"java_generic_services,omitempty"` - PyGenericServices *bool `protobuf:"varint,18,opt,name=py_generic_services,json=pyGenericServices,def=0" json:"py_generic_services,omitempty"` - PhpGenericServices *bool `protobuf:"varint,42,opt,name=php_generic_services,json=phpGenericServices,def=0" json:"php_generic_services,omitempty"` - // Is this file deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for everything in the file, or it will be completely ignored; in the very - // least, this is a formalization for deprecating files. - Deprecated *bool `protobuf:"varint,23,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // Enables the use of arenas for the proto messages in this file. This applies - // only to generated classes for C++. - CcEnableArenas *bool `protobuf:"varint,31,opt,name=cc_enable_arenas,json=ccEnableArenas,def=0" json:"cc_enable_arenas,omitempty"` - // Sets the objective c class prefix which is prepended to all objective c - // generated classes from this .proto. There is no default. - ObjcClassPrefix *string `protobuf:"bytes,36,opt,name=objc_class_prefix,json=objcClassPrefix" json:"objc_class_prefix,omitempty"` - // Namespace for generated classes; defaults to the package. - CsharpNamespace *string `protobuf:"bytes,37,opt,name=csharp_namespace,json=csharpNamespace" json:"csharp_namespace,omitempty"` - // By default Swift generators will take the proto package and CamelCase it - // replacing '.' with underscore and use that to prefix the types/symbols - // defined. When this options is provided, they will use this value instead - // to prefix the types/symbols defined. - SwiftPrefix *string `protobuf:"bytes,39,opt,name=swift_prefix,json=swiftPrefix" json:"swift_prefix,omitempty"` - // Sets the php class prefix which is prepended to all php generated classes - // from this .proto. Default is empty. - PhpClassPrefix *string `protobuf:"bytes,40,opt,name=php_class_prefix,json=phpClassPrefix" json:"php_class_prefix,omitempty"` - // Use this option to change the namespace of php generated classes. Default - // is empty. When this option is empty, the package name will be used for - // determining the namespace. - PhpNamespace *string `protobuf:"bytes,41,opt,name=php_namespace,json=phpNamespace" json:"php_namespace,omitempty"` - // The parser stores options it doesn't recognize here. - // See the documentation for the "Options" section above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FileOptions) Reset() { *m = FileOptions{} } -func (m *FileOptions) String() string { return proto.CompactTextString(m) } -func (*FileOptions) ProtoMessage() {} -func (*FileOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{10} -} - -var extRange_FileOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*FileOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_FileOptions -} -func (m *FileOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FileOptions.Unmarshal(m, b) -} -func (m *FileOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FileOptions.Marshal(b, m, deterministic) -} -func (dst *FileOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_FileOptions.Merge(dst, src) -} -func (m *FileOptions) XXX_Size() int { - return xxx_messageInfo_FileOptions.Size(m) -} -func (m *FileOptions) XXX_DiscardUnknown() { - xxx_messageInfo_FileOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_FileOptions proto.InternalMessageInfo - -const Default_FileOptions_JavaMultipleFiles bool = false -const Default_FileOptions_JavaStringCheckUtf8 bool = false -const Default_FileOptions_OptimizeFor FileOptions_OptimizeMode = FileOptions_SPEED -const Default_FileOptions_CcGenericServices bool = false -const Default_FileOptions_JavaGenericServices bool = false -const Default_FileOptions_PyGenericServices bool = false -const Default_FileOptions_PhpGenericServices bool = false -const Default_FileOptions_Deprecated bool = false -const Default_FileOptions_CcEnableArenas bool = false - -func (m *FileOptions) GetJavaPackage() string { - if m != nil && m.JavaPackage != nil { - return *m.JavaPackage - } - return "" -} - -func (m *FileOptions) GetJavaOuterClassname() string { - if m != nil && m.JavaOuterClassname != nil { - return *m.JavaOuterClassname - } - return "" -} - -func (m *FileOptions) GetJavaMultipleFiles() bool { - if m != nil && m.JavaMultipleFiles != nil { - return *m.JavaMultipleFiles - } - return Default_FileOptions_JavaMultipleFiles -} - -// Deprecated: Do not use. -func (m *FileOptions) GetJavaGenerateEqualsAndHash() bool { - if m != nil && m.JavaGenerateEqualsAndHash != nil { - return *m.JavaGenerateEqualsAndHash - } - return false -} - -func (m *FileOptions) GetJavaStringCheckUtf8() bool { - if m != nil && m.JavaStringCheckUtf8 != nil { - return *m.JavaStringCheckUtf8 - } - return Default_FileOptions_JavaStringCheckUtf8 -} - -func (m *FileOptions) GetOptimizeFor() FileOptions_OptimizeMode { - if m != nil && m.OptimizeFor != nil { - return *m.OptimizeFor - } - return Default_FileOptions_OptimizeFor -} - -func (m *FileOptions) GetGoPackage() string { - if m != nil && m.GoPackage != nil { - return *m.GoPackage - } - return "" -} - -func (m *FileOptions) GetCcGenericServices() bool { - if m != nil && m.CcGenericServices != nil { - return *m.CcGenericServices - } - return Default_FileOptions_CcGenericServices -} - -func (m *FileOptions) GetJavaGenericServices() bool { - if m != nil && m.JavaGenericServices != nil { - return *m.JavaGenericServices - } - return Default_FileOptions_JavaGenericServices -} - -func (m *FileOptions) GetPyGenericServices() bool { - if m != nil && m.PyGenericServices != nil { - return *m.PyGenericServices - } - return Default_FileOptions_PyGenericServices -} - -func (m *FileOptions) GetPhpGenericServices() bool { - if m != nil && m.PhpGenericServices != nil { - return *m.PhpGenericServices - } - return Default_FileOptions_PhpGenericServices -} - -func (m *FileOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_FileOptions_Deprecated -} - -func (m *FileOptions) GetCcEnableArenas() bool { - if m != nil && m.CcEnableArenas != nil { - return *m.CcEnableArenas - } - return Default_FileOptions_CcEnableArenas -} - -func (m *FileOptions) GetObjcClassPrefix() string { - if m != nil && m.ObjcClassPrefix != nil { - return *m.ObjcClassPrefix - } - return "" -} - -func (m *FileOptions) GetCsharpNamespace() string { - if m != nil && m.CsharpNamespace != nil { - return *m.CsharpNamespace - } - return "" -} - -func (m *FileOptions) GetSwiftPrefix() string { - if m != nil && m.SwiftPrefix != nil { - return *m.SwiftPrefix - } - return "" -} - -func (m *FileOptions) GetPhpClassPrefix() string { - if m != nil && m.PhpClassPrefix != nil { - return *m.PhpClassPrefix - } - return "" -} - -func (m *FileOptions) GetPhpNamespace() string { - if m != nil && m.PhpNamespace != nil { - return *m.PhpNamespace - } - return "" -} - -func (m *FileOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type MessageOptions struct { - // Set true to use the old proto1 MessageSet wire format for extensions. - // This is provided for backwards-compatibility with the MessageSet wire - // format. You should not use this for any other reason: It's less - // efficient, has fewer features, and is more complicated. - // - // The message must be defined exactly as follows: - // message Foo { - // option message_set_wire_format = true; - // extensions 4 to max; - // } - // Note that the message cannot have any defined fields; MessageSets only - // have extensions. - // - // All extensions of your type must be singular messages; e.g. they cannot - // be int32s, enums, or repeated messages. - // - // Because this is an option, the above two restrictions are not enforced by - // the protocol compiler. - MessageSetWireFormat *bool `protobuf:"varint,1,opt,name=message_set_wire_format,json=messageSetWireFormat,def=0" json:"message_set_wire_format,omitempty"` - // Disables the generation of the standard "descriptor()" accessor, which can - // conflict with a field of the same name. This is meant to make migration - // from proto1 easier; new code should avoid fields named "descriptor". - NoStandardDescriptorAccessor *bool `protobuf:"varint,2,opt,name=no_standard_descriptor_accessor,json=noStandardDescriptorAccessor,def=0" json:"no_standard_descriptor_accessor,omitempty"` - // Is this message deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the message, or it will be completely ignored; in the very least, - // this is a formalization for deprecating messages. - Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // Whether the message is an automatically generated map entry type for the - // maps field. - // - // For maps fields: - // map map_field = 1; - // The parsed descriptor looks like: - // message MapFieldEntry { - // option map_entry = true; - // optional KeyType key = 1; - // optional ValueType value = 2; - // } - // repeated MapFieldEntry map_field = 1; - // - // Implementations may choose not to generate the map_entry=true message, but - // use a native map in the target language to hold the keys and values. - // The reflection APIs in such implementions still need to work as - // if the field is a repeated message field. - // - // NOTE: Do not set the option in .proto files. Always use the maps syntax - // instead. The option should only be implicitly set by the proto compiler - // parser. - MapEntry *bool `protobuf:"varint,7,opt,name=map_entry,json=mapEntry" json:"map_entry,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MessageOptions) Reset() { *m = MessageOptions{} } -func (m *MessageOptions) String() string { return proto.CompactTextString(m) } -func (*MessageOptions) ProtoMessage() {} -func (*MessageOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{11} -} - -var extRange_MessageOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*MessageOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MessageOptions -} -func (m *MessageOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MessageOptions.Unmarshal(m, b) -} -func (m *MessageOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MessageOptions.Marshal(b, m, deterministic) -} -func (dst *MessageOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_MessageOptions.Merge(dst, src) -} -func (m *MessageOptions) XXX_Size() int { - return xxx_messageInfo_MessageOptions.Size(m) -} -func (m *MessageOptions) XXX_DiscardUnknown() { - xxx_messageInfo_MessageOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_MessageOptions proto.InternalMessageInfo - -const Default_MessageOptions_MessageSetWireFormat bool = false -const Default_MessageOptions_NoStandardDescriptorAccessor bool = false -const Default_MessageOptions_Deprecated bool = false - -func (m *MessageOptions) GetMessageSetWireFormat() bool { - if m != nil && m.MessageSetWireFormat != nil { - return *m.MessageSetWireFormat - } - return Default_MessageOptions_MessageSetWireFormat -} - -func (m *MessageOptions) GetNoStandardDescriptorAccessor() bool { - if m != nil && m.NoStandardDescriptorAccessor != nil { - return *m.NoStandardDescriptorAccessor - } - return Default_MessageOptions_NoStandardDescriptorAccessor -} - -func (m *MessageOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_MessageOptions_Deprecated -} - -func (m *MessageOptions) GetMapEntry() bool { - if m != nil && m.MapEntry != nil { - return *m.MapEntry - } - return false -} - -func (m *MessageOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type FieldOptions struct { - // The ctype option instructs the C++ code generator to use a different - // representation of the field than it normally would. See the specific - // options below. This option is not yet implemented in the open source - // release -- sorry, we'll try to include it in a future version! - Ctype *FieldOptions_CType `protobuf:"varint,1,opt,name=ctype,enum=google.protobuf.FieldOptions_CType,def=0" json:"ctype,omitempty"` - // The packed option can be enabled for repeated primitive fields to enable - // a more efficient representation on the wire. Rather than repeatedly - // writing the tag and type for each element, the entire array is encoded as - // a single length-delimited blob. In proto3, only explicit setting it to - // false will avoid using packed encoding. - Packed *bool `protobuf:"varint,2,opt,name=packed" json:"packed,omitempty"` - // The jstype option determines the JavaScript type used for values of the - // field. The option is permitted only for 64 bit integral and fixed types - // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING - // is represented as JavaScript string, which avoids loss of precision that - // can happen when a large value is converted to a floating point JavaScript. - // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to - // use the JavaScript "number" type. The behavior of the default option - // JS_NORMAL is implementation dependent. - // - // This option is an enum to permit additional types to be added, e.g. - // goog.math.Integer. - Jstype *FieldOptions_JSType `protobuf:"varint,6,opt,name=jstype,enum=google.protobuf.FieldOptions_JSType,def=0" json:"jstype,omitempty"` - // Should this field be parsed lazily? Lazy applies only to message-type - // fields. It means that when the outer message is initially parsed, the - // inner message's contents will not be parsed but instead stored in encoded - // form. The inner message will actually be parsed when it is first accessed. - // - // This is only a hint. Implementations are free to choose whether to use - // eager or lazy parsing regardless of the value of this option. However, - // setting this option true suggests that the protocol author believes that - // using lazy parsing on this field is worth the additional bookkeeping - // overhead typically needed to implement it. - // - // This option does not affect the public interface of any generated code; - // all method signatures remain the same. Furthermore, thread-safety of the - // interface is not affected by this option; const methods remain safe to - // call from multiple threads concurrently, while non-const methods continue - // to require exclusive access. - // - // - // Note that implementations may choose not to check required fields within - // a lazy sub-message. That is, calling IsInitialized() on the outer message - // may return true even if the inner message has missing required fields. - // This is necessary because otherwise the inner message would have to be - // parsed in order to perform the check, defeating the purpose of lazy - // parsing. An implementation which chooses not to check required fields - // must be consistent about it. That is, for any particular sub-message, the - // implementation must either *always* check its required fields, or *never* - // check its required fields, regardless of whether or not the message has - // been parsed. - Lazy *bool `protobuf:"varint,5,opt,name=lazy,def=0" json:"lazy,omitempty"` - // Is this field deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for accessors, or it will be completely ignored; in the very least, this - // is a formalization for deprecating fields. - Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // For Google-internal migration only. Do not use. - Weak *bool `protobuf:"varint,10,opt,name=weak,def=0" json:"weak,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FieldOptions) Reset() { *m = FieldOptions{} } -func (m *FieldOptions) String() string { return proto.CompactTextString(m) } -func (*FieldOptions) ProtoMessage() {} -func (*FieldOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{12} -} - -var extRange_FieldOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*FieldOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_FieldOptions -} -func (m *FieldOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FieldOptions.Unmarshal(m, b) -} -func (m *FieldOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FieldOptions.Marshal(b, m, deterministic) -} -func (dst *FieldOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_FieldOptions.Merge(dst, src) -} -func (m *FieldOptions) XXX_Size() int { - return xxx_messageInfo_FieldOptions.Size(m) -} -func (m *FieldOptions) XXX_DiscardUnknown() { - xxx_messageInfo_FieldOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_FieldOptions proto.InternalMessageInfo - -const Default_FieldOptions_Ctype FieldOptions_CType = FieldOptions_STRING -const Default_FieldOptions_Jstype FieldOptions_JSType = FieldOptions_JS_NORMAL -const Default_FieldOptions_Lazy bool = false -const Default_FieldOptions_Deprecated bool = false -const Default_FieldOptions_Weak bool = false - -func (m *FieldOptions) GetCtype() FieldOptions_CType { - if m != nil && m.Ctype != nil { - return *m.Ctype - } - return Default_FieldOptions_Ctype -} - -func (m *FieldOptions) GetPacked() bool { - if m != nil && m.Packed != nil { - return *m.Packed - } - return false -} - -func (m *FieldOptions) GetJstype() FieldOptions_JSType { - if m != nil && m.Jstype != nil { - return *m.Jstype - } - return Default_FieldOptions_Jstype -} - -func (m *FieldOptions) GetLazy() bool { - if m != nil && m.Lazy != nil { - return *m.Lazy - } - return Default_FieldOptions_Lazy -} - -func (m *FieldOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_FieldOptions_Deprecated -} - -func (m *FieldOptions) GetWeak() bool { - if m != nil && m.Weak != nil { - return *m.Weak - } - return Default_FieldOptions_Weak -} - -func (m *FieldOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type OneofOptions struct { - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *OneofOptions) Reset() { *m = OneofOptions{} } -func (m *OneofOptions) String() string { return proto.CompactTextString(m) } -func (*OneofOptions) ProtoMessage() {} -func (*OneofOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{13} -} - -var extRange_OneofOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*OneofOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_OneofOptions -} -func (m *OneofOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OneofOptions.Unmarshal(m, b) -} -func (m *OneofOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OneofOptions.Marshal(b, m, deterministic) -} -func (dst *OneofOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_OneofOptions.Merge(dst, src) -} -func (m *OneofOptions) XXX_Size() int { - return xxx_messageInfo_OneofOptions.Size(m) -} -func (m *OneofOptions) XXX_DiscardUnknown() { - xxx_messageInfo_OneofOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_OneofOptions proto.InternalMessageInfo - -func (m *OneofOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type EnumOptions struct { - // Set this option to true to allow mapping different tag names to the same - // value. - AllowAlias *bool `protobuf:"varint,2,opt,name=allow_alias,json=allowAlias" json:"allow_alias,omitempty"` - // Is this enum deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum, or it will be completely ignored; in the very least, this - // is a formalization for deprecating enums. - Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumOptions) Reset() { *m = EnumOptions{} } -func (m *EnumOptions) String() string { return proto.CompactTextString(m) } -func (*EnumOptions) ProtoMessage() {} -func (*EnumOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{14} -} - -var extRange_EnumOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*EnumOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_EnumOptions -} -func (m *EnumOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumOptions.Unmarshal(m, b) -} -func (m *EnumOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumOptions.Marshal(b, m, deterministic) -} -func (dst *EnumOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumOptions.Merge(dst, src) -} -func (m *EnumOptions) XXX_Size() int { - return xxx_messageInfo_EnumOptions.Size(m) -} -func (m *EnumOptions) XXX_DiscardUnknown() { - xxx_messageInfo_EnumOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumOptions proto.InternalMessageInfo - -const Default_EnumOptions_Deprecated bool = false - -func (m *EnumOptions) GetAllowAlias() bool { - if m != nil && m.AllowAlias != nil { - return *m.AllowAlias - } - return false -} - -func (m *EnumOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_EnumOptions_Deprecated -} - -func (m *EnumOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type EnumValueOptions struct { - // Is this enum value deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum value, or it will be completely ignored; in the very least, - // this is a formalization for deprecating enum values. - Deprecated *bool `protobuf:"varint,1,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumValueOptions) Reset() { *m = EnumValueOptions{} } -func (m *EnumValueOptions) String() string { return proto.CompactTextString(m) } -func (*EnumValueOptions) ProtoMessage() {} -func (*EnumValueOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{15} -} - -var extRange_EnumValueOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*EnumValueOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_EnumValueOptions -} -func (m *EnumValueOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumValueOptions.Unmarshal(m, b) -} -func (m *EnumValueOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumValueOptions.Marshal(b, m, deterministic) -} -func (dst *EnumValueOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumValueOptions.Merge(dst, src) -} -func (m *EnumValueOptions) XXX_Size() int { - return xxx_messageInfo_EnumValueOptions.Size(m) -} -func (m *EnumValueOptions) XXX_DiscardUnknown() { - xxx_messageInfo_EnumValueOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumValueOptions proto.InternalMessageInfo - -const Default_EnumValueOptions_Deprecated bool = false - -func (m *EnumValueOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_EnumValueOptions_Deprecated -} - -func (m *EnumValueOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type ServiceOptions struct { - // Is this service deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the service, or it will be completely ignored; in the very least, - // this is a formalization for deprecating services. - Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServiceOptions) Reset() { *m = ServiceOptions{} } -func (m *ServiceOptions) String() string { return proto.CompactTextString(m) } -func (*ServiceOptions) ProtoMessage() {} -func (*ServiceOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{16} -} - -var extRange_ServiceOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*ServiceOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_ServiceOptions -} -func (m *ServiceOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServiceOptions.Unmarshal(m, b) -} -func (m *ServiceOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServiceOptions.Marshal(b, m, deterministic) -} -func (dst *ServiceOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServiceOptions.Merge(dst, src) -} -func (m *ServiceOptions) XXX_Size() int { - return xxx_messageInfo_ServiceOptions.Size(m) -} -func (m *ServiceOptions) XXX_DiscardUnknown() { - xxx_messageInfo_ServiceOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_ServiceOptions proto.InternalMessageInfo - -const Default_ServiceOptions_Deprecated bool = false - -func (m *ServiceOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_ServiceOptions_Deprecated -} - -func (m *ServiceOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type MethodOptions struct { - // Is this method deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the method, or it will be completely ignored; in the very least, - // this is a formalization for deprecating methods. - Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - IdempotencyLevel *MethodOptions_IdempotencyLevel `protobuf:"varint,34,opt,name=idempotency_level,json=idempotencyLevel,enum=google.protobuf.MethodOptions_IdempotencyLevel,def=0" json:"idempotency_level,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MethodOptions) Reset() { *m = MethodOptions{} } -func (m *MethodOptions) String() string { return proto.CompactTextString(m) } -func (*MethodOptions) ProtoMessage() {} -func (*MethodOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{17} -} - -var extRange_MethodOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*MethodOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MethodOptions -} -func (m *MethodOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MethodOptions.Unmarshal(m, b) -} -func (m *MethodOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MethodOptions.Marshal(b, m, deterministic) -} -func (dst *MethodOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_MethodOptions.Merge(dst, src) -} -func (m *MethodOptions) XXX_Size() int { - return xxx_messageInfo_MethodOptions.Size(m) -} -func (m *MethodOptions) XXX_DiscardUnknown() { - xxx_messageInfo_MethodOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_MethodOptions proto.InternalMessageInfo - -const Default_MethodOptions_Deprecated bool = false -const Default_MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel = MethodOptions_IDEMPOTENCY_UNKNOWN - -func (m *MethodOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_MethodOptions_Deprecated -} - -func (m *MethodOptions) GetIdempotencyLevel() MethodOptions_IdempotencyLevel { - if m != nil && m.IdempotencyLevel != nil { - return *m.IdempotencyLevel - } - return Default_MethodOptions_IdempotencyLevel -} - -func (m *MethodOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -// A message representing a option the parser does not recognize. This only -// appears in options protos created by the compiler::Parser class. -// DescriptorPool resolves these when building Descriptor objects. Therefore, -// options protos in descriptor objects (e.g. returned by Descriptor::options(), -// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions -// in them. -type UninterpretedOption struct { - Name []*UninterpretedOption_NamePart `protobuf:"bytes,2,rep,name=name" json:"name,omitempty"` - // The value of the uninterpreted option, in whatever type the tokenizer - // identified it as during parsing. Exactly one of these should be set. - IdentifierValue *string `protobuf:"bytes,3,opt,name=identifier_value,json=identifierValue" json:"identifier_value,omitempty"` - PositiveIntValue *uint64 `protobuf:"varint,4,opt,name=positive_int_value,json=positiveIntValue" json:"positive_int_value,omitempty"` - NegativeIntValue *int64 `protobuf:"varint,5,opt,name=negative_int_value,json=negativeIntValue" json:"negative_int_value,omitempty"` - DoubleValue *float64 `protobuf:"fixed64,6,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"` - StringValue []byte `protobuf:"bytes,7,opt,name=string_value,json=stringValue" json:"string_value,omitempty"` - AggregateValue *string `protobuf:"bytes,8,opt,name=aggregate_value,json=aggregateValue" json:"aggregate_value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UninterpretedOption) Reset() { *m = UninterpretedOption{} } -func (m *UninterpretedOption) String() string { return proto.CompactTextString(m) } -func (*UninterpretedOption) ProtoMessage() {} -func (*UninterpretedOption) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{18} -} -func (m *UninterpretedOption) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UninterpretedOption.Unmarshal(m, b) -} -func (m *UninterpretedOption) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UninterpretedOption.Marshal(b, m, deterministic) -} -func (dst *UninterpretedOption) XXX_Merge(src proto.Message) { - xxx_messageInfo_UninterpretedOption.Merge(dst, src) -} -func (m *UninterpretedOption) XXX_Size() int { - return xxx_messageInfo_UninterpretedOption.Size(m) -} -func (m *UninterpretedOption) XXX_DiscardUnknown() { - xxx_messageInfo_UninterpretedOption.DiscardUnknown(m) -} - -var xxx_messageInfo_UninterpretedOption proto.InternalMessageInfo - -func (m *UninterpretedOption) GetName() []*UninterpretedOption_NamePart { - if m != nil { - return m.Name - } - return nil -} - -func (m *UninterpretedOption) GetIdentifierValue() string { - if m != nil && m.IdentifierValue != nil { - return *m.IdentifierValue - } - return "" -} - -func (m *UninterpretedOption) GetPositiveIntValue() uint64 { - if m != nil && m.PositiveIntValue != nil { - return *m.PositiveIntValue - } - return 0 -} - -func (m *UninterpretedOption) GetNegativeIntValue() int64 { - if m != nil && m.NegativeIntValue != nil { - return *m.NegativeIntValue - } - return 0 -} - -func (m *UninterpretedOption) GetDoubleValue() float64 { - if m != nil && m.DoubleValue != nil { - return *m.DoubleValue - } - return 0 -} - -func (m *UninterpretedOption) GetStringValue() []byte { - if m != nil { - return m.StringValue - } - return nil -} - -func (m *UninterpretedOption) GetAggregateValue() string { - if m != nil && m.AggregateValue != nil { - return *m.AggregateValue - } - return "" -} - -// The name of the uninterpreted option. Each string represents a segment in -// a dot-separated name. is_extension is true iff a segment represents an -// extension (denoted with parentheses in options specs in .proto files). -// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents -// "foo.(bar.baz).qux". -type UninterpretedOption_NamePart struct { - NamePart *string `protobuf:"bytes,1,req,name=name_part,json=namePart" json:"name_part,omitempty"` - IsExtension *bool `protobuf:"varint,2,req,name=is_extension,json=isExtension" json:"is_extension,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UninterpretedOption_NamePart) Reset() { *m = UninterpretedOption_NamePart{} } -func (m *UninterpretedOption_NamePart) String() string { return proto.CompactTextString(m) } -func (*UninterpretedOption_NamePart) ProtoMessage() {} -func (*UninterpretedOption_NamePart) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{18, 0} -} -func (m *UninterpretedOption_NamePart) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UninterpretedOption_NamePart.Unmarshal(m, b) -} -func (m *UninterpretedOption_NamePart) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UninterpretedOption_NamePart.Marshal(b, m, deterministic) -} -func (dst *UninterpretedOption_NamePart) XXX_Merge(src proto.Message) { - xxx_messageInfo_UninterpretedOption_NamePart.Merge(dst, src) -} -func (m *UninterpretedOption_NamePart) XXX_Size() int { - return xxx_messageInfo_UninterpretedOption_NamePart.Size(m) -} -func (m *UninterpretedOption_NamePart) XXX_DiscardUnknown() { - xxx_messageInfo_UninterpretedOption_NamePart.DiscardUnknown(m) -} - -var xxx_messageInfo_UninterpretedOption_NamePart proto.InternalMessageInfo - -func (m *UninterpretedOption_NamePart) GetNamePart() string { - if m != nil && m.NamePart != nil { - return *m.NamePart - } - return "" -} - -func (m *UninterpretedOption_NamePart) GetIsExtension() bool { - if m != nil && m.IsExtension != nil { - return *m.IsExtension - } - return false -} - -// Encapsulates information about the original source file from which a -// FileDescriptorProto was generated. -type SourceCodeInfo struct { - // A Location identifies a piece of source code in a .proto file which - // corresponds to a particular definition. This information is intended - // to be useful to IDEs, code indexers, documentation generators, and similar - // tools. - // - // For example, say we have a file like: - // message Foo { - // optional string foo = 1; - // } - // Let's look at just the field definition: - // optional string foo = 1; - // ^ ^^ ^^ ^ ^^^ - // a bc de f ghi - // We have the following locations: - // span path represents - // [a,i) [ 4, 0, 2, 0 ] The whole field definition. - // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). - // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). - // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). - // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). - // - // Notes: - // - A location may refer to a repeated field itself (i.e. not to any - // particular index within it). This is used whenever a set of elements are - // logically enclosed in a single code segment. For example, an entire - // extend block (possibly containing multiple extension definitions) will - // have an outer location whose path refers to the "extensions" repeated - // field without an index. - // - Multiple locations may have the same path. This happens when a single - // logical declaration is spread out across multiple places. The most - // obvious example is the "extend" block again -- there may be multiple - // extend blocks in the same scope, each of which will have the same path. - // - A location's span is not always a subset of its parent's span. For - // example, the "extendee" of an extension declaration appears at the - // beginning of the "extend" block and is shared by all extensions within - // the block. - // - Just because a location's span is a subset of some other location's span - // does not mean that it is a descendent. For example, a "group" defines - // both a type and a field in a single declaration. Thus, the locations - // corresponding to the type and field and their components will overlap. - // - Code which tries to interpret locations should probably be designed to - // ignore those that it doesn't understand, as more types of locations could - // be recorded in the future. - Location []*SourceCodeInfo_Location `protobuf:"bytes,1,rep,name=location" json:"location,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SourceCodeInfo) Reset() { *m = SourceCodeInfo{} } -func (m *SourceCodeInfo) String() string { return proto.CompactTextString(m) } -func (*SourceCodeInfo) ProtoMessage() {} -func (*SourceCodeInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{19} -} -func (m *SourceCodeInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SourceCodeInfo.Unmarshal(m, b) -} -func (m *SourceCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SourceCodeInfo.Marshal(b, m, deterministic) -} -func (dst *SourceCodeInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_SourceCodeInfo.Merge(dst, src) -} -func (m *SourceCodeInfo) XXX_Size() int { - return xxx_messageInfo_SourceCodeInfo.Size(m) -} -func (m *SourceCodeInfo) XXX_DiscardUnknown() { - xxx_messageInfo_SourceCodeInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_SourceCodeInfo proto.InternalMessageInfo - -func (m *SourceCodeInfo) GetLocation() []*SourceCodeInfo_Location { - if m != nil { - return m.Location - } - return nil -} - -type SourceCodeInfo_Location struct { - // Identifies which part of the FileDescriptorProto was defined at this - // location. - // - // Each element is a field number or an index. They form a path from - // the root FileDescriptorProto to the place where the definition. For - // example, this path: - // [ 4, 3, 2, 7, 1 ] - // refers to: - // file.message_type(3) // 4, 3 - // .field(7) // 2, 7 - // .name() // 1 - // This is because FileDescriptorProto.message_type has field number 4: - // repeated DescriptorProto message_type = 4; - // and DescriptorProto.field has field number 2: - // repeated FieldDescriptorProto field = 2; - // and FieldDescriptorProto.name has field number 1: - // optional string name = 1; - // - // Thus, the above path gives the location of a field name. If we removed - // the last element: - // [ 4, 3, 2, 7 ] - // this path refers to the whole field declaration (from the beginning - // of the label to the terminating semicolon). - Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"` - // Always has exactly three or four elements: start line, start column, - // end line (optional, otherwise assumed same as start line), end column. - // These are packed into a single field for efficiency. Note that line - // and column numbers are zero-based -- typically you will want to add - // 1 to each before displaying to a user. - Span []int32 `protobuf:"varint,2,rep,packed,name=span" json:"span,omitempty"` - // If this SourceCodeInfo represents a complete declaration, these are any - // comments appearing before and after the declaration which appear to be - // attached to the declaration. - // - // A series of line comments appearing on consecutive lines, with no other - // tokens appearing on those lines, will be treated as a single comment. - // - // leading_detached_comments will keep paragraphs of comments that appear - // before (but not connected to) the current element. Each paragraph, - // separated by empty lines, will be one comment element in the repeated - // field. - // - // Only the comment content is provided; comment markers (e.g. //) are - // stripped out. For block comments, leading whitespace and an asterisk - // will be stripped from the beginning of each line other than the first. - // Newlines are included in the output. - // - // Examples: - // - // optional int32 foo = 1; // Comment attached to foo. - // // Comment attached to bar. - // optional int32 bar = 2; - // - // optional string baz = 3; - // // Comment attached to baz. - // // Another line attached to baz. - // - // // Comment attached to qux. - // // - // // Another line attached to qux. - // optional double qux = 4; - // - // // Detached comment for corge. This is not leading or trailing comments - // // to qux or corge because there are blank lines separating it from - // // both. - // - // // Detached comment for corge paragraph 2. - // - // optional string corge = 5; - // /* Block comment attached - // * to corge. Leading asterisks - // * will be removed. */ - // /* Block comment attached to - // * grault. */ - // optional int32 grault = 6; - // - // // ignored detached comments. - LeadingComments *string `protobuf:"bytes,3,opt,name=leading_comments,json=leadingComments" json:"leading_comments,omitempty"` - TrailingComments *string `protobuf:"bytes,4,opt,name=trailing_comments,json=trailingComments" json:"trailing_comments,omitempty"` - LeadingDetachedComments []string `protobuf:"bytes,6,rep,name=leading_detached_comments,json=leadingDetachedComments" json:"leading_detached_comments,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SourceCodeInfo_Location) Reset() { *m = SourceCodeInfo_Location{} } -func (m *SourceCodeInfo_Location) String() string { return proto.CompactTextString(m) } -func (*SourceCodeInfo_Location) ProtoMessage() {} -func (*SourceCodeInfo_Location) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{19, 0} -} -func (m *SourceCodeInfo_Location) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SourceCodeInfo_Location.Unmarshal(m, b) -} -func (m *SourceCodeInfo_Location) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SourceCodeInfo_Location.Marshal(b, m, deterministic) -} -func (dst *SourceCodeInfo_Location) XXX_Merge(src proto.Message) { - xxx_messageInfo_SourceCodeInfo_Location.Merge(dst, src) -} -func (m *SourceCodeInfo_Location) XXX_Size() int { - return xxx_messageInfo_SourceCodeInfo_Location.Size(m) -} -func (m *SourceCodeInfo_Location) XXX_DiscardUnknown() { - xxx_messageInfo_SourceCodeInfo_Location.DiscardUnknown(m) -} - -var xxx_messageInfo_SourceCodeInfo_Location proto.InternalMessageInfo - -func (m *SourceCodeInfo_Location) GetPath() []int32 { - if m != nil { - return m.Path - } - return nil -} - -func (m *SourceCodeInfo_Location) GetSpan() []int32 { - if m != nil { - return m.Span - } - return nil -} - -func (m *SourceCodeInfo_Location) GetLeadingComments() string { - if m != nil && m.LeadingComments != nil { - return *m.LeadingComments - } - return "" -} - -func (m *SourceCodeInfo_Location) GetTrailingComments() string { - if m != nil && m.TrailingComments != nil { - return *m.TrailingComments - } - return "" -} - -func (m *SourceCodeInfo_Location) GetLeadingDetachedComments() []string { - if m != nil { - return m.LeadingDetachedComments - } - return nil -} - -// Describes the relationship between generated code and its original source -// file. A GeneratedCodeInfo message is associated with only one generated -// source file, but may contain references to different source .proto files. -type GeneratedCodeInfo struct { - // An Annotation connects some span of text in generated code to an element - // of its generating .proto file. - Annotation []*GeneratedCodeInfo_Annotation `protobuf:"bytes,1,rep,name=annotation" json:"annotation,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GeneratedCodeInfo) Reset() { *m = GeneratedCodeInfo{} } -func (m *GeneratedCodeInfo) String() string { return proto.CompactTextString(m) } -func (*GeneratedCodeInfo) ProtoMessage() {} -func (*GeneratedCodeInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{20} -} -func (m *GeneratedCodeInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GeneratedCodeInfo.Unmarshal(m, b) -} -func (m *GeneratedCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GeneratedCodeInfo.Marshal(b, m, deterministic) -} -func (dst *GeneratedCodeInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_GeneratedCodeInfo.Merge(dst, src) -} -func (m *GeneratedCodeInfo) XXX_Size() int { - return xxx_messageInfo_GeneratedCodeInfo.Size(m) -} -func (m *GeneratedCodeInfo) XXX_DiscardUnknown() { - xxx_messageInfo_GeneratedCodeInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_GeneratedCodeInfo proto.InternalMessageInfo - -func (m *GeneratedCodeInfo) GetAnnotation() []*GeneratedCodeInfo_Annotation { - if m != nil { - return m.Annotation - } - return nil -} - -type GeneratedCodeInfo_Annotation struct { - // Identifies the element in the original source .proto file. This field - // is formatted the same as SourceCodeInfo.Location.path. - Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"` - // Identifies the filesystem path to the original source .proto. - SourceFile *string `protobuf:"bytes,2,opt,name=source_file,json=sourceFile" json:"source_file,omitempty"` - // Identifies the starting offset in bytes in the generated code - // that relates to the identified object. - Begin *int32 `protobuf:"varint,3,opt,name=begin" json:"begin,omitempty"` - // Identifies the ending offset in bytes in the generated code that - // relates to the identified offset. The end offset should be one past - // the last relevant byte (so the length of the text = end - begin). - End *int32 `protobuf:"varint,4,opt,name=end" json:"end,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GeneratedCodeInfo_Annotation) Reset() { *m = GeneratedCodeInfo_Annotation{} } -func (m *GeneratedCodeInfo_Annotation) String() string { return proto.CompactTextString(m) } -func (*GeneratedCodeInfo_Annotation) ProtoMessage() {} -func (*GeneratedCodeInfo_Annotation) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{20, 0} -} -func (m *GeneratedCodeInfo_Annotation) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GeneratedCodeInfo_Annotation.Unmarshal(m, b) -} -func (m *GeneratedCodeInfo_Annotation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GeneratedCodeInfo_Annotation.Marshal(b, m, deterministic) -} -func (dst *GeneratedCodeInfo_Annotation) XXX_Merge(src proto.Message) { - xxx_messageInfo_GeneratedCodeInfo_Annotation.Merge(dst, src) -} -func (m *GeneratedCodeInfo_Annotation) XXX_Size() int { - return xxx_messageInfo_GeneratedCodeInfo_Annotation.Size(m) -} -func (m *GeneratedCodeInfo_Annotation) XXX_DiscardUnknown() { - xxx_messageInfo_GeneratedCodeInfo_Annotation.DiscardUnknown(m) -} - -var xxx_messageInfo_GeneratedCodeInfo_Annotation proto.InternalMessageInfo - -func (m *GeneratedCodeInfo_Annotation) GetPath() []int32 { - if m != nil { - return m.Path - } - return nil -} - -func (m *GeneratedCodeInfo_Annotation) GetSourceFile() string { - if m != nil && m.SourceFile != nil { - return *m.SourceFile - } - return "" -} - -func (m *GeneratedCodeInfo_Annotation) GetBegin() int32 { - if m != nil && m.Begin != nil { - return *m.Begin - } - return 0 -} - -func (m *GeneratedCodeInfo_Annotation) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -func init() { - proto.RegisterType((*FileDescriptorSet)(nil), "google.protobuf.FileDescriptorSet") - proto.RegisterType((*FileDescriptorProto)(nil), "google.protobuf.FileDescriptorProto") - proto.RegisterType((*DescriptorProto)(nil), "google.protobuf.DescriptorProto") - proto.RegisterType((*DescriptorProto_ExtensionRange)(nil), "google.protobuf.DescriptorProto.ExtensionRange") - proto.RegisterType((*DescriptorProto_ReservedRange)(nil), "google.protobuf.DescriptorProto.ReservedRange") - proto.RegisterType((*ExtensionRangeOptions)(nil), "google.protobuf.ExtensionRangeOptions") - proto.RegisterType((*FieldDescriptorProto)(nil), "google.protobuf.FieldDescriptorProto") - proto.RegisterType((*OneofDescriptorProto)(nil), "google.protobuf.OneofDescriptorProto") - proto.RegisterType((*EnumDescriptorProto)(nil), "google.protobuf.EnumDescriptorProto") - proto.RegisterType((*EnumDescriptorProto_EnumReservedRange)(nil), "google.protobuf.EnumDescriptorProto.EnumReservedRange") - proto.RegisterType((*EnumValueDescriptorProto)(nil), "google.protobuf.EnumValueDescriptorProto") - proto.RegisterType((*ServiceDescriptorProto)(nil), "google.protobuf.ServiceDescriptorProto") - proto.RegisterType((*MethodDescriptorProto)(nil), "google.protobuf.MethodDescriptorProto") - proto.RegisterType((*FileOptions)(nil), "google.protobuf.FileOptions") - proto.RegisterType((*MessageOptions)(nil), "google.protobuf.MessageOptions") - proto.RegisterType((*FieldOptions)(nil), "google.protobuf.FieldOptions") - proto.RegisterType((*OneofOptions)(nil), "google.protobuf.OneofOptions") - proto.RegisterType((*EnumOptions)(nil), "google.protobuf.EnumOptions") - proto.RegisterType((*EnumValueOptions)(nil), "google.protobuf.EnumValueOptions") - proto.RegisterType((*ServiceOptions)(nil), "google.protobuf.ServiceOptions") - proto.RegisterType((*MethodOptions)(nil), "google.protobuf.MethodOptions") - proto.RegisterType((*UninterpretedOption)(nil), "google.protobuf.UninterpretedOption") - proto.RegisterType((*UninterpretedOption_NamePart)(nil), "google.protobuf.UninterpretedOption.NamePart") - proto.RegisterType((*SourceCodeInfo)(nil), "google.protobuf.SourceCodeInfo") - proto.RegisterType((*SourceCodeInfo_Location)(nil), "google.protobuf.SourceCodeInfo.Location") - proto.RegisterType((*GeneratedCodeInfo)(nil), "google.protobuf.GeneratedCodeInfo") - proto.RegisterType((*GeneratedCodeInfo_Annotation)(nil), "google.protobuf.GeneratedCodeInfo.Annotation") - proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Type", FieldDescriptorProto_Type_name, FieldDescriptorProto_Type_value) - proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Label", FieldDescriptorProto_Label_name, FieldDescriptorProto_Label_value) - proto.RegisterEnum("google.protobuf.FileOptions_OptimizeMode", FileOptions_OptimizeMode_name, FileOptions_OptimizeMode_value) - proto.RegisterEnum("google.protobuf.FieldOptions_CType", FieldOptions_CType_name, FieldOptions_CType_value) - proto.RegisterEnum("google.protobuf.FieldOptions_JSType", FieldOptions_JSType_name, FieldOptions_JSType_value) - proto.RegisterEnum("google.protobuf.MethodOptions_IdempotencyLevel", MethodOptions_IdempotencyLevel_name, MethodOptions_IdempotencyLevel_value) -} - -func init() { - proto.RegisterFile("google/protobuf/descriptor.proto", fileDescriptor_descriptor_4df4cb5f42392df6) -} - -var fileDescriptor_descriptor_4df4cb5f42392df6 = []byte{ - // 2555 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x59, 0xdd, 0x6e, 0x1b, 0xc7, - 0xf5, 0xcf, 0xf2, 0x4b, 0xe4, 0x21, 0x45, 0x8d, 0x46, 0x8a, 0xbd, 0x56, 0x3e, 0x2c, 0x33, 0x1f, - 0x96, 0x9d, 0x7f, 0xa8, 0xc0, 0xb1, 0x1d, 0x47, 0xfe, 0x23, 0x2d, 0x45, 0xae, 0x15, 0xaa, 0x12, - 0xc9, 0x2e, 0xa9, 0xe6, 0x03, 0x28, 0x16, 0xa3, 0xdd, 0x21, 0xb9, 0xf6, 0x72, 0x77, 0xb3, 0xbb, - 0xb4, 0xad, 0xa0, 0x17, 0x06, 0x7a, 0xd5, 0xab, 0xde, 0x16, 0x45, 0xd1, 0x8b, 0xde, 0x04, 0xe8, - 0x03, 0x14, 0xc8, 0x5d, 0x9f, 0xa0, 0x40, 0xde, 0xa0, 0x68, 0x0b, 0xb4, 0x8f, 0xd0, 0xcb, 0x62, - 0x66, 0x76, 0x97, 0xbb, 0x24, 0x15, 0x2b, 0x01, 0xe2, 0x5c, 0x91, 0xf3, 0x9b, 0xdf, 0x39, 0x73, - 0xe6, 0xcc, 0x99, 0x33, 0x67, 0x66, 0x61, 0x7b, 0xe4, 0x38, 0x23, 0x8b, 0xee, 0xba, 0x9e, 0x13, - 0x38, 0xa7, 0xd3, 0xe1, 0xae, 0x41, 0x7d, 0xdd, 0x33, 0xdd, 0xc0, 0xf1, 0xea, 0x1c, 0xc3, 0x6b, - 0x82, 0x51, 0x8f, 0x18, 0xb5, 0x63, 0x58, 0x7f, 0x60, 0x5a, 0xb4, 0x15, 0x13, 0xfb, 0x34, 0xc0, - 0xf7, 0x20, 0x37, 0x34, 0x2d, 0x2a, 0x4b, 0xdb, 0xd9, 0x9d, 0xf2, 0xad, 0x37, 0xeb, 0x73, 0x42, - 0xf5, 0xb4, 0x44, 0x8f, 0xc1, 0x2a, 0x97, 0xa8, 0xfd, 0x2b, 0x07, 0x1b, 0x4b, 0x7a, 0x31, 0x86, - 0x9c, 0x4d, 0x26, 0x4c, 0xa3, 0xb4, 0x53, 0x52, 0xf9, 0x7f, 0x2c, 0xc3, 0x8a, 0x4b, 0xf4, 0x47, - 0x64, 0x44, 0xe5, 0x0c, 0x87, 0xa3, 0x26, 0x7e, 0x1d, 0xc0, 0xa0, 0x2e, 0xb5, 0x0d, 0x6a, 0xeb, - 0x67, 0x72, 0x76, 0x3b, 0xbb, 0x53, 0x52, 0x13, 0x08, 0x7e, 0x07, 0xd6, 0xdd, 0xe9, 0xa9, 0x65, - 0xea, 0x5a, 0x82, 0x06, 0xdb, 0xd9, 0x9d, 0xbc, 0x8a, 0x44, 0x47, 0x6b, 0x46, 0xbe, 0x0e, 0x6b, - 0x4f, 0x28, 0x79, 0x94, 0xa4, 0x96, 0x39, 0xb5, 0xca, 0xe0, 0x04, 0xb1, 0x09, 0x95, 0x09, 0xf5, - 0x7d, 0x32, 0xa2, 0x5a, 0x70, 0xe6, 0x52, 0x39, 0xc7, 0x67, 0xbf, 0xbd, 0x30, 0xfb, 0xf9, 0x99, - 0x97, 0x43, 0xa9, 0xc1, 0x99, 0x4b, 0x71, 0x03, 0x4a, 0xd4, 0x9e, 0x4e, 0x84, 0x86, 0xfc, 0x39, - 0xfe, 0x53, 0xec, 0xe9, 0x64, 0x5e, 0x4b, 0x91, 0x89, 0x85, 0x2a, 0x56, 0x7c, 0xea, 0x3d, 0x36, - 0x75, 0x2a, 0x17, 0xb8, 0x82, 0xeb, 0x0b, 0x0a, 0xfa, 0xa2, 0x7f, 0x5e, 0x47, 0x24, 0x87, 0x9b, - 0x50, 0xa2, 0x4f, 0x03, 0x6a, 0xfb, 0xa6, 0x63, 0xcb, 0x2b, 0x5c, 0xc9, 0x5b, 0x4b, 0x56, 0x91, - 0x5a, 0xc6, 0xbc, 0x8a, 0x99, 0x1c, 0xbe, 0x0b, 0x2b, 0x8e, 0x1b, 0x98, 0x8e, 0xed, 0xcb, 0xc5, - 0x6d, 0x69, 0xa7, 0x7c, 0xeb, 0xd5, 0xa5, 0x81, 0xd0, 0x15, 0x1c, 0x35, 0x22, 0xe3, 0x36, 0x20, - 0xdf, 0x99, 0x7a, 0x3a, 0xd5, 0x74, 0xc7, 0xa0, 0x9a, 0x69, 0x0f, 0x1d, 0xb9, 0xc4, 0x15, 0x5c, - 0x5d, 0x9c, 0x08, 0x27, 0x36, 0x1d, 0x83, 0xb6, 0xed, 0xa1, 0xa3, 0x56, 0xfd, 0x54, 0x1b, 0x5f, - 0x82, 0x82, 0x7f, 0x66, 0x07, 0xe4, 0xa9, 0x5c, 0xe1, 0x11, 0x12, 0xb6, 0x6a, 0x5f, 0x17, 0x60, - 0xed, 0x22, 0x21, 0x76, 0x1f, 0xf2, 0x43, 0x36, 0x4b, 0x39, 0xf3, 0x5d, 0x7c, 0x20, 0x64, 0xd2, - 0x4e, 0x2c, 0x7c, 0x4f, 0x27, 0x36, 0xa0, 0x6c, 0x53, 0x3f, 0xa0, 0x86, 0x88, 0x88, 0xec, 0x05, - 0x63, 0x0a, 0x84, 0xd0, 0x62, 0x48, 0xe5, 0xbe, 0x57, 0x48, 0x7d, 0x0a, 0x6b, 0xb1, 0x49, 0x9a, - 0x47, 0xec, 0x51, 0x14, 0x9b, 0xbb, 0xcf, 0xb3, 0xa4, 0xae, 0x44, 0x72, 0x2a, 0x13, 0x53, 0xab, - 0x34, 0xd5, 0xc6, 0x2d, 0x00, 0xc7, 0xa6, 0xce, 0x50, 0x33, 0xa8, 0x6e, 0xc9, 0xc5, 0x73, 0xbc, - 0xd4, 0x65, 0x94, 0x05, 0x2f, 0x39, 0x02, 0xd5, 0x2d, 0xfc, 0xe1, 0x2c, 0xd4, 0x56, 0xce, 0x89, - 0x94, 0x63, 0xb1, 0xc9, 0x16, 0xa2, 0xed, 0x04, 0xaa, 0x1e, 0x65, 0x71, 0x4f, 0x8d, 0x70, 0x66, - 0x25, 0x6e, 0x44, 0xfd, 0xb9, 0x33, 0x53, 0x43, 0x31, 0x31, 0xb1, 0x55, 0x2f, 0xd9, 0xc4, 0x6f, - 0x40, 0x0c, 0x68, 0x3c, 0xac, 0x80, 0x67, 0xa1, 0x4a, 0x04, 0x76, 0xc8, 0x84, 0x6e, 0x7d, 0x09, - 0xd5, 0xb4, 0x7b, 0xf0, 0x26, 0xe4, 0xfd, 0x80, 0x78, 0x01, 0x8f, 0xc2, 0xbc, 0x2a, 0x1a, 0x18, - 0x41, 0x96, 0xda, 0x06, 0xcf, 0x72, 0x79, 0x95, 0xfd, 0xc5, 0x3f, 0x9d, 0x4d, 0x38, 0xcb, 0x27, - 0xfc, 0xf6, 0xe2, 0x8a, 0xa6, 0x34, 0xcf, 0xcf, 0x7b, 0xeb, 0x03, 0x58, 0x4d, 0x4d, 0xe0, 0xa2, - 0x43, 0xd7, 0x7e, 0x05, 0x2f, 0x2f, 0x55, 0x8d, 0x3f, 0x85, 0xcd, 0xa9, 0x6d, 0xda, 0x01, 0xf5, - 0x5c, 0x8f, 0xb2, 0x88, 0x15, 0x43, 0xc9, 0xff, 0x5e, 0x39, 0x27, 0xe6, 0x4e, 0x92, 0x6c, 0xa1, - 0x45, 0xdd, 0x98, 0x2e, 0x82, 0x37, 0x4b, 0xc5, 0xff, 0xac, 0xa0, 0x67, 0xcf, 0x9e, 0x3d, 0xcb, - 0xd4, 0x7e, 0x57, 0x80, 0xcd, 0x65, 0x7b, 0x66, 0xe9, 0xf6, 0xbd, 0x04, 0x05, 0x7b, 0x3a, 0x39, - 0xa5, 0x1e, 0x77, 0x52, 0x5e, 0x0d, 0x5b, 0xb8, 0x01, 0x79, 0x8b, 0x9c, 0x52, 0x4b, 0xce, 0x6d, - 0x4b, 0x3b, 0xd5, 0x5b, 0xef, 0x5c, 0x68, 0x57, 0xd6, 0x8f, 0x98, 0x88, 0x2a, 0x24, 0xf1, 0x47, - 0x90, 0x0b, 0x53, 0x34, 0xd3, 0x70, 0xf3, 0x62, 0x1a, 0xd8, 0x5e, 0x52, 0xb9, 0x1c, 0x7e, 0x05, - 0x4a, 0xec, 0x57, 0xc4, 0x46, 0x81, 0xdb, 0x5c, 0x64, 0x00, 0x8b, 0x0b, 0xbc, 0x05, 0x45, 0xbe, - 0x4d, 0x0c, 0x1a, 0x1d, 0x6d, 0x71, 0x9b, 0x05, 0x96, 0x41, 0x87, 0x64, 0x6a, 0x05, 0xda, 0x63, - 0x62, 0x4d, 0x29, 0x0f, 0xf8, 0x92, 0x5a, 0x09, 0xc1, 0x5f, 0x30, 0x0c, 0x5f, 0x85, 0xb2, 0xd8, - 0x55, 0xa6, 0x6d, 0xd0, 0xa7, 0x3c, 0x7b, 0xe6, 0x55, 0xb1, 0xd1, 0xda, 0x0c, 0x61, 0xc3, 0x3f, - 0xf4, 0x1d, 0x3b, 0x0a, 0x4d, 0x3e, 0x04, 0x03, 0xf8, 0xf0, 0x1f, 0xcc, 0x27, 0xee, 0xd7, 0x96, - 0x4f, 0x6f, 0x3e, 0xa6, 0x6a, 0x7f, 0xc9, 0x40, 0x8e, 0xe7, 0x8b, 0x35, 0x28, 0x0f, 0x3e, 0xeb, - 0x29, 0x5a, 0xab, 0x7b, 0xb2, 0x7f, 0xa4, 0x20, 0x09, 0x57, 0x01, 0x38, 0xf0, 0xe0, 0xa8, 0xdb, - 0x18, 0xa0, 0x4c, 0xdc, 0x6e, 0x77, 0x06, 0x77, 0x6f, 0xa3, 0x6c, 0x2c, 0x70, 0x22, 0x80, 0x5c, - 0x92, 0xf0, 0xfe, 0x2d, 0x94, 0xc7, 0x08, 0x2a, 0x42, 0x41, 0xfb, 0x53, 0xa5, 0x75, 0xf7, 0x36, - 0x2a, 0xa4, 0x91, 0xf7, 0x6f, 0xa1, 0x15, 0xbc, 0x0a, 0x25, 0x8e, 0xec, 0x77, 0xbb, 0x47, 0xa8, - 0x18, 0xeb, 0xec, 0x0f, 0xd4, 0x76, 0xe7, 0x00, 0x95, 0x62, 0x9d, 0x07, 0x6a, 0xf7, 0xa4, 0x87, - 0x20, 0xd6, 0x70, 0xac, 0xf4, 0xfb, 0x8d, 0x03, 0x05, 0x95, 0x63, 0xc6, 0xfe, 0x67, 0x03, 0xa5, - 0x8f, 0x2a, 0x29, 0xb3, 0xde, 0xbf, 0x85, 0x56, 0xe3, 0x21, 0x94, 0xce, 0xc9, 0x31, 0xaa, 0xe2, - 0x75, 0x58, 0x15, 0x43, 0x44, 0x46, 0xac, 0xcd, 0x41, 0x77, 0x6f, 0x23, 0x34, 0x33, 0x44, 0x68, - 0x59, 0x4f, 0x01, 0x77, 0x6f, 0x23, 0x5c, 0x6b, 0x42, 0x9e, 0x47, 0x17, 0xc6, 0x50, 0x3d, 0x6a, - 0xec, 0x2b, 0x47, 0x5a, 0xb7, 0x37, 0x68, 0x77, 0x3b, 0x8d, 0x23, 0x24, 0xcd, 0x30, 0x55, 0xf9, - 0xf9, 0x49, 0x5b, 0x55, 0x5a, 0x28, 0x93, 0xc4, 0x7a, 0x4a, 0x63, 0xa0, 0xb4, 0x50, 0xb6, 0xa6, - 0xc3, 0xe6, 0xb2, 0x3c, 0xb9, 0x74, 0x67, 0x24, 0x96, 0x38, 0x73, 0xce, 0x12, 0x73, 0x5d, 0x0b, - 0x4b, 0xfc, 0xcf, 0x0c, 0x6c, 0x2c, 0x39, 0x2b, 0x96, 0x0e, 0xf2, 0x13, 0xc8, 0x8b, 0x10, 0x15, - 0xa7, 0xe7, 0x8d, 0xa5, 0x87, 0x0e, 0x0f, 0xd8, 0x85, 0x13, 0x94, 0xcb, 0x25, 0x2b, 0x88, 0xec, - 0x39, 0x15, 0x04, 0x53, 0xb1, 0x90, 0xd3, 0x7f, 0xb9, 0x90, 0xd3, 0xc5, 0xb1, 0x77, 0xf7, 0x22, - 0xc7, 0x1e, 0xc7, 0xbe, 0x5b, 0x6e, 0xcf, 0x2f, 0xc9, 0xed, 0xf7, 0x61, 0x7d, 0x41, 0xd1, 0x85, - 0x73, 0xec, 0xaf, 0x25, 0x90, 0xcf, 0x73, 0xce, 0x73, 0x32, 0x5d, 0x26, 0x95, 0xe9, 0xee, 0xcf, - 0x7b, 0xf0, 0xda, 0xf9, 0x8b, 0xb0, 0xb0, 0xd6, 0x5f, 0x49, 0x70, 0x69, 0x79, 0xa5, 0xb8, 0xd4, - 0x86, 0x8f, 0xa0, 0x30, 0xa1, 0xc1, 0xd8, 0x89, 0xaa, 0xa5, 0xb7, 0x97, 0x9c, 0xc1, 0xac, 0x7b, - 0x7e, 0xb1, 0x43, 0xa9, 0xe4, 0x21, 0x9e, 0x3d, 0xaf, 0xdc, 0x13, 0xd6, 0x2c, 0x58, 0xfa, 0x9b, - 0x0c, 0xbc, 0xbc, 0x54, 0xf9, 0x52, 0x43, 0x5f, 0x03, 0x30, 0x6d, 0x77, 0x1a, 0x88, 0x8a, 0x48, - 0x24, 0xd8, 0x12, 0x47, 0x78, 0xf2, 0x62, 0xc9, 0x73, 0x1a, 0xc4, 0xfd, 0x59, 0xde, 0x0f, 0x02, - 0xe2, 0x84, 0x7b, 0x33, 0x43, 0x73, 0xdc, 0xd0, 0xd7, 0xcf, 0x99, 0xe9, 0x42, 0x60, 0xbe, 0x07, - 0x48, 0xb7, 0x4c, 0x6a, 0x07, 0x9a, 0x1f, 0x78, 0x94, 0x4c, 0x4c, 0x7b, 0xc4, 0x4f, 0x90, 0xe2, - 0x5e, 0x7e, 0x48, 0x2c, 0x9f, 0xaa, 0x6b, 0xa2, 0xbb, 0x1f, 0xf5, 0x32, 0x09, 0x1e, 0x40, 0x5e, - 0x42, 0xa2, 0x90, 0x92, 0x10, 0xdd, 0xb1, 0x44, 0xed, 0xeb, 0x22, 0x94, 0x13, 0x75, 0x35, 0xbe, - 0x06, 0x95, 0x87, 0xe4, 0x31, 0xd1, 0xa2, 0xbb, 0x92, 0xf0, 0x44, 0x99, 0x61, 0xbd, 0xf0, 0xbe, - 0xf4, 0x1e, 0x6c, 0x72, 0x8a, 0x33, 0x0d, 0xa8, 0xa7, 0xe9, 0x16, 0xf1, 0x7d, 0xee, 0xb4, 0x22, - 0xa7, 0x62, 0xd6, 0xd7, 0x65, 0x5d, 0xcd, 0xa8, 0x07, 0xdf, 0x81, 0x0d, 0x2e, 0x31, 0x99, 0x5a, - 0x81, 0xe9, 0x5a, 0x54, 0x63, 0xb7, 0x37, 0x9f, 0x9f, 0x24, 0xb1, 0x65, 0xeb, 0x8c, 0x71, 0x1c, - 0x12, 0x98, 0x45, 0x3e, 0x6e, 0xc1, 0x6b, 0x5c, 0x6c, 0x44, 0x6d, 0xea, 0x91, 0x80, 0x6a, 0xf4, - 0x8b, 0x29, 0xb1, 0x7c, 0x8d, 0xd8, 0x86, 0x36, 0x26, 0xfe, 0x58, 0xde, 0x64, 0x0a, 0xf6, 0x33, - 0xb2, 0xa4, 0x5e, 0x61, 0xc4, 0x83, 0x90, 0xa7, 0x70, 0x5a, 0xc3, 0x36, 0x3e, 0x26, 0xfe, 0x18, - 0xef, 0xc1, 0x25, 0xae, 0xc5, 0x0f, 0x3c, 0xd3, 0x1e, 0x69, 0xfa, 0x98, 0xea, 0x8f, 0xb4, 0x69, - 0x30, 0xbc, 0x27, 0xbf, 0x92, 0x1c, 0x9f, 0x5b, 0xd8, 0xe7, 0x9c, 0x26, 0xa3, 0x9c, 0x04, 0xc3, - 0x7b, 0xb8, 0x0f, 0x15, 0xb6, 0x18, 0x13, 0xf3, 0x4b, 0xaa, 0x0d, 0x1d, 0x8f, 0x1f, 0x8d, 0xd5, - 0x25, 0xa9, 0x29, 0xe1, 0xc1, 0x7a, 0x37, 0x14, 0x38, 0x76, 0x0c, 0xba, 0x97, 0xef, 0xf7, 0x14, - 0xa5, 0xa5, 0x96, 0x23, 0x2d, 0x0f, 0x1c, 0x8f, 0x05, 0xd4, 0xc8, 0x89, 0x1d, 0x5c, 0x16, 0x01, - 0x35, 0x72, 0x22, 0xf7, 0xde, 0x81, 0x0d, 0x5d, 0x17, 0x73, 0x36, 0x75, 0x2d, 0xbc, 0x63, 0xf9, - 0x32, 0x4a, 0x39, 0x4b, 0xd7, 0x0f, 0x04, 0x21, 0x8c, 0x71, 0x1f, 0x7f, 0x08, 0x2f, 0xcf, 0x9c, - 0x95, 0x14, 0x5c, 0x5f, 0x98, 0xe5, 0xbc, 0xe8, 0x1d, 0xd8, 0x70, 0xcf, 0x16, 0x05, 0x71, 0x6a, - 0x44, 0xf7, 0x6c, 0x5e, 0xec, 0x03, 0xd8, 0x74, 0xc7, 0xee, 0xa2, 0xdc, 0xcd, 0xa4, 0x1c, 0x76, - 0xc7, 0xee, 0xbc, 0xe0, 0x5b, 0xfc, 0xc2, 0xed, 0x51, 0x9d, 0x04, 0xd4, 0x90, 0x2f, 0x27, 0xe9, - 0x89, 0x0e, 0xbc, 0x0b, 0x48, 0xd7, 0x35, 0x6a, 0x93, 0x53, 0x8b, 0x6a, 0xc4, 0xa3, 0x36, 0xf1, - 0xe5, 0xab, 0x49, 0x72, 0x55, 0xd7, 0x15, 0xde, 0xdb, 0xe0, 0x9d, 0xf8, 0x26, 0xac, 0x3b, 0xa7, - 0x0f, 0x75, 0x11, 0x92, 0x9a, 0xeb, 0xd1, 0xa1, 0xf9, 0x54, 0x7e, 0x93, 0xfb, 0x77, 0x8d, 0x75, - 0xf0, 0x80, 0xec, 0x71, 0x18, 0xdf, 0x00, 0xa4, 0xfb, 0x63, 0xe2, 0xb9, 0x3c, 0x27, 0xfb, 0x2e, - 0xd1, 0xa9, 0xfc, 0x96, 0xa0, 0x0a, 0xbc, 0x13, 0xc1, 0x6c, 0x4b, 0xf8, 0x4f, 0xcc, 0x61, 0x10, - 0x69, 0xbc, 0x2e, 0xb6, 0x04, 0xc7, 0x42, 0x6d, 0x3b, 0x80, 0x98, 0x2b, 0x52, 0x03, 0xef, 0x70, - 0x5a, 0xd5, 0x1d, 0xbb, 0xc9, 0x71, 0xdf, 0x80, 0x55, 0xc6, 0x9c, 0x0d, 0x7a, 0x43, 0x14, 0x64, - 0xee, 0x38, 0x31, 0xe2, 0x0f, 0x56, 0x1b, 0xd7, 0xf6, 0xa0, 0x92, 0x8c, 0x4f, 0x5c, 0x02, 0x11, - 0xa1, 0x48, 0x62, 0xc5, 0x4a, 0xb3, 0xdb, 0x62, 0x65, 0xc6, 0xe7, 0x0a, 0xca, 0xb0, 0x72, 0xe7, - 0xa8, 0x3d, 0x50, 0x34, 0xf5, 0xa4, 0x33, 0x68, 0x1f, 0x2b, 0x28, 0x9b, 0xa8, 0xab, 0x0f, 0x73, - 0xc5, 0xb7, 0xd1, 0xf5, 0xda, 0x37, 0x19, 0xa8, 0xa6, 0x2f, 0x4a, 0xf8, 0xff, 0xe1, 0x72, 0xf4, - 0xaa, 0xe1, 0xd3, 0x40, 0x7b, 0x62, 0x7a, 0x7c, 0xe3, 0x4c, 0x88, 0x38, 0xc4, 0xe2, 0xa5, 0xdb, - 0x0c, 0x59, 0x7d, 0x1a, 0x7c, 0x62, 0x7a, 0x6c, 0x5b, 0x4c, 0x48, 0x80, 0x8f, 0xe0, 0xaa, 0xed, - 0x68, 0x7e, 0x40, 0x6c, 0x83, 0x78, 0x86, 0x36, 0x7b, 0x4f, 0xd2, 0x88, 0xae, 0x53, 0xdf, 0x77, - 0xc4, 0x81, 0x15, 0x6b, 0x79, 0xd5, 0x76, 0xfa, 0x21, 0x79, 0x96, 0xc9, 0x1b, 0x21, 0x75, 0x2e, - 0xcc, 0xb2, 0xe7, 0x85, 0xd9, 0x2b, 0x50, 0x9a, 0x10, 0x57, 0xa3, 0x76, 0xe0, 0x9d, 0xf1, 0xf2, - 0xb8, 0xa8, 0x16, 0x27, 0xc4, 0x55, 0x58, 0xfb, 0x85, 0xdc, 0x52, 0x0e, 0x73, 0xc5, 0x22, 0x2a, - 0x1d, 0xe6, 0x8a, 0x25, 0x04, 0xb5, 0x7f, 0x64, 0xa1, 0x92, 0x2c, 0x97, 0xd9, 0xed, 0x43, 0xe7, - 0x27, 0x8b, 0xc4, 0x73, 0xcf, 0x1b, 0xdf, 0x5a, 0x5c, 0xd7, 0x9b, 0xec, 0xc8, 0xd9, 0x2b, 0x88, - 0x22, 0x56, 0x15, 0x92, 0xec, 0xb8, 0x67, 0xd9, 0x86, 0x8a, 0xa2, 0xa1, 0xa8, 0x86, 0x2d, 0x7c, - 0x00, 0x85, 0x87, 0x3e, 0xd7, 0x5d, 0xe0, 0xba, 0xdf, 0xfc, 0x76, 0xdd, 0x87, 0x7d, 0xae, 0xbc, - 0x74, 0xd8, 0xd7, 0x3a, 0x5d, 0xf5, 0xb8, 0x71, 0xa4, 0x86, 0xe2, 0xf8, 0x0a, 0xe4, 0x2c, 0xf2, - 0xe5, 0x59, 0xfa, 0x70, 0xe2, 0xd0, 0x45, 0x17, 0xe1, 0x0a, 0xe4, 0x9e, 0x50, 0xf2, 0x28, 0x7d, - 0x24, 0x70, 0xe8, 0x07, 0xdc, 0x0c, 0xbb, 0x90, 0xe7, 0xfe, 0xc2, 0x00, 0xa1, 0xc7, 0xd0, 0x4b, - 0xb8, 0x08, 0xb9, 0x66, 0x57, 0x65, 0x1b, 0x02, 0x41, 0x45, 0xa0, 0x5a, 0xaf, 0xad, 0x34, 0x15, - 0x94, 0xa9, 0xdd, 0x81, 0x82, 0x70, 0x02, 0xdb, 0x2c, 0xb1, 0x1b, 0xd0, 0x4b, 0x61, 0x33, 0xd4, - 0x21, 0x45, 0xbd, 0x27, 0xc7, 0xfb, 0x8a, 0x8a, 0x32, 0xe9, 0xa5, 0xce, 0xa1, 0x7c, 0xcd, 0x87, - 0x4a, 0xb2, 0x5e, 0x7e, 0x31, 0x77, 0xe1, 0xbf, 0x4a, 0x50, 0x4e, 0xd4, 0xbf, 0xac, 0x70, 0x21, - 0x96, 0xe5, 0x3c, 0xd1, 0x88, 0x65, 0x12, 0x3f, 0x0c, 0x0d, 0xe0, 0x50, 0x83, 0x21, 0x17, 0x5d, - 0xba, 0x17, 0xb4, 0x45, 0xf2, 0xa8, 0x50, 0xfb, 0xa3, 0x04, 0x68, 0xbe, 0x00, 0x9d, 0x33, 0x53, - 0xfa, 0x31, 0xcd, 0xac, 0xfd, 0x41, 0x82, 0x6a, 0xba, 0xea, 0x9c, 0x33, 0xef, 0xda, 0x8f, 0x6a, - 0xde, 0xdf, 0x33, 0xb0, 0x9a, 0xaa, 0x35, 0x2f, 0x6a, 0xdd, 0x17, 0xb0, 0x6e, 0x1a, 0x74, 0xe2, - 0x3a, 0x01, 0xb5, 0xf5, 0x33, 0xcd, 0xa2, 0x8f, 0xa9, 0x25, 0xd7, 0x78, 0xd2, 0xd8, 0xfd, 0xf6, - 0x6a, 0xb6, 0xde, 0x9e, 0xc9, 0x1d, 0x31, 0xb1, 0xbd, 0x8d, 0x76, 0x4b, 0x39, 0xee, 0x75, 0x07, - 0x4a, 0xa7, 0xf9, 0x99, 0x76, 0xd2, 0xf9, 0x59, 0xa7, 0xfb, 0x49, 0x47, 0x45, 0xe6, 0x1c, 0xed, - 0x07, 0xdc, 0xf6, 0x3d, 0x40, 0xf3, 0x46, 0xe1, 0xcb, 0xb0, 0xcc, 0x2c, 0xf4, 0x12, 0xde, 0x80, - 0xb5, 0x4e, 0x57, 0xeb, 0xb7, 0x5b, 0x8a, 0xa6, 0x3c, 0x78, 0xa0, 0x34, 0x07, 0x7d, 0xf1, 0x3e, - 0x11, 0xb3, 0x07, 0xa9, 0x0d, 0x5e, 0xfb, 0x7d, 0x16, 0x36, 0x96, 0x58, 0x82, 0x1b, 0xe1, 0xcd, - 0x42, 0x5c, 0x76, 0xde, 0xbd, 0x88, 0xf5, 0x75, 0x56, 0x10, 0xf4, 0x88, 0x17, 0x84, 0x17, 0x91, - 0x1b, 0xc0, 0xbc, 0x64, 0x07, 0xe6, 0xd0, 0xa4, 0x5e, 0xf8, 0x9c, 0x23, 0xae, 0x1b, 0x6b, 0x33, - 0x5c, 0xbc, 0xe8, 0xfc, 0x1f, 0x60, 0xd7, 0xf1, 0xcd, 0xc0, 0x7c, 0x4c, 0x35, 0xd3, 0x8e, 0xde, - 0x7e, 0xd8, 0xf5, 0x23, 0xa7, 0xa2, 0xa8, 0xa7, 0x6d, 0x07, 0x31, 0xdb, 0xa6, 0x23, 0x32, 0xc7, - 0x66, 0xc9, 0x3c, 0xab, 0xa2, 0xa8, 0x27, 0x66, 0x5f, 0x83, 0x8a, 0xe1, 0x4c, 0x59, 0x4d, 0x26, - 0x78, 0xec, 0xec, 0x90, 0xd4, 0xb2, 0xc0, 0x62, 0x4a, 0x58, 0x6d, 0xcf, 0x1e, 0x9d, 0x2a, 0x6a, - 0x59, 0x60, 0x82, 0x72, 0x1d, 0xd6, 0xc8, 0x68, 0xe4, 0x31, 0xe5, 0x91, 0x22, 0x71, 0x7f, 0xa8, - 0xc6, 0x30, 0x27, 0x6e, 0x1d, 0x42, 0x31, 0xf2, 0x03, 0x3b, 0xaa, 0x99, 0x27, 0x34, 0x57, 0x5c, - 0x8a, 0x33, 0x3b, 0x25, 0xb5, 0x68, 0x47, 0x9d, 0xd7, 0xa0, 0x62, 0xfa, 0xda, 0xec, 0x0d, 0x3d, - 0xb3, 0x9d, 0xd9, 0x29, 0xaa, 0x65, 0xd3, 0x8f, 0xdf, 0x1f, 0x6b, 0x5f, 0x65, 0xa0, 0x9a, 0xfe, - 0x06, 0x80, 0x5b, 0x50, 0xb4, 0x1c, 0x9d, 0xf0, 0xd0, 0x12, 0x1f, 0xa0, 0x76, 0x9e, 0xf3, 0xd9, - 0xa0, 0x7e, 0x14, 0xf2, 0xd5, 0x58, 0x72, 0xeb, 0x6f, 0x12, 0x14, 0x23, 0x18, 0x5f, 0x82, 0x9c, - 0x4b, 0x82, 0x31, 0x57, 0x97, 0xdf, 0xcf, 0x20, 0x49, 0xe5, 0x6d, 0x86, 0xfb, 0x2e, 0xb1, 0x79, - 0x08, 0x84, 0x38, 0x6b, 0xb3, 0x75, 0xb5, 0x28, 0x31, 0xf8, 0xe5, 0xc4, 0x99, 0x4c, 0xa8, 0x1d, - 0xf8, 0xd1, 0xba, 0x86, 0x78, 0x33, 0x84, 0xf1, 0x3b, 0xb0, 0x1e, 0x78, 0xc4, 0xb4, 0x52, 0xdc, - 0x1c, 0xe7, 0xa2, 0xa8, 0x23, 0x26, 0xef, 0xc1, 0x95, 0x48, 0xaf, 0x41, 0x03, 0xa2, 0x8f, 0xa9, - 0x31, 0x13, 0x2a, 0xf0, 0x47, 0x88, 0xcb, 0x21, 0xa1, 0x15, 0xf6, 0x47, 0xb2, 0xb5, 0x6f, 0x24, - 0x58, 0x8f, 0xae, 0x53, 0x46, 0xec, 0xac, 0x63, 0x00, 0x62, 0xdb, 0x4e, 0x90, 0x74, 0xd7, 0x62, - 0x28, 0x2f, 0xc8, 0xd5, 0x1b, 0xb1, 0x90, 0x9a, 0x50, 0xb0, 0x35, 0x01, 0x98, 0xf5, 0x9c, 0xeb, - 0xb6, 0xab, 0x50, 0x0e, 0x3f, 0xf0, 0xf0, 0xaf, 0x84, 0xe2, 0x02, 0x0e, 0x02, 0x62, 0xf7, 0x2e, - 0xbc, 0x09, 0xf9, 0x53, 0x3a, 0x32, 0xed, 0xf0, 0xd9, 0x56, 0x34, 0xa2, 0x67, 0x92, 0x5c, 0xfc, - 0x4c, 0xb2, 0xff, 0x5b, 0x09, 0x36, 0x74, 0x67, 0x32, 0x6f, 0xef, 0x3e, 0x9a, 0x7b, 0x05, 0xf0, - 0x3f, 0x96, 0x3e, 0xff, 0x68, 0x64, 0x06, 0xe3, 0xe9, 0x69, 0x5d, 0x77, 0x26, 0xbb, 0x23, 0xc7, - 0x22, 0xf6, 0x68, 0xf6, 0x99, 0x93, 0xff, 0xd1, 0xdf, 0x1d, 0x51, 0xfb, 0xdd, 0x91, 0x93, 0xf8, - 0xe8, 0x79, 0x7f, 0xf6, 0xf7, 0xbf, 0x92, 0xf4, 0xa7, 0x4c, 0xf6, 0xa0, 0xb7, 0xff, 0xe7, 0xcc, - 0xd6, 0x81, 0x18, 0xae, 0x17, 0xb9, 0x47, 0xa5, 0x43, 0x8b, 0xea, 0x6c, 0xca, 0xff, 0x0b, 0x00, - 0x00, 0xff, 0xff, 0x1a, 0x28, 0x25, 0x79, 0x42, 0x1d, 0x00, 0x00, -} diff --git a/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go b/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go deleted file mode 100644 index a69b403ce15..00000000000 --- a/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go +++ /dev/null @@ -1,79 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/empty.proto - -package empty // import "github.com/golang/protobuf/ptypes/empty" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// 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 - -// A generic empty message that you can re-use to avoid defining duplicated -// empty messages in your APIs. A typical example is to use it as the request -// or the response type of an API method. For instance: -// -// service Foo { -// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); -// } -// -// The JSON representation for `Empty` is empty JSON object `{}`. -type Empty struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Empty) Reset() { *m = Empty{} } -func (m *Empty) String() string { return proto.CompactTextString(m) } -func (*Empty) ProtoMessage() {} -func (*Empty) Descriptor() ([]byte, []int) { - return fileDescriptor_empty_39e6d6db0632e5b2, []int{0} -} -func (*Empty) XXX_WellKnownType() string { return "Empty" } -func (m *Empty) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Empty.Unmarshal(m, b) -} -func (m *Empty) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Empty.Marshal(b, m, deterministic) -} -func (dst *Empty) XXX_Merge(src proto.Message) { - xxx_messageInfo_Empty.Merge(dst, src) -} -func (m *Empty) XXX_Size() int { - return xxx_messageInfo_Empty.Size(m) -} -func (m *Empty) XXX_DiscardUnknown() { - xxx_messageInfo_Empty.DiscardUnknown(m) -} - -var xxx_messageInfo_Empty proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Empty)(nil), "google.protobuf.Empty") -} - -func init() { proto.RegisterFile("google/protobuf/empty.proto", fileDescriptor_empty_39e6d6db0632e5b2) } - -var fileDescriptor_empty_39e6d6db0632e5b2 = []byte{ - // 148 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4e, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcd, 0x2d, 0x28, - 0xa9, 0xd4, 0x03, 0x73, 0x85, 0xf8, 0x21, 0x92, 0x7a, 0x30, 0x49, 0x25, 0x76, 0x2e, 0x56, 0x57, - 0x90, 0xbc, 0x53, 0x19, 0x97, 0x70, 0x72, 0x7e, 0xae, 0x1e, 0x9a, 0xbc, 0x13, 0x17, 0x58, 0x36, - 0x00, 0xc4, 0x0d, 0x60, 0x8c, 0x52, 0x4f, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, - 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, 0x4b, 0x47, 0x58, 0x53, 0x50, 0x52, 0x59, 0x90, 0x5a, 0x0c, - 0xb1, 0xed, 0x07, 0x23, 0xe3, 0x22, 0x26, 0x66, 0xf7, 0x00, 0xa7, 0x55, 0x4c, 0x72, 0xee, 0x10, - 0x13, 0x03, 0xa0, 0xea, 0xf4, 0xc2, 0x53, 0x73, 0x72, 0xbc, 0xf3, 0xf2, 0xcb, 0xf3, 0x42, 0x40, - 0xea, 0x93, 0xd8, 0xc0, 0x06, 0x18, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x64, 0xd4, 0xb3, 0xa6, - 0xb7, 0x00, 0x00, 0x00, -} diff --git a/vendor/github.com/google/go-github/AUTHORS b/vendor/github.com/google/go-github/AUTHORS deleted file mode 100644 index 548ff1587dd..00000000000 --- a/vendor/github.com/google/go-github/AUTHORS +++ /dev/null @@ -1,171 +0,0 @@ -# This is the official list of go-github authors for copyright purposes. -# -# This does not necessarily list everyone who has contributed code, since in -# some cases, their employer may be the copyright holder. To see the full list -# of contributors, see the revision history in source control or -# https://github.com/google/go-github/graphs/contributors. -# -# Authors who wish to be recognized in this file should add themselves (or -# their employer, as appropriate). - -178inaba -Abhinav Gupta -Ahmed Hagy -Ainsley Chong -Akeda Bagus -Alec Thomas -Aleks Clark -Alex Bramley -Alexander Harkness -Allen Sun -Amey Sakhadeo -Andreas Garnæs -Andrew Ryabchun -Andy Hume -Andy Lindeman -Anshuman Bhartiya -Antoine Pelisse -Anubha Kushwaha -Aravind -Arıl Bozoluk -Austin Dizzy -Beshr Kayali -Beyang Liu -Billy Lynch -Björn Häuser -Brad Harris -Bradley Falzon -Brian Egizi -Bryan Boreham -Cami Diez -Carlos Alexandro Becker -chandresh-pancholi -Charlie Yan -Chris King -Chris Roche -Chris Schaefer -Christoph Sassenberg -Colin Misare -Craig Peterson -Cristian Maglie -Daehyeok Mun -Daniel Leavitt -Dave Du Cros -Dave Henderson -David Deng -Dennis Webb -Diego Lapiduz -Dmitri Shuralyov -dmnlk -Don Petersen -Doug Turner -Drew Fradette -Eli Uriegas -Elliott Beach -erwinvaneyk -Fabrice -Filippo Valsorda -Florian Forster -Francesc Gil -Francis -Fredrik Jönsson -Garrett Squire -Georgy Buranov -Gnahz -Google Inc. -griffin_stewie -Guz Alexander -Hanno Hecker -Hari haran -haya14busa -Huy Tr -huydx -i2bskn -Isao Jonas -isqua -Jameel Haffejee -Jan Kosecki -Jeremy Morris -Jihoon Chung -Jimmi Dyson -Joe Tsai -John Barton -John Engelman -jpbelanger-mtl -Juan Basso -Julien Rostand -Justin Abrahms -jzhoucliqr -Katrina Owen -Keita Urashima -Kevin Burke -Konrad Malawski -Kookheon Kwon -Krzysztof Kowalczyk -Kshitij Saraogi -kyokomi -Lucas Alcantara -Luke Evers -Luke Kysow -Luke Roberts -Luke Young -Maksim Zhylinski -Martin-Louis Bright -Mat Geist -Matt Brender -Matt Landis -Maxime Bury -Michael Tiller -Michał Glapa -Nathan VanBenschoten -Neil O'Toole -Nick Miyake -Nick Spragg -Nikhita Raghunath -Noah Zoschke -ns-cweber -Ondřej Kupka -Panagiotis Moustafellos -Parker Moore -Pavel Shtanko -Petr Shevtsov -Pierre Carrier -Piotr Zurek -Quinn Slack -Rackspace US, Inc. -RaviTeja Pothana -rc1140 -Red Hat, Inc. -Rob Figueiredo -Ronak Jain -Ruben Vereecken -Ryan Lower -Sahil Dua -saisi -Sam Minnée -Sander van Harmelen -Sarasa Kisaragi -Sean Wang -Sebastian Mandrean -Sebastian Mæland Pedersen -Sevki -Shawn Catanzarite -Shawn Smith -sona-tar -SoundCloud, Ltd. -Stian Eikeland -Thomas Bruyelle -Timothée Peignier -Trey Tacon -ttacon -Varadarajan Aravamudhan -Victor Castell -Victor Vrantchan -Vlad Ungureanu -Will Maier -William Bailey -Yann Malet -Yannick Utard -Yicheng Qin -Yumikiyo Osanai -Zach Latta diff --git a/vendor/github.com/google/go-github/LICENSE b/vendor/github.com/google/go-github/LICENSE deleted file mode 100644 index 53d5374a711..00000000000 --- a/vendor/github.com/google/go-github/LICENSE +++ /dev/null @@ -1,341 +0,0 @@ -Copyright (c) 2013 The go-github AUTHORS. All rights reserved. - -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. - ----------- - -Some documentation is taken from the GitHub Developer site -, which is available under the following Creative -Commons Attribution 3.0 License. This applies only to the go-github source -code and would not apply to any compiled binaries. - -THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE -COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY -COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS -AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. - -BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE -TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY -BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS -CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND -CONDITIONS. - -1. Definitions - - a. "Adaptation" means a work based upon the Work, or upon the Work and - other pre-existing works, such as a translation, adaptation, - derivative work, arrangement of music or other alterations of a - literary or artistic work, or phonogram or performance and includes - cinematographic adaptations or any other form in which the Work may be - recast, transformed, or adapted including in any form recognizably - derived from the original, except that a work that constitutes a - Collection will not be considered an Adaptation for the purpose of - this License. For the avoidance of doubt, where the Work is a musical - work, performance or phonogram, the synchronization of the Work in - timed-relation with a moving image ("synching") will be considered an - Adaptation for the purpose of this License. - b. "Collection" means a collection of literary or artistic works, such as - encyclopedias and anthologies, or performances, phonograms or - broadcasts, or other works or subject matter other than works listed - in Section 1(f) below, which, by reason of the selection and - arrangement of their contents, constitute intellectual creations, in - which the Work is included in its entirety in unmodified form along - with one or more other contributions, each constituting separate and - independent works in themselves, which together are assembled into a - collective whole. A work that constitutes a Collection will not be - considered an Adaptation (as defined above) for the purposes of this - License. - c. "Distribute" means to make available to the public the original and - copies of the Work or Adaptation, as appropriate, through sale or - other transfer of ownership. - d. "Licensor" means the individual, individuals, entity or entities that - offer(s) the Work under the terms of this License. - e. "Original Author" means, in the case of a literary or artistic work, - the individual, individuals, entity or entities who created the Work - or if no individual or entity can be identified, the publisher; and in - addition (i) in the case of a performance the actors, singers, - musicians, dancers, and other persons who act, sing, deliver, declaim, - play in, interpret or otherwise perform literary or artistic works or - expressions of folklore; (ii) in the case of a phonogram the producer - being the person or legal entity who first fixes the sounds of a - performance or other sounds; and, (iii) in the case of broadcasts, the - organization that transmits the broadcast. - f. "Work" means the literary and/or artistic work offered under the terms - of this License including without limitation any production in the - literary, scientific and artistic domain, whatever may be the mode or - form of its expression including digital form, such as a book, - pamphlet and other writing; a lecture, address, sermon or other work - of the same nature; a dramatic or dramatico-musical work; a - choreographic work or entertainment in dumb show; a musical - composition with or without words; a cinematographic work to which are - assimilated works expressed by a process analogous to cinematography; - a work of drawing, painting, architecture, sculpture, engraving or - lithography; a photographic work to which are assimilated works - expressed by a process analogous to photography; a work of applied - art; an illustration, map, plan, sketch or three-dimensional work - relative to geography, topography, architecture or science; a - performance; a broadcast; a phonogram; a compilation of data to the - extent it is protected as a copyrightable work; or a work performed by - a variety or circus performer to the extent it is not otherwise - considered a literary or artistic work. - g. "You" means an individual or entity exercising rights under this - License who has not previously violated the terms of this License with - respect to the Work, or who has received express permission from the - Licensor to exercise rights under this License despite a previous - violation. - h. "Publicly Perform" means to perform public recitations of the Work and - to communicate to the public those public recitations, by any means or - process, including by wire or wireless means or public digital - performances; to make available to the public Works in such a way that - members of the public may access these Works from a place and at a - place individually chosen by them; to perform the Work to the public - by any means or process and the communication to the public of the - performances of the Work, including by public digital performance; to - broadcast and rebroadcast the Work by any means including signs, - sounds or images. - i. "Reproduce" means to make copies of the Work by any means including - without limitation by sound or visual recordings and the right of - fixation and reproducing fixations of the Work, including storage of a - protected performance or phonogram in digital form or other electronic - medium. - -2. Fair Dealing Rights. Nothing in this License is intended to reduce, -limit, or restrict any uses free from copyright or rights arising from -limitations or exceptions that are provided for in connection with the -copyright protection under copyright law or other applicable laws. - -3. License Grant. Subject to the terms and conditions of this License, -Licensor hereby grants You a worldwide, royalty-free, non-exclusive, -perpetual (for the duration of the applicable copyright) license to -exercise the rights in the Work as stated below: - - a. to Reproduce the Work, to incorporate the Work into one or more - Collections, and to Reproduce the Work as incorporated in the - Collections; - b. to create and Reproduce Adaptations provided that any such Adaptation, - including any translation in any medium, takes reasonable steps to - clearly label, demarcate or otherwise identify that changes were made - to the original Work. For example, a translation could be marked "The - original work was translated from English to Spanish," or a - modification could indicate "The original work has been modified."; - c. to Distribute and Publicly Perform the Work including as incorporated - in Collections; and, - d. to Distribute and Publicly Perform Adaptations. - e. For the avoidance of doubt: - - i. Non-waivable Compulsory License Schemes. In those jurisdictions in - which the right to collect royalties through any statutory or - compulsory licensing scheme cannot be waived, the Licensor - reserves the exclusive right to collect such royalties for any - exercise by You of the rights granted under this License; - ii. Waivable Compulsory License Schemes. In those jurisdictions in - which the right to collect royalties through any statutory or - compulsory licensing scheme can be waived, the Licensor waives the - exclusive right to collect such royalties for any exercise by You - of the rights granted under this License; and, - iii. Voluntary License Schemes. The Licensor waives the right to - collect royalties, whether individually or, in the event that the - Licensor is a member of a collecting society that administers - voluntary licensing schemes, via that society, from any exercise - by You of the rights granted under this License. - -The above rights may be exercised in all media and formats whether now -known or hereafter devised. The above rights include the right to make -such modifications as are technically necessary to exercise the rights in -other media and formats. Subject to Section 8(f), all rights not expressly -granted by Licensor are hereby reserved. - -4. Restrictions. The license granted in Section 3 above is expressly made -subject to and limited by the following restrictions: - - a. You may Distribute or Publicly Perform the Work only under the terms - of this License. You must include a copy of, or the Uniform Resource - Identifier (URI) for, this License with every copy of the Work You - Distribute or Publicly Perform. You may not offer or impose any terms - on the Work that restrict the terms of this License or the ability of - the recipient of the Work to exercise the rights granted to that - recipient under the terms of the License. You may not sublicense the - Work. You must keep intact all notices that refer to this License and - to the disclaimer of warranties with every copy of the Work You - Distribute or Publicly Perform. When You Distribute or Publicly - Perform the Work, You may not impose any effective technological - measures on the Work that restrict the ability of a recipient of the - Work from You to exercise the rights granted to that recipient under - the terms of the License. This Section 4(a) applies to the Work as - incorporated in a Collection, but this does not require the Collection - apart from the Work itself to be made subject to the terms of this - License. If You create a Collection, upon notice from any Licensor You - must, to the extent practicable, remove from the Collection any credit - as required by Section 4(b), as requested. If You create an - Adaptation, upon notice from any Licensor You must, to the extent - practicable, remove from the Adaptation any credit as required by - Section 4(b), as requested. - b. If You Distribute, or Publicly Perform the Work or any Adaptations or - Collections, You must, unless a request has been made pursuant to - Section 4(a), keep intact all copyright notices for the Work and - provide, reasonable to the medium or means You are utilizing: (i) the - name of the Original Author (or pseudonym, if applicable) if supplied, - and/or if the Original Author and/or Licensor designate another party - or parties (e.g., a sponsor institute, publishing entity, journal) for - attribution ("Attribution Parties") in Licensor's copyright notice, - terms of service or by other reasonable means, the name of such party - or parties; (ii) the title of the Work if supplied; (iii) to the - extent reasonably practicable, the URI, if any, that Licensor - specifies to be associated with the Work, unless such URI does not - refer to the copyright notice or licensing information for the Work; - and (iv) , consistent with Section 3(b), in the case of an Adaptation, - a credit identifying the use of the Work in the Adaptation (e.g., - "French translation of the Work by Original Author," or "Screenplay - based on original Work by Original Author"). The credit required by - this Section 4 (b) may be implemented in any reasonable manner; - provided, however, that in the case of a Adaptation or Collection, at - a minimum such credit will appear, if a credit for all contributing - authors of the Adaptation or Collection appears, then as part of these - credits and in a manner at least as prominent as the credits for the - other contributing authors. For the avoidance of doubt, You may only - use the credit required by this Section for the purpose of attribution - in the manner set out above and, by exercising Your rights under this - License, You may not implicitly or explicitly assert or imply any - connection with, sponsorship or endorsement by the Original Author, - Licensor and/or Attribution Parties, as appropriate, of You or Your - use of the Work, without the separate, express prior written - permission of the Original Author, Licensor and/or Attribution - Parties. - c. Except as otherwise agreed in writing by the Licensor or as may be - otherwise permitted by applicable law, if You Reproduce, Distribute or - Publicly Perform the Work either by itself or as part of any - Adaptations or Collections, You must not distort, mutilate, modify or - take other derogatory action in relation to the Work which would be - prejudicial to the Original Author's honor or reputation. Licensor - agrees that in those jurisdictions (e.g. Japan), in which any exercise - of the right granted in Section 3(b) of this License (the right to - make Adaptations) would be deemed to be a distortion, mutilation, - modification or other derogatory action prejudicial to the Original - Author's honor and reputation, the Licensor will waive or not assert, - as appropriate, this Section, to the fullest extent permitted by the - applicable national law, to enable You to reasonably exercise Your - right under Section 3(b) of this License (right to make Adaptations) - but not otherwise. - -5. Representations, Warranties and Disclaimer - -UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR -OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY -KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, -INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, -FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF -LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, -WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION -OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. - -6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE -LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR -ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES -ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS -BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -7. Termination - - a. This License and the rights granted hereunder will terminate - automatically upon any breach by You of the terms of this License. - Individuals or entities who have received Adaptations or Collections - from You under this License, however, will not have their licenses - terminated provided such individuals or entities remain in full - compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will - survive any termination of this License. - b. Subject to the above terms and conditions, the license granted here is - perpetual (for the duration of the applicable copyright in the Work). - Notwithstanding the above, Licensor reserves the right to release the - Work under different license terms or to stop distributing the Work at - any time; provided, however that any such election will not serve to - withdraw this License (or any other license that has been, or is - required to be, granted under the terms of this License), and this - License will continue in full force and effect unless terminated as - stated above. - -8. Miscellaneous - - a. Each time You Distribute or Publicly Perform the Work or a Collection, - the Licensor offers to the recipient a license to the Work on the same - terms and conditions as the license granted to You under this License. - b. Each time You Distribute or Publicly Perform an Adaptation, Licensor - offers to the recipient a license to the original Work on the same - terms and conditions as the license granted to You under this License. - c. If any provision of this License is invalid or unenforceable under - applicable law, it shall not affect the validity or enforceability of - the remainder of the terms of this License, and without further action - by the parties to this agreement, such provision shall be reformed to - the minimum extent necessary to make such provision valid and - enforceable. - d. No term or provision of this License shall be deemed waived and no - breach consented to unless such waiver or consent shall be in writing - and signed by the party to be charged with such waiver or consent. - e. This License constitutes the entire agreement between the parties with - respect to the Work licensed here. There are no understandings, - agreements or representations with respect to the Work not specified - here. Licensor shall not be bound by any additional provisions that - may appear in any communication from You. This License may not be - modified without the mutual written agreement of the Licensor and You. - f. The rights granted under, and the subject matter referenced, in this - License were drafted utilizing the terminology of the Berne Convention - for the Protection of Literary and Artistic Works (as amended on - September 28, 1979), the Rome Convention of 1961, the WIPO Copyright - Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 - and the Universal Copyright Convention (as revised on July 24, 1971). - These rights and subject matter take effect in the relevant - jurisdiction in which the License terms are sought to be enforced - according to the corresponding provisions of the implementation of - those treaty provisions in the applicable national law. If the - standard suite of rights granted under applicable copyright law - includes additional rights not granted under this License, such - additional rights are deemed to be included in the License; this - License is not intended to restrict the license of any rights under - applicable law. - - -Creative Commons Notice - - Creative Commons is not a party to this License, and makes no warranty - whatsoever in connection with the Work. Creative Commons will not be - liable to You or any party on any legal theory for any damages - whatsoever, including without limitation any general, special, - incidental or consequential damages arising in connection to this - license. Notwithstanding the foregoing two (2) sentences, if Creative - Commons has expressly identified itself as the Licensor hereunder, it - shall have all rights and obligations of Licensor. - - Except for the limited purpose of indicating to the public that the - Work is licensed under the CCPL, Creative Commons does not authorize - the use by either party of the trademark "Creative Commons" or any - related trademark or logo of Creative Commons without the prior - written consent of Creative Commons. Any permitted use will be in - compliance with Creative Commons' then-current trademark usage - guidelines, as may be published on its website or otherwise made - available upon request from time to time. For the avoidance of doubt, - this trademark restriction does not form part of this License. - - Creative Commons may be contacted at http://creativecommons.org/. diff --git a/vendor/github.com/google/go-github/github/activity.go b/vendor/github.com/google/go-github/github/activity.go deleted file mode 100644 index d6c992c7f50..00000000000 --- a/vendor/github.com/google/go-github/github/activity.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import "context" - -// ActivityService handles communication with the activity related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/activity/ -type ActivityService service - -// FeedLink represents a link to a related resource. -type FeedLink struct { - HRef *string `json:"href,omitempty"` - Type *string `json:"type,omitempty"` -} - -// Feeds represents timeline resources in Atom format. -type Feeds struct { - TimelineURL *string `json:"timeline_url,omitempty"` - UserURL *string `json:"user_url,omitempty"` - CurrentUserPublicURL *string `json:"current_user_public_url,omitempty"` - CurrentUserURL *string `json:"current_user_url,omitempty"` - CurrentUserActorURL *string `json:"current_user_actor_url,omitempty"` - CurrentUserOrganizationURL *string `json:"current_user_organization_url,omitempty"` - CurrentUserOrganizationURLs []string `json:"current_user_organization_urls,omitempty"` - Links *struct { - Timeline *FeedLink `json:"timeline,omitempty"` - User *FeedLink `json:"user,omitempty"` - CurrentUserPublic *FeedLink `json:"current_user_public,omitempty"` - CurrentUser *FeedLink `json:"current_user,omitempty"` - CurrentUserActor *FeedLink `json:"current_user_actor,omitempty"` - CurrentUserOrganization *FeedLink `json:"current_user_organization,omitempty"` - CurrentUserOrganizations []FeedLink `json:"current_user_organizations,omitempty"` - } `json:"_links,omitempty"` -} - -// ListFeeds lists all the feeds available to the authenticated user. -// -// GitHub provides several timeline resources in Atom format: -// Timeline: The GitHub global public timeline -// User: The public timeline for any user, using URI template -// Current user public: The public timeline for the authenticated user -// Current user: The private timeline for the authenticated user -// Current user actor: The private timeline for activity created by the -// authenticated user -// Current user organizations: The private timeline for the organizations -// the authenticated user is a member of. -// -// Note: Private feeds are only returned when authenticating via Basic Auth -// since current feed URIs use the older, non revocable auth tokens. -func (s *ActivityService) ListFeeds(ctx context.Context) (*Feeds, *Response, error) { - req, err := s.client.NewRequest("GET", "feeds", nil) - if err != nil { - return nil, nil, err - } - - f := &Feeds{} - resp, err := s.client.Do(ctx, req, f) - if err != nil { - return nil, resp, err - } - - return f, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/activity_events.go b/vendor/github.com/google/go-github/github/activity_events.go deleted file mode 100644 index f337fcd2b05..00000000000 --- a/vendor/github.com/google/go-github/github/activity_events.go +++ /dev/null @@ -1,324 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "time" -) - -// Event represents a GitHub event. -type Event struct { - Type *string `json:"type,omitempty"` - Public *bool `json:"public,omitempty"` - RawPayload *json.RawMessage `json:"payload,omitempty"` - Repo *Repository `json:"repo,omitempty"` - Actor *User `json:"actor,omitempty"` - Org *Organization `json:"org,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - ID *string `json:"id,omitempty"` -} - -func (e Event) String() string { - return Stringify(e) -} - -// ParsePayload parses the event payload. For recognized event types, -// a value of the corresponding struct type will be returned. -func (e *Event) ParsePayload() (payload interface{}, err error) { - switch *e.Type { - case "CommitCommentEvent": - payload = &CommitCommentEvent{} - case "CreateEvent": - payload = &CreateEvent{} - case "DeleteEvent": - payload = &DeleteEvent{} - case "DeploymentEvent": - payload = &DeploymentEvent{} - case "DeploymentStatusEvent": - payload = &DeploymentStatusEvent{} - case "ForkEvent": - payload = &ForkEvent{} - case "GollumEvent": - payload = &GollumEvent{} - case "InstallationEvent": - payload = &InstallationEvent{} - case "InstallationRepositoriesEvent": - payload = &InstallationRepositoriesEvent{} - case "IssueCommentEvent": - payload = &IssueCommentEvent{} - case "IssuesEvent": - payload = &IssuesEvent{} - case "LabelEvent": - payload = &LabelEvent{} - case "MarketplacePurchaseEvent": - payload = &MarketplacePurchaseEvent{} - case "MemberEvent": - payload = &MemberEvent{} - case "MembershipEvent": - payload = &MembershipEvent{} - case "MilestoneEvent": - payload = &MilestoneEvent{} - case "OrganizationEvent": - payload = &OrganizationEvent{} - case "OrgBlockEvent": - payload = &OrgBlockEvent{} - case "PageBuildEvent": - payload = &PageBuildEvent{} - case "PingEvent": - payload = &PingEvent{} - case "ProjectEvent": - payload = &ProjectEvent{} - case "ProjectCardEvent": - payload = &ProjectCardEvent{} - case "ProjectColumnEvent": - payload = &ProjectColumnEvent{} - case "PublicEvent": - payload = &PublicEvent{} - case "PullRequestEvent": - payload = &PullRequestEvent{} - case "PullRequestReviewEvent": - payload = &PullRequestReviewEvent{} - case "PullRequestReviewCommentEvent": - payload = &PullRequestReviewCommentEvent{} - case "PushEvent": - payload = &PushEvent{} - case "ReleaseEvent": - payload = &ReleaseEvent{} - case "RepositoryEvent": - payload = &RepositoryEvent{} - case "StatusEvent": - payload = &StatusEvent{} - case "TeamEvent": - payload = &TeamEvent{} - case "TeamAddEvent": - payload = &TeamAddEvent{} - case "WatchEvent": - payload = &WatchEvent{} - } - err = json.Unmarshal(*e.RawPayload, &payload) - return payload, err -} - -// Payload returns the parsed event payload. For recognized event types, -// a value of the corresponding struct type will be returned. -// -// Deprecated: Use ParsePayload instead, which returns an error -// rather than panics if JSON unmarshaling raw payload fails. -func (e *Event) Payload() (payload interface{}) { - var err error - payload, err = e.ParsePayload() - if err != nil { - panic(err) - } - return payload -} - -// ListEvents drinks from the firehose of all public events across GitHub. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-public-events -func (s *ActivityService) ListEvents(ctx context.Context, opt *ListOptions) ([]*Event, *Response, error) { - u, err := addOptions("events", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListRepositoryEvents lists events for a repository. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-repository-events -func (s *ActivityService) ListRepositoryEvents(ctx context.Context, owner, repo string, opt *ListOptions) ([]*Event, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/events", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListIssueEventsForRepository lists issue events for a repository. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-issue-events-for-a-repository -func (s *ActivityService) ListIssueEventsForRepository(ctx context.Context, owner, repo string, opt *ListOptions) ([]*IssueEvent, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/events", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*IssueEvent - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListEventsForRepoNetwork lists public events for a network of repositories. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-public-events-for-a-network-of-repositories -func (s *ActivityService) ListEventsForRepoNetwork(ctx context.Context, owner, repo string, opt *ListOptions) ([]*Event, *Response, error) { - u := fmt.Sprintf("networks/%v/%v/events", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListEventsForOrganization lists public events for an organization. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-public-events-for-an-organization -func (s *ActivityService) ListEventsForOrganization(ctx context.Context, org string, opt *ListOptions) ([]*Event, *Response, error) { - u := fmt.Sprintf("orgs/%v/events", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListEventsPerformedByUser lists the events performed by a user. If publicOnly is -// true, only public events will be returned. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-events-performed-by-a-user -func (s *ActivityService) ListEventsPerformedByUser(ctx context.Context, user string, publicOnly bool, opt *ListOptions) ([]*Event, *Response, error) { - var u string - if publicOnly { - u = fmt.Sprintf("users/%v/events/public", user) - } else { - u = fmt.Sprintf("users/%v/events", user) - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListEventsReceivedByUser lists the events received by a user. If publicOnly is -// true, only public events will be returned. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-events-that-a-user-has-received -func (s *ActivityService) ListEventsReceivedByUser(ctx context.Context, user string, publicOnly bool, opt *ListOptions) ([]*Event, *Response, error) { - var u string - if publicOnly { - u = fmt.Sprintf("users/%v/received_events/public", user) - } else { - u = fmt.Sprintf("users/%v/received_events", user) - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListUserEventsForOrganization provides the user’s organization dashboard. You -// must be authenticated as the user to view this. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-events-for-an-organization -func (s *ActivityService) ListUserEventsForOrganization(ctx context.Context, org, user string, opt *ListOptions) ([]*Event, *Response, error) { - u := fmt.Sprintf("users/%v/events/orgs/%v", user, org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/activity_notifications.go b/vendor/github.com/google/go-github/github/activity_notifications.go deleted file mode 100644 index 45c8b2aeced..00000000000 --- a/vendor/github.com/google/go-github/github/activity_notifications.go +++ /dev/null @@ -1,223 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// Notification identifies a GitHub notification for a user. -type Notification struct { - ID *string `json:"id,omitempty"` - Repository *Repository `json:"repository,omitempty"` - Subject *NotificationSubject `json:"subject,omitempty"` - - // Reason identifies the event that triggered the notification. - // - // GitHub API docs: https://developer.github.com/v3/activity/notifications/#notification-reasons - Reason *string `json:"reason,omitempty"` - - Unread *bool `json:"unread,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - LastReadAt *time.Time `json:"last_read_at,omitempty"` - URL *string `json:"url,omitempty"` -} - -// NotificationSubject identifies the subject of a notification. -type NotificationSubject struct { - Title *string `json:"title,omitempty"` - URL *string `json:"url,omitempty"` - LatestCommentURL *string `json:"latest_comment_url,omitempty"` - Type *string `json:"type,omitempty"` -} - -// NotificationListOptions specifies the optional parameters to the -// ActivityService.ListNotifications method. -type NotificationListOptions struct { - All bool `url:"all,omitempty"` - Participating bool `url:"participating,omitempty"` - Since time.Time `url:"since,omitempty"` - Before time.Time `url:"before,omitempty"` - - ListOptions -} - -// ListNotifications lists all notifications for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#list-your-notifications -func (s *ActivityService) ListNotifications(ctx context.Context, opt *NotificationListOptions) ([]*Notification, *Response, error) { - u := fmt.Sprintf("notifications") - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var notifications []*Notification - resp, err := s.client.Do(ctx, req, ¬ifications) - if err != nil { - return nil, resp, err - } - - return notifications, resp, nil -} - -// ListRepositoryNotifications lists all notifications in a given repository -// for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#list-your-notifications-in-a-repository -func (s *ActivityService) ListRepositoryNotifications(ctx context.Context, owner, repo string, opt *NotificationListOptions) ([]*Notification, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/notifications", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var notifications []*Notification - resp, err := s.client.Do(ctx, req, ¬ifications) - if err != nil { - return nil, resp, err - } - - return notifications, resp, nil -} - -type markReadOptions struct { - LastReadAt time.Time `json:"last_read_at,omitempty"` -} - -// MarkNotificationsRead marks all notifications up to lastRead as read. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#mark-as-read -func (s *ActivityService) MarkNotificationsRead(ctx context.Context, lastRead time.Time) (*Response, error) { - opts := &markReadOptions{ - LastReadAt: lastRead, - } - req, err := s.client.NewRequest("PUT", "notifications", opts) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// MarkRepositoryNotificationsRead marks all notifications up to lastRead in -// the specified repository as read. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#mark-notifications-as-read-in-a-repository -func (s *ActivityService) MarkRepositoryNotificationsRead(ctx context.Context, owner, repo string, lastRead time.Time) (*Response, error) { - opts := &markReadOptions{ - LastReadAt: lastRead, - } - u := fmt.Sprintf("repos/%v/%v/notifications", owner, repo) - req, err := s.client.NewRequest("PUT", u, opts) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// GetThread gets the specified notification thread. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#view-a-single-thread -func (s *ActivityService) GetThread(ctx context.Context, id string) (*Notification, *Response, error) { - u := fmt.Sprintf("notifications/threads/%v", id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - notification := new(Notification) - resp, err := s.client.Do(ctx, req, notification) - if err != nil { - return nil, resp, err - } - - return notification, resp, nil -} - -// MarkThreadRead marks the specified thread as read. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#mark-a-thread-as-read -func (s *ActivityService) MarkThreadRead(ctx context.Context, id string) (*Response, error) { - u := fmt.Sprintf("notifications/threads/%v", id) - - req, err := s.client.NewRequest("PATCH", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// GetThreadSubscription checks to see if the authenticated user is subscribed -// to a thread. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#get-a-thread-subscription -func (s *ActivityService) GetThreadSubscription(ctx context.Context, id string) (*Subscription, *Response, error) { - u := fmt.Sprintf("notifications/threads/%v/subscription", id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - sub := new(Subscription) - resp, err := s.client.Do(ctx, req, sub) - if err != nil { - return nil, resp, err - } - - return sub, resp, nil -} - -// SetThreadSubscription sets the subscription for the specified thread for the -// authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#set-a-thread-subscription -func (s *ActivityService) SetThreadSubscription(ctx context.Context, id string, subscription *Subscription) (*Subscription, *Response, error) { - u := fmt.Sprintf("notifications/threads/%v/subscription", id) - - req, err := s.client.NewRequest("PUT", u, subscription) - if err != nil { - return nil, nil, err - } - - sub := new(Subscription) - resp, err := s.client.Do(ctx, req, sub) - if err != nil { - return nil, resp, err - } - - return sub, resp, nil -} - -// DeleteThreadSubscription deletes the subscription for the specified thread -// for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#delete-a-thread-subscription -func (s *ActivityService) DeleteThreadSubscription(ctx context.Context, id string) (*Response, error) { - u := fmt.Sprintf("notifications/threads/%v/subscription", id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/activity_star.go b/vendor/github.com/google/go-github/github/activity_star.go deleted file mode 100644 index d5b067127c6..00000000000 --- a/vendor/github.com/google/go-github/github/activity_star.go +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// StarredRepository is returned by ListStarred. -type StarredRepository struct { - StarredAt *Timestamp `json:"starred_at,omitempty"` - Repository *Repository `json:"repo,omitempty"` -} - -// Stargazer represents a user that has starred a repository. -type Stargazer struct { - StarredAt *Timestamp `json:"starred_at,omitempty"` - User *User `json:"user,omitempty"` -} - -// ListStargazers lists people who have starred the specified repo. -// -// GitHub API docs: https://developer.github.com/v3/activity/starring/#list-stargazers -func (s *ActivityService) ListStargazers(ctx context.Context, owner, repo string, opt *ListOptions) ([]*Stargazer, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/stargazers", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeStarringPreview) - - var stargazers []*Stargazer - resp, err := s.client.Do(ctx, req, &stargazers) - if err != nil { - return nil, resp, err - } - - return stargazers, resp, nil -} - -// ActivityListStarredOptions specifies the optional parameters to the -// ActivityService.ListStarred method. -type ActivityListStarredOptions struct { - // How to sort the repository list. Possible values are: created, updated, - // pushed, full_name. Default is "full_name". - Sort string `url:"sort,omitempty"` - - // Direction in which to sort repositories. Possible values are: asc, desc. - // Default is "asc" when sort is "full_name", otherwise default is "desc". - Direction string `url:"direction,omitempty"` - - ListOptions -} - -// ListStarred lists all the repos starred by a user. Passing the empty string -// will list the starred repositories for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/starring/#list-repositories-being-starred -func (s *ActivityService) ListStarred(ctx context.Context, user string, opt *ActivityListStarredOptions) ([]*StarredRepository, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/starred", user) - } else { - u = "user/starred" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeStarringPreview) - - var repos []*StarredRepository - resp, err := s.client.Do(ctx, req, &repos) - if err != nil { - return nil, resp, err - } - - return repos, resp, nil -} - -// IsStarred checks if a repository is starred by authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/starring/#check-if-you-are-starring-a-repository -func (s *ActivityService) IsStarred(ctx context.Context, owner, repo string) (bool, *Response, error) { - u := fmt.Sprintf("user/starred/%v/%v", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - resp, err := s.client.Do(ctx, req, nil) - starred, err := parseBoolResponse(err) - return starred, resp, err -} - -// Star a repository as the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/starring/#star-a-repository -func (s *ActivityService) Star(ctx context.Context, owner, repo string) (*Response, error) { - u := fmt.Sprintf("user/starred/%v/%v", owner, repo) - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// Unstar a repository as the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/starring/#unstar-a-repository -func (s *ActivityService) Unstar(ctx context.Context, owner, repo string) (*Response, error) { - u := fmt.Sprintf("user/starred/%v/%v", owner, repo) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/activity_watching.go b/vendor/github.com/google/go-github/github/activity_watching.go deleted file mode 100644 index c749ca86e7c..00000000000 --- a/vendor/github.com/google/go-github/github/activity_watching.go +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// Subscription identifies a repository or thread subscription. -type Subscription struct { - Subscribed *bool `json:"subscribed,omitempty"` - Ignored *bool `json:"ignored,omitempty"` - Reason *string `json:"reason,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - URL *string `json:"url,omitempty"` - - // only populated for repository subscriptions - RepositoryURL *string `json:"repository_url,omitempty"` - - // only populated for thread subscriptions - ThreadURL *string `json:"thread_url,omitempty"` -} - -// ListWatchers lists watchers of a particular repo. -// -// GitHub API docs: https://developer.github.com/v3/activity/watching/#list-watchers -func (s *ActivityService) ListWatchers(ctx context.Context, owner, repo string, opt *ListOptions) ([]*User, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/subscribers", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var watchers []*User - resp, err := s.client.Do(ctx, req, &watchers) - if err != nil { - return nil, resp, err - } - - return watchers, resp, nil -} - -// ListWatched lists the repositories the specified user is watching. Passing -// the empty string will fetch watched repos for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/watching/#list-repositories-being-watched -func (s *ActivityService) ListWatched(ctx context.Context, user string, opt *ListOptions) ([]*Repository, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/subscriptions", user) - } else { - u = "user/subscriptions" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var watched []*Repository - resp, err := s.client.Do(ctx, req, &watched) - if err != nil { - return nil, resp, err - } - - return watched, resp, nil -} - -// GetRepositorySubscription returns the subscription for the specified -// repository for the authenticated user. If the authenticated user is not -// watching the repository, a nil Subscription is returned. -// -// GitHub API docs: https://developer.github.com/v3/activity/watching/#get-a-repository-subscription -func (s *ActivityService) GetRepositorySubscription(ctx context.Context, owner, repo string) (*Subscription, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/subscription", owner, repo) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - sub := new(Subscription) - resp, err := s.client.Do(ctx, req, sub) - if err != nil { - // if it's just a 404, don't return that as an error - _, err = parseBoolResponse(err) - return nil, resp, err - } - - return sub, resp, nil -} - -// SetRepositorySubscription sets the subscription for the specified repository -// for the authenticated user. -// -// To watch a repository, set subscription.Subscribed to true. -// To ignore notifications made within a repository, set subscription.Ignored to true. -// To stop watching a repository, use DeleteRepositorySubscription. -// -// GitHub API docs: https://developer.github.com/v3/activity/watching/#set-a-repository-subscription -func (s *ActivityService) SetRepositorySubscription(ctx context.Context, owner, repo string, subscription *Subscription) (*Subscription, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/subscription", owner, repo) - - req, err := s.client.NewRequest("PUT", u, subscription) - if err != nil { - return nil, nil, err - } - - sub := new(Subscription) - resp, err := s.client.Do(ctx, req, sub) - if err != nil { - return nil, resp, err - } - - return sub, resp, nil -} - -// DeleteRepositorySubscription deletes the subscription for the specified -// repository for the authenticated user. -// -// This is used to stop watching a repository. To control whether or not to -// receive notifications from a repository, use SetRepositorySubscription. -// -// GitHub API docs: https://developer.github.com/v3/activity/watching/#delete-a-repository-subscription -func (s *ActivityService) DeleteRepositorySubscription(ctx context.Context, owner, repo string) (*Response, error) { - u := fmt.Sprintf("repos/%s/%s/subscription", owner, repo) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/admin.go b/vendor/github.com/google/go-github/github/admin.go deleted file mode 100644 index 2d96733a1c7..00000000000 --- a/vendor/github.com/google/go-github/github/admin.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// AdminService handles communication with the admin related methods of the -// GitHub API. These API routes are normally only accessible for GitHub -// Enterprise installations. -// -// GitHub API docs: https://developer.github.com/v3/enterprise/ -type AdminService service - -// TeamLDAPMapping represents the mapping between a GitHub team and an LDAP group. -type TeamLDAPMapping struct { - ID *int64 `json:"id,omitempty"` - LDAPDN *string `json:"ldap_dn,omitempty"` - URL *string `json:"url,omitempty"` - Name *string `json:"name,omitempty"` - Slug *string `json:"slug,omitempty"` - Description *string `json:"description,omitempty"` - Privacy *string `json:"privacy,omitempty"` - Permission *string `json:"permission,omitempty"` - - MembersURL *string `json:"members_url,omitempty"` - RepositoriesURL *string `json:"repositories_url,omitempty"` -} - -func (m TeamLDAPMapping) String() string { - return Stringify(m) -} - -// UserLDAPMapping represents the mapping between a GitHub user and an LDAP user. -type UserLDAPMapping struct { - ID *int64 `json:"id,omitempty"` - LDAPDN *string `json:"ldap_dn,omitempty"` - Login *string `json:"login,omitempty"` - AvatarURL *string `json:"avatar_url,omitempty"` - GravatarID *string `json:"gravatar_id,omitempty"` - Type *string `json:"type,omitempty"` - SiteAdmin *bool `json:"site_admin,omitempty"` - - URL *string `json:"url,omitempty"` - EventsURL *string `json:"events_url,omitempty"` - FollowingURL *string `json:"following_url,omitempty"` - FollowersURL *string `json:"followers_url,omitempty"` - GistsURL *string `json:"gists_url,omitempty"` - OrganizationsURL *string `json:"organizations_url,omitempty"` - ReceivedEventsURL *string `json:"received_events_url,omitempty"` - ReposURL *string `json:"repos_url,omitempty"` - StarredURL *string `json:"starred_url,omitempty"` - SubscriptionsURL *string `json:"subscriptions_url,omitempty"` -} - -func (m UserLDAPMapping) String() string { - return Stringify(m) -} - -// UpdateUserLDAPMapping updates the mapping between a GitHub user and an LDAP user. -// -// GitHub API docs: https://developer.github.com/v3/enterprise/ldap/#update-ldap-mapping-for-a-user -func (s *AdminService) UpdateUserLDAPMapping(ctx context.Context, user string, mapping *UserLDAPMapping) (*UserLDAPMapping, *Response, error) { - u := fmt.Sprintf("admin/ldap/users/%v/mapping", user) - req, err := s.client.NewRequest("PATCH", u, mapping) - if err != nil { - return nil, nil, err - } - - m := new(UserLDAPMapping) - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// UpdateTeamLDAPMapping updates the mapping between a GitHub team and an LDAP group. -// -// GitHub API docs: https://developer.github.com/v3/enterprise/ldap/#update-ldap-mapping-for-a-team -func (s *AdminService) UpdateTeamLDAPMapping(ctx context.Context, team int64, mapping *TeamLDAPMapping) (*TeamLDAPMapping, *Response, error) { - u := fmt.Sprintf("admin/ldap/teams/%v/mapping", team) - req, err := s.client.NewRequest("PATCH", u, mapping) - if err != nil { - return nil, nil, err - } - - m := new(TeamLDAPMapping) - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/admin_stats.go b/vendor/github.com/google/go-github/github/admin_stats.go deleted file mode 100644 index 1550d250ef0..00000000000 --- a/vendor/github.com/google/go-github/github/admin_stats.go +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// AdminStats represents a variety of stats of a Github Enterprise -// installation. -type AdminStats struct { - Issues *IssueStats `json:"issues,omitempty"` - Hooks *HookStats `json:"hooks,omitempty"` - Milestones *MilestoneStats `json:"milestones,omitempty"` - Orgs *OrgStats `json:"orgs,omitempty"` - Comments *CommentStats `json:"comments,omitempty"` - Pages *PageStats `json:"pages,omitempty"` - Users *UserStats `json:"users,omitempty"` - Gists *GistStats `json:"gists,omitempty"` - Pulls *PullStats `json:"pulls,omitempty"` - Repos *RepoStats `json:"repos,omitempty"` -} - -func (s AdminStats) String() string { - return Stringify(s) -} - -// IssueStats represents the number of total, open and closed issues. -type IssueStats struct { - TotalIssues *int `json:"total_issues,omitempty"` - OpenIssues *int `json:"open_issues,omitempty"` - ClosedIssues *int `json:"closed_issues,omitempty"` -} - -func (s IssueStats) String() string { - return Stringify(s) -} - -// HookStats represents the number of total, active and inactive hooks. -type HookStats struct { - TotalHooks *int `json:"total_hooks,omitempty"` - ActiveHooks *int `json:"active_hooks,omitempty"` - InactiveHooks *int `json:"inactive_hooks,omitempty"` -} - -func (s HookStats) String() string { - return Stringify(s) -} - -// MilestoneStats represents the number of total, open and close milestones. -type MilestoneStats struct { - TotalMilestones *int `json:"total_milestones,omitempty"` - OpenMilestones *int `json:"open_milestones,omitempty"` - ClosedMilestones *int `json:"closed_milestones,omitempty"` -} - -func (s MilestoneStats) String() string { - return Stringify(s) -} - -// OrgStats represents the number of total, disabled organizations and the team -// and team member count. -type OrgStats struct { - TotalOrgs *int `json:"total_orgs,omitempty"` - DisabledOrgs *int `json:"disabled_orgs,omitempty"` - TotalTeams *int `json:"total_teams,omitempty"` - TotalTeamMembers *int `json:"total_team_members,omitempty"` -} - -func (s OrgStats) String() string { - return Stringify(s) -} - -// CommentStats represents the number of total comments on commits, gists, issues -// and pull requests. -type CommentStats struct { - TotalCommitComments *int `json:"total_commit_comments,omitempty"` - TotalGistComments *int `json:"total_gist_comments,omitempty"` - TotalIssueComments *int `json:"total_issue_comments,omitempty"` - TotalPullRequestComments *int `json:"total_pull_request_comments,omitempty"` -} - -func (s CommentStats) String() string { - return Stringify(s) -} - -// PageStats represents the total number of github pages. -type PageStats struct { - TotalPages *int `json:"total_pages,omitempty"` -} - -func (s PageStats) String() string { - return Stringify(s) -} - -// UserStats represents the number of total, admin and suspended users. -type UserStats struct { - TotalUsers *int `json:"total_users,omitempty"` - AdminUsers *int `json:"admin_users,omitempty"` - SuspendedUsers *int `json:"suspended_users,omitempty"` -} - -func (s UserStats) String() string { - return Stringify(s) -} - -//GistStats represents the number of total, private and public gists. -type GistStats struct { - TotalGists *int `json:"total_gists,omitempty"` - PrivateGists *int `json:"private_gists,omitempty"` - PublicGists *int `json:"public_gists,omitempty"` -} - -func (s GistStats) String() string { - return Stringify(s) -} - -// PullStats represents the number of total, merged, mergable and unmergeable -// pull-requests. -type PullStats struct { - TotalPulls *int `json:"total_pulls,omitempty"` - MergedPulls *int `json:"merged_pulls,omitempty"` - MergablePulls *int `json:"mergeable_pulls,omitempty"` - UnmergablePulls *int `json:"unmergeable_pulls,omitempty"` -} - -func (s PullStats) String() string { - return Stringify(s) -} - -// RepoStats represents the number of total, root, fork, organization repositories -// together with the total number of pushes and wikis. -type RepoStats struct { - TotalRepos *int `json:"total_repos,omitempty"` - RootRepos *int `json:"root_repos,omitempty"` - ForkRepos *int `json:"fork_repos,omitempty"` - OrgRepos *int `json:"org_repos,omitempty"` - TotalPushes *int `json:"total_pushes,omitempty"` - TotalWikis *int `json:"total_wikis,omitempty"` -} - -func (s RepoStats) String() string { - return Stringify(s) -} - -// GetAdminStats returns a variety of metrics about a Github Enterprise -// installation. -// -// Please note that this is only available to site administrators, -// otherwise it will error with a 404 not found (instead of 401 or 403). -// -// GitHub API docs: https://developer.github.com/v3/enterprise-admin/admin_stats/ -func (s *AdminService) GetAdminStats(ctx context.Context) (*AdminStats, *Response, error) { - u := fmt.Sprintf("enterprise/stats/all") - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - m := new(AdminStats) - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/apps.go b/vendor/github.com/google/go-github/github/apps.go deleted file mode 100644 index 740642e62f6..00000000000 --- a/vendor/github.com/google/go-github/github/apps.go +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// AppsService provides access to the installation related functions -// in the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/apps/ -type AppsService service - -// App represents a GitHub App. -type App struct { - ID *int64 `json:"id,omitempty"` - Owner *User `json:"owner,omitempty"` - Name *string `json:"name,omitempty"` - Description *string `json:"description,omitempty"` - ExternalURL *string `json:"external_url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` -} - -// InstallationToken represents an installation token. -type InstallationToken struct { - Token *string `json:"token,omitempty"` - ExpiresAt *time.Time `json:"expires_at,omitempty"` -} - -// Get a single GitHub App. Passing the empty string will get -// the authenticated GitHub App. -// -// Note: appSlug is just the URL-friendly name of your GitHub App. -// You can find this on the settings page for your GitHub App -// (e.g., https://github.com/settings/apps/:app_slug). -// -// GitHub API docs: https://developer.github.com/v3/apps/#get-a-single-github-app -func (s *AppsService) Get(ctx context.Context, appSlug string) (*App, *Response, error) { - var u string - if appSlug != "" { - u = fmt.Sprintf("apps/%v", appSlug) - } else { - u = "app" - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeIntegrationPreview) - - app := new(App) - resp, err := s.client.Do(ctx, req, app) - if err != nil { - return nil, resp, err - } - - return app, resp, nil -} - -// ListInstallations lists the installations that the current GitHub App has. -// -// GitHub API docs: https://developer.github.com/v3/apps/#find-installations -func (s *AppsService) ListInstallations(ctx context.Context, opt *ListOptions) ([]*Installation, *Response, error) { - u, err := addOptions("app/installations", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeIntegrationPreview) - - var i []*Installation - resp, err := s.client.Do(ctx, req, &i) - if err != nil { - return nil, resp, err - } - - return i, resp, nil -} - -// GetInstallation returns the specified installation. -// -// GitHub API docs: https://developer.github.com/v3/apps/#get-a-single-installation -func (s *AppsService) GetInstallation(ctx context.Context, id int64) (*Installation, *Response, error) { - u := fmt.Sprintf("app/installations/%v", id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeIntegrationPreview) - - i := new(Installation) - resp, err := s.client.Do(ctx, req, i) - if err != nil { - return nil, resp, err - } - - return i, resp, nil -} - -// ListUserInstallations lists installations that are accessible to the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/apps/#list-installations-for-user -func (s *AppsService) ListUserInstallations(ctx context.Context, opt *ListOptions) ([]*Installation, *Response, error) { - u, err := addOptions("user/installations", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeIntegrationPreview) - - var i struct { - Installations []*Installation `json:"installations"` - } - resp, err := s.client.Do(ctx, req, &i) - if err != nil { - return nil, resp, err - } - - return i.Installations, resp, nil -} - -// CreateInstallationToken creates a new installation token. -// -// GitHub API docs: https://developer.github.com/v3/apps/#create-a-new-installation-token -func (s *AppsService) CreateInstallationToken(ctx context.Context, id int64) (*InstallationToken, *Response, error) { - u := fmt.Sprintf("installations/%v/access_tokens", id) - - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeIntegrationPreview) - - t := new(InstallationToken) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/apps_installation.go b/vendor/github.com/google/go-github/github/apps_installation.go deleted file mode 100644 index af85cb87f19..00000000000 --- a/vendor/github.com/google/go-github/github/apps_installation.go +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// Installation represents a GitHub Apps installation. -type Installation struct { - ID *int64 `json:"id,omitempty"` - Account *User `json:"account,omitempty"` - AccessTokensURL *string `json:"access_tokens_url,omitempty"` - RepositoriesURL *string `json:"repositories_url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` -} - -func (i Installation) String() string { - return Stringify(i) -} - -// ListRepos lists the repositories that are accessible to the authenticated installation. -// -// GitHub API docs: https://developer.github.com/v3/apps/installations/#list-repositories -func (s *AppsService) ListRepos(ctx context.Context, opt *ListOptions) ([]*Repository, *Response, error) { - u, err := addOptions("installation/repositories", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeIntegrationPreview) - - var r struct { - Repositories []*Repository `json:"repositories"` - } - resp, err := s.client.Do(ctx, req, &r) - if err != nil { - return nil, resp, err - } - - return r.Repositories, resp, nil -} - -// ListUserRepos lists repositories that are accessible -// to the authenticated user for an installation. -// -// GitHub API docs: https://developer.github.com/v3/apps/installations/#list-repositories-accessible-to-the-user-for-an-installation -func (s *AppsService) ListUserRepos(ctx context.Context, id int64, opt *ListOptions) ([]*Repository, *Response, error) { - u := fmt.Sprintf("user/installations/%v/repositories", id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeIntegrationPreview) - - var r struct { - Repositories []*Repository `json:"repositories"` - } - resp, err := s.client.Do(ctx, req, &r) - if err != nil { - return nil, resp, err - } - - return r.Repositories, resp, nil -} - -// AddRepository adds a single repository to an installation. -// -// GitHub API docs: https://developer.github.com/v3/apps/installations/#add-repository-to-installation -func (s *AppsService) AddRepository(ctx context.Context, instID, repoID int64) (*Repository, *Response, error) { - u := fmt.Sprintf("apps/installations/%v/repositories/%v", instID, repoID) - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, nil, err - } - - r := new(Repository) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// RemoveRepository removes a single repository from an installation. -// -// GitHub docs: https://developer.github.com/v3/apps/installations/#remove-repository-from-installation -func (s *AppsService) RemoveRepository(ctx context.Context, instID, repoID int64) (*Response, error) { - u := fmt.Sprintf("apps/installations/%v/repositories/%v", instID, repoID) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/apps_marketplace.go b/vendor/github.com/google/go-github/github/apps_marketplace.go deleted file mode 100644 index 089cdbf7ee1..00000000000 --- a/vendor/github.com/google/go-github/github/apps_marketplace.go +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// MarketplaceService handles communication with the marketplace related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/apps/marketplace/ -type MarketplaceService struct { - client *Client - // Stubbed controls whether endpoints that return stubbed data are used - // instead of production endpoints. Stubbed data is fake data that's useful - // for testing your GitHub Apps. Stubbed data is hard-coded and will not - // change based on actual subscriptions. - // - // GitHub API docs: https://developer.github.com/v3/apps/marketplace/ - Stubbed bool -} - -// MarketplacePlan represents a GitHub Apps Marketplace Listing Plan. -type MarketplacePlan struct { - URL *string `json:"url,omitempty"` - AccountsURL *string `json:"accounts_url,omitempty"` - ID *int64 `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Description *string `json:"description,omitempty"` - MonthlyPriceInCents *int `json:"monthly_price_in_cents,omitempty"` - YearlyPriceInCents *int `json:"yearly_price_in_cents,omitempty"` - PriceModel *string `json:"price_model,omitempty"` - UnitName *string `json:"unit_name,omitempty"` - Bullets *[]string `json:"bullets,omitempty"` -} - -// MarketplacePurchase represents a GitHub Apps Marketplace Purchase. -type MarketplacePurchase struct { - BillingCycle *string `json:"billing_cycle,omitempty"` - NextBillingDate *string `json:"next_billing_date,omitempty"` - UnitCount *int `json:"unit_count,omitempty"` - Plan *MarketplacePlan `json:"plan,omitempty"` - Account *MarketplacePlanAccount `json:"account,omitempty"` -} - -// MarketplacePlanAccount represents a GitHub Account (user or organization) on a specific plan. -type MarketplacePlanAccount struct { - URL *string `json:"url,omitempty"` - Type *string `json:"type,omitempty"` - ID *int64 `json:"id,omitempty"` - Login *string `json:"login,omitempty"` - Email *string `json:"email,omitempty"` - OrganizationBillingEmail *string `json:"organization_billing_email,omitempty"` - MarketplacePurchase *MarketplacePurchase `json:"marketplace_purchase,omitempty"` -} - -// ListPlans lists all plans for your Marketplace listing. -// -// GitHub API docs: https://developer.github.com/v3/apps/marketplace/#list-all-plans-for-your-marketplace-listing -func (s *MarketplaceService) ListPlans(ctx context.Context, opt *ListOptions) ([]*MarketplacePlan, *Response, error) { - uri := s.marketplaceURI("plans") - u, err := addOptions(uri, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMarketplacePreview) - - var plans []*MarketplacePlan - resp, err := s.client.Do(ctx, req, &plans) - if err != nil { - return nil, resp, err - } - - return plans, resp, nil -} - -// ListPlanAccountsForPlan lists all GitHub accounts (user or organization) on a specific plan. -// -// GitHub API docs: https://developer.github.com/v3/apps/marketplace/#list-all-github-accounts-user-or-organization-on-a-specific-plan -func (s *MarketplaceService) ListPlanAccountsForPlan(ctx context.Context, planID int64, opt *ListOptions) ([]*MarketplacePlanAccount, *Response, error) { - uri := s.marketplaceURI(fmt.Sprintf("plans/%v/accounts", planID)) - u, err := addOptions(uri, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMarketplacePreview) - - var accounts []*MarketplacePlanAccount - resp, err := s.client.Do(ctx, req, &accounts) - if err != nil { - return nil, resp, err - } - - return accounts, resp, nil -} - -// ListPlanAccountsForAccount lists all GitHub accounts (user or organization) associated with an account. -// -// GitHub API docs: https://developer.github.com/v3/apps/marketplace/#check-if-a-github-account-is-associated-with-any-marketplace-listing -func (s *MarketplaceService) ListPlanAccountsForAccount(ctx context.Context, accountID int64, opt *ListOptions) ([]*MarketplacePlanAccount, *Response, error) { - uri := s.marketplaceURI(fmt.Sprintf("accounts/%v", accountID)) - u, err := addOptions(uri, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMarketplacePreview) - - var accounts []*MarketplacePlanAccount - resp, err := s.client.Do(ctx, req, &accounts) - if err != nil { - return nil, resp, err - } - - return accounts, resp, nil -} - -// ListMarketplacePurchasesForUser lists all GitHub marketplace purchases made by a user. -// -// GitHub API docs: https://developer.github.com/v3/apps/marketplace/#get-a-users-marketplace-purchases -func (s *MarketplaceService) ListMarketplacePurchasesForUser(ctx context.Context, opt *ListOptions) ([]*MarketplacePurchase, *Response, error) { - uri := "user/marketplace_purchases" - if s.Stubbed { - uri = "user/marketplace_purchases/stubbed" - } - - u, err := addOptions(uri, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMarketplacePreview) - - var purchases []*MarketplacePurchase - resp, err := s.client.Do(ctx, req, &purchases) - if err != nil { - return nil, resp, err - } - - return purchases, resp, nil -} - -func (s *MarketplaceService) marketplaceURI(endpoint string) string { - url := "marketplace_listing" - if s.Stubbed { - url = "marketplace_listing/stubbed" - } - return url + "/" + endpoint -} diff --git a/vendor/github.com/google/go-github/github/authorizations.go b/vendor/github.com/google/go-github/github/authorizations.go deleted file mode 100644 index 190205b02ac..00000000000 --- a/vendor/github.com/google/go-github/github/authorizations.go +++ /dev/null @@ -1,435 +0,0 @@ -// Copyright 2015 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// Scope models a GitHub authorization scope. -// -// GitHub API docs: https://developer.github.com/v3/oauth/#scopes -type Scope string - -// This is the set of scopes for GitHub API V3 -const ( - ScopeNone Scope = "(no scope)" // REVISIT: is this actually returned, or just a documentation artifact? - ScopeUser Scope = "user" - ScopeUserEmail Scope = "user:email" - ScopeUserFollow Scope = "user:follow" - ScopePublicRepo Scope = "public_repo" - ScopeRepo Scope = "repo" - ScopeRepoDeployment Scope = "repo_deployment" - ScopeRepoStatus Scope = "repo:status" - ScopeDeleteRepo Scope = "delete_repo" - ScopeNotifications Scope = "notifications" - ScopeGist Scope = "gist" - ScopeReadRepoHook Scope = "read:repo_hook" - ScopeWriteRepoHook Scope = "write:repo_hook" - ScopeAdminRepoHook Scope = "admin:repo_hook" - ScopeAdminOrgHook Scope = "admin:org_hook" - ScopeReadOrg Scope = "read:org" - ScopeWriteOrg Scope = "write:org" - ScopeAdminOrg Scope = "admin:org" - ScopeReadPublicKey Scope = "read:public_key" - ScopeWritePublicKey Scope = "write:public_key" - ScopeAdminPublicKey Scope = "admin:public_key" - ScopeReadGPGKey Scope = "read:gpg_key" - ScopeWriteGPGKey Scope = "write:gpg_key" - ScopeAdminGPGKey Scope = "admin:gpg_key" -) - -// AuthorizationsService handles communication with the authorization related -// methods of the GitHub API. -// -// This service requires HTTP Basic Authentication; it cannot be accessed using -// an OAuth token. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/ -type AuthorizationsService service - -// Authorization represents an individual GitHub authorization. -type Authorization struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - Scopes []Scope `json:"scopes,omitempty"` - Token *string `json:"token,omitempty"` - TokenLastEight *string `json:"token_last_eight,omitempty"` - HashedToken *string `json:"hashed_token,omitempty"` - App *AuthorizationApp `json:"app,omitempty"` - Note *string `json:"note,omitempty"` - NoteURL *string `json:"note_url,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - Fingerprint *string `json:"fingerprint,omitempty"` - - // User is only populated by the Check and Reset methods. - User *User `json:"user,omitempty"` -} - -func (a Authorization) String() string { - return Stringify(a) -} - -// AuthorizationApp represents an individual GitHub app (in the context of authorization). -type AuthorizationApp struct { - URL *string `json:"url,omitempty"` - Name *string `json:"name,omitempty"` - ClientID *string `json:"client_id,omitempty"` -} - -func (a AuthorizationApp) String() string { - return Stringify(a) -} - -// Grant represents an OAuth application that has been granted access to an account. -type Grant struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - App *AuthorizationApp `json:"app,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - Scopes []string `json:"scopes,omitempty"` -} - -func (g Grant) String() string { - return Stringify(g) -} - -// AuthorizationRequest represents a request to create an authorization. -type AuthorizationRequest struct { - Scopes []Scope `json:"scopes,omitempty"` - Note *string `json:"note,omitempty"` - NoteURL *string `json:"note_url,omitempty"` - ClientID *string `json:"client_id,omitempty"` - ClientSecret *string `json:"client_secret,omitempty"` - Fingerprint *string `json:"fingerprint,omitempty"` -} - -func (a AuthorizationRequest) String() string { - return Stringify(a) -} - -// AuthorizationUpdateRequest represents a request to update an authorization. -// -// Note that for any one update, you must only provide one of the "scopes" -// fields. That is, you may provide only one of "Scopes", or "AddScopes", or -// "RemoveScopes". -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#update-an-existing-authorization -type AuthorizationUpdateRequest struct { - Scopes []string `json:"scopes,omitempty"` - AddScopes []string `json:"add_scopes,omitempty"` - RemoveScopes []string `json:"remove_scopes,omitempty"` - Note *string `json:"note,omitempty"` - NoteURL *string `json:"note_url,omitempty"` - Fingerprint *string `json:"fingerprint,omitempty"` -} - -func (a AuthorizationUpdateRequest) String() string { - return Stringify(a) -} - -// List the authorizations for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#list-your-authorizations -func (s *AuthorizationsService) List(ctx context.Context, opt *ListOptions) ([]*Authorization, *Response, error) { - u := "authorizations" - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var auths []*Authorization - resp, err := s.client.Do(ctx, req, &auths) - if err != nil { - return nil, resp, err - } - return auths, resp, nil -} - -// Get a single authorization. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#get-a-single-authorization -func (s *AuthorizationsService) Get(ctx context.Context, id int64) (*Authorization, *Response, error) { - u := fmt.Sprintf("authorizations/%d", id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - return a, resp, nil -} - -// Create a new authorization for the specified OAuth application. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#create-a-new-authorization -func (s *AuthorizationsService) Create(ctx context.Context, auth *AuthorizationRequest) (*Authorization, *Response, error) { - u := "authorizations" - - req, err := s.client.NewRequest("POST", u, auth) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - return a, resp, nil -} - -// GetOrCreateForApp creates a new authorization for the specified OAuth -// application, only if an authorization for that application doesn’t already -// exist for the user. -// -// If a new token is created, the HTTP status code will be "201 Created", and -// the returned Authorization.Token field will be populated. If an existing -// token is returned, the status code will be "200 OK" and the -// Authorization.Token field will be empty. -// -// clientID is the OAuth Client ID with which to create the token. -// -// GitHub API docs: -// https://developer.github.com/v3/oauth_authorizations/#get-or-create-an-authorization-for-a-specific-app -// https://developer.github.com/v3/oauth_authorizations/#get-or-create-an-authorization-for-a-specific-app-and-fingerprint -func (s *AuthorizationsService) GetOrCreateForApp(ctx context.Context, clientID string, auth *AuthorizationRequest) (*Authorization, *Response, error) { - var u string - if auth.Fingerprint == nil || *auth.Fingerprint == "" { - u = fmt.Sprintf("authorizations/clients/%v", clientID) - } else { - u = fmt.Sprintf("authorizations/clients/%v/%v", clientID, *auth.Fingerprint) - } - - req, err := s.client.NewRequest("PUT", u, auth) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - - return a, resp, nil -} - -// Edit a single authorization. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#update-an-existing-authorization -func (s *AuthorizationsService) Edit(ctx context.Context, id int64, auth *AuthorizationUpdateRequest) (*Authorization, *Response, error) { - u := fmt.Sprintf("authorizations/%d", id) - - req, err := s.client.NewRequest("PATCH", u, auth) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - - return a, resp, nil -} - -// Delete a single authorization. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#delete-an-authorization -func (s *AuthorizationsService) Delete(ctx context.Context, id int64) (*Response, error) { - u := fmt.Sprintf("authorizations/%d", id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// Check if an OAuth token is valid for a specific app. -// -// Note that this operation requires the use of BasicAuth, but where the -// username is the OAuth application clientID, and the password is its -// clientSecret. Invalid tokens will return a 404 Not Found. -// -// The returned Authorization.User field will be populated. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#check-an-authorization -func (s *AuthorizationsService) Check(ctx context.Context, clientID string, token string) (*Authorization, *Response, error) { - u := fmt.Sprintf("applications/%v/tokens/%v", clientID, token) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - - return a, resp, nil -} - -// Reset is used to reset a valid OAuth token without end user involvement. -// Applications must save the "token" property in the response, because changes -// take effect immediately. -// -// Note that this operation requires the use of BasicAuth, but where the -// username is the OAuth application clientID, and the password is its -// clientSecret. Invalid tokens will return a 404 Not Found. -// -// The returned Authorization.User field will be populated. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#reset-an-authorization -func (s *AuthorizationsService) Reset(ctx context.Context, clientID string, token string) (*Authorization, *Response, error) { - u := fmt.Sprintf("applications/%v/tokens/%v", clientID, token) - - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - - return a, resp, nil -} - -// Revoke an authorization for an application. -// -// Note that this operation requires the use of BasicAuth, but where the -// username is the OAuth application clientID, and the password is its -// clientSecret. Invalid tokens will return a 404 Not Found. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#revoke-an-authorization-for-an-application -func (s *AuthorizationsService) Revoke(ctx context.Context, clientID string, token string) (*Response, error) { - u := fmt.Sprintf("applications/%v/tokens/%v", clientID, token) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ListGrants lists the set of OAuth applications that have been granted -// access to a user's account. This will return one entry for each application -// that has been granted access to the account, regardless of the number of -// tokens an application has generated for the user. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#list-your-grants -func (s *AuthorizationsService) ListGrants(ctx context.Context, opt *ListOptions) ([]*Grant, *Response, error) { - u, err := addOptions("applications/grants", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - grants := []*Grant{} - resp, err := s.client.Do(ctx, req, &grants) - if err != nil { - return nil, resp, err - } - - return grants, resp, nil -} - -// GetGrant gets a single OAuth application grant. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#get-a-single-grant -func (s *AuthorizationsService) GetGrant(ctx context.Context, id int64) (*Grant, *Response, error) { - u := fmt.Sprintf("applications/grants/%d", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - grant := new(Grant) - resp, err := s.client.Do(ctx, req, grant) - if err != nil { - return nil, resp, err - } - - return grant, resp, nil -} - -// DeleteGrant deletes an OAuth application grant. Deleting an application's -// grant will also delete all OAuth tokens associated with the application for -// the user. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#delete-a-grant -func (s *AuthorizationsService) DeleteGrant(ctx context.Context, id int64) (*Response, error) { - u := fmt.Sprintf("applications/grants/%d", id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// CreateImpersonation creates an impersonation OAuth token. -// -// This requires admin permissions. With the returned Authorization.Token -// you can e.g. create or delete a user's public SSH key. NOTE: creating a -// new token automatically revokes an existing one. -// -// GitHub API docs: https://developer.github.com/enterprise/2.5/v3/users/administration/#create-an-impersonation-oauth-token -func (s *AuthorizationsService) CreateImpersonation(ctx context.Context, username string, authReq *AuthorizationRequest) (*Authorization, *Response, error) { - u := fmt.Sprintf("admin/users/%v/authorizations", username) - req, err := s.client.NewRequest("POST", u, authReq) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - return a, resp, nil -} - -// DeleteImpersonation deletes an impersonation OAuth token. -// -// NOTE: there can be only one at a time. -// -// GitHub API docs: https://developer.github.com/enterprise/2.5/v3/users/administration/#delete-an-impersonation-oauth-token -func (s *AuthorizationsService) DeleteImpersonation(ctx context.Context, username string) (*Response, error) { - u := fmt.Sprintf("admin/users/%v/authorizations", username) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/doc.go b/vendor/github.com/google/go-github/github/doc.go deleted file mode 100644 index 4ba03cb3ca4..00000000000 --- a/vendor/github.com/google/go-github/github/doc.go +++ /dev/null @@ -1,191 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -Package github provides a client for using the GitHub API. - -Usage: - - import "github.com/google/go-github/github" - -Construct a new GitHub client, then use the various services on the client to -access different parts of the GitHub API. For example: - - client := github.NewClient(nil) - - // list all organizations for user "willnorris" - orgs, _, err := client.Organizations.List(ctx, "willnorris", nil) - -Some API methods have optional parameters that can be passed. For example: - - client := github.NewClient(nil) - - // list public repositories for org "github" - opt := &github.RepositoryListByOrgOptions{Type: "public"} - repos, _, err := client.Repositories.ListByOrg(ctx, "github", opt) - -The services of a client divide the API into logical chunks and correspond to -the structure of the GitHub API documentation at -https://developer.github.com/v3/. - -Authentication - -The go-github library does not directly handle authentication. Instead, when -creating a new client, pass an http.Client that can handle authentication for -you. The easiest and recommended way to do this is using the golang.org/x/oauth2 -library, but you can always use any other library that provides an http.Client. -If you have an OAuth2 access token (for example, a personal API token), you can -use it with the oauth2 library using: - - import "golang.org/x/oauth2" - - func main() { - ctx := context.Background() - ts := oauth2.StaticTokenSource( - &oauth2.Token{AccessToken: "... your access token ..."}, - ) - tc := oauth2.NewClient(ctx, ts) - - client := github.NewClient(tc) - - // list all repositories for the authenticated user - repos, _, err := client.Repositories.List(ctx, "", nil) - } - -Note that when using an authenticated Client, all calls made by the client will -include the specified OAuth token. Therefore, authenticated clients should -almost never be shared between different users. - -See the oauth2 docs for complete instructions on using that library. - -For API methods that require HTTP Basic Authentication, use the -BasicAuthTransport. - -GitHub Apps authentication can be provided by the -https://github.com/bradleyfalzon/ghinstallation package. - - import "github.com/bradleyfalzon/ghinstallation" - - func main() { - // Wrap the shared transport for use with the integration ID 1 authenticating with installation ID 99. - itr, err := ghinstallation.NewKeyFromFile(http.DefaultTransport, 1, 99, "2016-10-19.private-key.pem") - if err != nil { - // Handle error. - } - - // Use installation transport with client - client := github.NewClient(&http.Client{Transport: itr}) - - // Use client... - } - -Rate Limiting - -GitHub imposes a rate limit on all API clients. Unauthenticated clients are -limited to 60 requests per hour, while authenticated clients can make up to -5,000 requests per hour. The Search API has a custom rate limit. Unauthenticated -clients are limited to 10 requests per minute, while authenticated clients -can make up to 30 requests per minute. To receive the higher rate limit when -making calls that are not issued on behalf of a user, -use UnauthenticatedRateLimitedTransport. - -The returned Response.Rate value contains the rate limit information -from the most recent API call. If a recent enough response isn't -available, you can use RateLimits to fetch the most up-to-date rate -limit data for the client. - -To detect an API rate limit error, you can check if its type is *github.RateLimitError: - - repos, _, err := client.Repositories.List(ctx, "", nil) - if _, ok := err.(*github.RateLimitError); ok { - log.Println("hit rate limit") - } - -Learn more about GitHub rate limiting at -https://developer.github.com/v3/#rate-limiting. - -Accepted Status - -Some endpoints may return a 202 Accepted status code, meaning that the -information required is not yet ready and was scheduled to be gathered on -the GitHub side. Methods known to behave like this are documented specifying -this behavior. - -To detect this condition of error, you can check if its type is -*github.AcceptedError: - - stats, _, err := client.Repositories.ListContributorsStats(ctx, org, repo) - if _, ok := err.(*github.AcceptedError); ok { - log.Println("scheduled on GitHub side") - } - -Conditional Requests - -The GitHub API has good support for conditional requests which will help -prevent you from burning through your rate limit, as well as help speed up your -application. go-github does not handle conditional requests directly, but is -instead designed to work with a caching http.Transport. We recommend using -https://github.com/gregjones/httpcache for that. - -Learn more about GitHub conditional requests at -https://developer.github.com/v3/#conditional-requests. - -Creating and Updating Resources - -All structs for GitHub resources use pointer values for all non-repeated fields. -This allows distinguishing between unset fields and those set to a zero-value. -Helper functions have been provided to easily create these pointers for string, -bool, and int values. For example: - - // create a new private repository named "foo" - repo := &github.Repository{ - Name: github.String("foo"), - Private: github.Bool(true), - } - client.Repositories.Create(ctx, "", repo) - -Users who have worked with protocol buffers should find this pattern familiar. - -Pagination - -All requests for resource collections (repos, pull requests, issues, etc.) -support pagination. Pagination options are described in the -github.ListOptions struct and passed to the list methods directly or as an -embedded type of a more specific list options struct (for example -github.PullRequestListOptions). Pages information is available via the -github.Response struct. - - client := github.NewClient(nil) - - opt := &github.RepositoryListByOrgOptions{ - ListOptions: github.ListOptions{PerPage: 10}, - } - // get all pages of results - var allRepos []*github.Repository - for { - repos, resp, err := client.Repositories.ListByOrg(ctx, "github", opt) - if err != nil { - return err - } - allRepos = append(allRepos, repos...) - if resp.NextPage == 0 { - break - } - opt.Page = resp.NextPage - } - -Google App Engine - -Go on App Engine Classic (which as of this writing uses Go 1.6) can not use -the "context" import and still relies on "golang.org/x/net/context". -As a result, if you wish to continue to use "go-github" on App Engine Classic, -you will need to rewrite all the "context" imports using the following command: - - gofmt -w -r '"context" -> "golang.org/x/net/context"' *.go - -See "with_appengine.go" for more details. - -*/ -package github diff --git a/vendor/github.com/google/go-github/github/event_types.go b/vendor/github.com/google/go-github/github/event_types.go deleted file mode 100644 index 046ba51395c..00000000000 --- a/vendor/github.com/google/go-github/github/event_types.go +++ /dev/null @@ -1,748 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// These event types are shared between the Events API and used as Webhook payloads. - -package github - -// CommitCommentEvent is triggered when a commit comment is created. -// The Webhook event name is "commit_comment". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#commitcommentevent -type CommitCommentEvent struct { - Comment *RepositoryComment `json:"comment,omitempty"` - - // The following fields are only populated by Webhook events. - Action *string `json:"action,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// CreateEvent represents a created repository, branch, or tag. -// The Webhook event name is "create". -// -// Note: webhooks will not receive this event for created repositories. -// Additionally, webhooks will not receive this event for tags if more -// than three tags are pushed at once. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#createevent -type CreateEvent struct { - Ref *string `json:"ref,omitempty"` - // RefType is the object that was created. Possible values are: "repository", "branch", "tag". - RefType *string `json:"ref_type,omitempty"` - MasterBranch *string `json:"master_branch,omitempty"` - Description *string `json:"description,omitempty"` - - // The following fields are only populated by Webhook events. - PusherType *string `json:"pusher_type,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// DeleteEvent represents a deleted branch or tag. -// The Webhook event name is "delete". -// -// Note: webhooks will not receive this event for tags if more than three tags -// are deleted at once. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#deleteevent -type DeleteEvent struct { - Ref *string `json:"ref,omitempty"` - // RefType is the object that was deleted. Possible values are: "branch", "tag". - RefType *string `json:"ref_type,omitempty"` - - // The following fields are only populated by Webhook events. - PusherType *string `json:"pusher_type,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// DeploymentEvent represents a deployment. -// The Webhook event name is "deployment". -// -// Events of this type are not visible in timelines, they are only used to trigger hooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#deploymentevent -type DeploymentEvent struct { - Deployment *Deployment `json:"deployment,omitempty"` - Repo *Repository `json:"repository,omitempty"` - - // The following fields are only populated by Webhook events. - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// DeploymentStatusEvent represents a deployment status. -// The Webhook event name is "deployment_status". -// -// Events of this type are not visible in timelines, they are only used to trigger hooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#deploymentstatusevent -type DeploymentStatusEvent struct { - Deployment *Deployment `json:"deployment,omitempty"` - DeploymentStatus *DeploymentStatus `json:"deployment_status,omitempty"` - Repo *Repository `json:"repository,omitempty"` - - // The following fields are only populated by Webhook events. - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// ForkEvent is triggered when a user forks a repository. -// The Webhook event name is "fork". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#forkevent -type ForkEvent struct { - // Forkee is the created repository. - Forkee *Repository `json:"forkee,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// Page represents a single Wiki page. -type Page struct { - PageName *string `json:"page_name,omitempty"` - Title *string `json:"title,omitempty"` - Summary *string `json:"summary,omitempty"` - Action *string `json:"action,omitempty"` - SHA *string `json:"sha,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` -} - -// GollumEvent is triggered when a Wiki page is created or updated. -// The Webhook event name is "gollum". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#gollumevent -type GollumEvent struct { - Pages []*Page `json:"pages,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// EditChange represents the changes when an issue, pull request, or comment has -// been edited. -type EditChange struct { - Title *struct { - From *string `json:"from,omitempty"` - } `json:"title,omitempty"` - Body *struct { - From *string `json:"from,omitempty"` - } `json:"body,omitempty"` -} - -// ProjectChange represents the changes when a project has been edited. -type ProjectChange struct { - Name *struct { - From *string `json:"from,omitempty"` - } `json:"name,omitempty"` - Body *struct { - From *string `json:"from,omitempty"` - } `json:"body,omitempty"` -} - -// ProjectCardChange represents the changes when a project card has been edited. -type ProjectCardChange struct { - Note *struct { - From *string `json:"from,omitempty"` - } `json:"note,omitempty"` -} - -// ProjectColumnChange represents the changes when a project column has been edited. -type ProjectColumnChange struct { - Name *struct { - From *string `json:"from,omitempty"` - } `json:"name,omitempty"` -} - -// TeamChange represents the changes when a team has been edited. -type TeamChange struct { - Description *struct { - From *string `json:"from,omitempty"` - } `json:"description,omitempty"` - Name *struct { - From *string `json:"from,omitempty"` - } `json:"name,omitempty"` - Privacy *struct { - From *string `json:"from,omitempty"` - } `json:"privacy,omitempty"` - Repository *struct { - Permissions *struct { - From *struct { - Admin *bool `json:"admin,omitempty"` - Pull *bool `json:"pull,omitempty"` - Push *bool `json:"push,omitempty"` - } `json:"from,omitempty"` - } `json:"permissions,omitempty"` - } `json:"repository,omitempty"` -} - -// InstallationEvent is triggered when a GitHub App has been installed or uninstalled. -// The Webhook event name is "installation". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#installationevent -type InstallationEvent struct { - // The action that was performed. Can be either "created" or "deleted". - Action *string `json:"action,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// InstallationRepositoriesEvent is triggered when a repository is added or -// removed from an installation. The Webhook event name is "installation_repositories". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#installationrepositoriesevent -type InstallationRepositoriesEvent struct { - // The action that was performed. Can be either "added" or "removed". - Action *string `json:"action,omitempty"` - RepositoriesAdded []*Repository `json:"repositories_added,omitempty"` - RepositoriesRemoved []*Repository `json:"repositories_removed,omitempty"` - RepositorySelection *string `json:"repository_selection,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// IssueCommentEvent is triggered when an issue comment is created on an issue -// or pull request. -// The Webhook event name is "issue_comment". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#issuecommentevent -type IssueCommentEvent struct { - // Action is the action that was performed on the comment. - // Possible values are: "created", "edited", "deleted". - Action *string `json:"action,omitempty"` - Issue *Issue `json:"issue,omitempty"` - Comment *IssueComment `json:"comment,omitempty"` - - // The following fields are only populated by Webhook events. - Changes *EditChange `json:"changes,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// IssuesEvent is triggered when an issue is assigned, unassigned, labeled, -// unlabeled, opened, closed, or reopened. -// The Webhook event name is "issues". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#issuesevent -type IssuesEvent struct { - // Action is the action that was performed. Possible values are: "assigned", - // "unassigned", "labeled", "unlabeled", "opened", "closed", "reopened", "edited". - Action *string `json:"action,omitempty"` - Issue *Issue `json:"issue,omitempty"` - Assignee *User `json:"assignee,omitempty"` - Label *Label `json:"label,omitempty"` - - // The following fields are only populated by Webhook events. - Changes *EditChange `json:"changes,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// LabelEvent is triggered when a repository's label is created, edited, or deleted. -// The Webhook event name is "label" -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#labelevent -type LabelEvent struct { - // Action is the action that was performed. Possible values are: - // "created", "edited", "deleted" - Action *string `json:"action,omitempty"` - Label *Label `json:"label,omitempty"` - - // The following fields are only populated by Webhook events. - Changes *EditChange `json:"changes,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Org *Organization `json:"organization,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// MarketplacePurchaseEvent is triggered when a user purchases, cancels, or changes -// their GitHub Marketplace plan. -// Webhook event name "marketplace_purchase". -// -// Github API docs: https://developer.github.com/v3/activity/events/types/#marketplacepurchaseevent -type MarketplacePurchaseEvent struct { - // Action is the action that was performed. Possible values are: - // "purchased", "cancelled", "changed". - Action *string `json:"action,omitempty"` - - // The following fields are only populated by Webhook events. - EffectiveDate *Timestamp `json:"effective_date,omitempty"` - MarketplacePurchase *MarketplacePurchase `json:"marketplace_purchase,omitempty"` - PreviousMarketplacePurchase *MarketplacePurchase `json:"previous_marketplace_purchase,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// MemberEvent is triggered when a user is added as a collaborator to a repository. -// The Webhook event name is "member". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#memberevent -type MemberEvent struct { - // Action is the action that was performed. Possible value is: "added". - Action *string `json:"action,omitempty"` - Member *User `json:"member,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// MembershipEvent is triggered when a user is added or removed from a team. -// The Webhook event name is "membership". -// -// Events of this type are not visible in timelines, they are only used to -// trigger organization webhooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#membershipevent -type MembershipEvent struct { - // Action is the action that was performed. Possible values are: "added", "removed". - Action *string `json:"action,omitempty"` - // Scope is the scope of the membership. Possible value is: "team". - Scope *string `json:"scope,omitempty"` - Member *User `json:"member,omitempty"` - Team *Team `json:"team,omitempty"` - - // The following fields are only populated by Webhook events. - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// MilestoneEvent is triggered when a milestone is created, closed, opened, edited, or deleted. -// The Webhook event name is "milestone". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#milestoneevent -type MilestoneEvent struct { - // Action is the action that was performed. Possible values are: - // "created", "closed", "opened", "edited", "deleted" - Action *string `json:"action,omitempty"` - Milestone *Milestone `json:"milestone,omitempty"` - - // The following fields are only populated by Webhook events. - Changes *EditChange `json:"changes,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Org *Organization `json:"organization,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// OrganizationEvent is triggered when a user is added, removed, or invited to an organization. -// Events of this type are not visible in timelines. These events are only used to trigger organization hooks. -// Webhook event name is "organization". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#organizationevent -type OrganizationEvent struct { - // Action is the action that was performed. - // Can be one of "member_added", "member_removed", or "member_invited". - Action *string `json:"action,omitempty"` - - // Invitaion is the invitation for the user or email if the action is "member_invited". - Invitation *Invitation `json:"invitation,omitempty"` - - // Membership is the membership between the user and the organization. - // Not present when the action is "member_invited". - Membership *Membership `json:"membership,omitempty"` - - Organization *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// OrgBlockEvent is triggered when an organization blocks or unblocks a user. -// The Webhook event name is "org_block". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#orgblockevent -type OrgBlockEvent struct { - // Action is the action that was performed. - // Can be "blocked" or "unblocked". - Action *string `json:"action,omitempty"` - BlockedUser *User `json:"blocked_user,omitempty"` - Organization *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - - // The following fields are only populated by Webhook events. - Installation *Installation `json:"installation,omitempty"` -} - -// PageBuildEvent represents an attempted build of a GitHub Pages site, whether -// successful or not. -// The Webhook event name is "page_build". -// -// This event is triggered on push to a GitHub Pages enabled branch (gh-pages -// for project pages, master for user and organization pages). -// -// Events of this type are not visible in timelines, they are only used to trigger hooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#pagebuildevent -type PageBuildEvent struct { - Build *PagesBuild `json:"build,omitempty"` - - // The following fields are only populated by Webhook events. - ID *int64 `json:"id,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// PingEvent is triggered when a Webhook is added to GitHub. -// -// GitHub API docs: https://developer.github.com/webhooks/#ping-event -type PingEvent struct { - // Random string of GitHub zen. - Zen *string `json:"zen,omitempty"` - // The ID of the webhook that triggered the ping. - HookID *int64 `json:"hook_id,omitempty"` - // The webhook configuration. - Hook *Hook `json:"hook,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// ProjectEvent is triggered when project is created, modified or deleted. -// The webhook event name is "project". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#projectevent -type ProjectEvent struct { - Action *string `json:"action,omitempty"` - Changes *ProjectChange `json:"changes,omitempty"` - Project *Project `json:"project,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// ProjectCardEvent is triggered when a project card is created, updated, moved, converted to an issue, or deleted. -// The webhook event name is "project_card". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#projectcardevent -type ProjectCardEvent struct { - Action *string `json:"action,omitempty"` - Changes *ProjectCardChange `json:"changes,omitempty"` - AfterID *int64 `json:"after_id,omitempty"` - ProjectCard *ProjectCard `json:"project_card,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// ProjectColumnEvent is triggered when a project column is created, updated, moved, or deleted. -// The webhook event name is "project_column". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#projectcolumnevent -type ProjectColumnEvent struct { - Action *string `json:"action,omitempty"` - Changes *ProjectColumnChange `json:"changes,omitempty"` - AfterID *int64 `json:"after_id,omitempty"` - ProjectColumn *ProjectColumn `json:"project_column,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// PublicEvent is triggered when a private repository is open sourced. -// According to GitHub: "Without a doubt: the best GitHub event." -// The Webhook event name is "public". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#publicevent -type PublicEvent struct { - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// PullRequestEvent is triggered when a pull request is assigned, unassigned, -// labeled, unlabeled, opened, closed, reopened, or synchronized. -// The Webhook event name is "pull_request". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#pullrequestevent -type PullRequestEvent struct { - // Action is the action that was performed. Possible values are: - // "assigned", "unassigned", "review_requested", "review_request_removed", "labeled", "unlabeled", - // "opened", "closed", "reopened", "synchronize", "edited". - // If the action is "closed" and the merged key is false, - // the pull request was closed with unmerged commits. If the action is "closed" - // and the merged key is true, the pull request was merged. - Action *string `json:"action,omitempty"` - Number *int `json:"number,omitempty"` - PullRequest *PullRequest `json:"pull_request,omitempty"` - - // The following fields are only populated by Webhook events. - Changes *EditChange `json:"changes,omitempty"` - RequestedReviewers []*User `json:"requested_reviewers,omitempty"` // Populated in "review_requested", "review_request_removed" event deliveries. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// PullRequestReviewEvent is triggered when a review is submitted on a pull -// request. -// The Webhook event name is "pull_request_review". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#pullrequestreviewevent -type PullRequestReviewEvent struct { - // Action is always "submitted". - Action *string `json:"action,omitempty"` - Review *PullRequestReview `json:"review,omitempty"` - PullRequest *PullRequest `json:"pull_request,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` - - // The following field is only present when the webhook is triggered on - // a repository belonging to an organization. - Organization *Organization `json:"organization,omitempty"` -} - -// PullRequestReviewCommentEvent is triggered when a comment is created on a -// portion of the unified diff of a pull request. -// The Webhook event name is "pull_request_review_comment". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#pullrequestreviewcommentevent -type PullRequestReviewCommentEvent struct { - // Action is the action that was performed on the comment. - // Possible values are: "created", "edited", "deleted". - Action *string `json:"action,omitempty"` - PullRequest *PullRequest `json:"pull_request,omitempty"` - Comment *PullRequestComment `json:"comment,omitempty"` - - // The following fields are only populated by Webhook events. - Changes *EditChange `json:"changes,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// PushEvent represents a git push to a GitHub repository. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#pushevent -type PushEvent struct { - PushID *int64 `json:"push_id,omitempty"` - Head *string `json:"head,omitempty"` - Ref *string `json:"ref,omitempty"` - Size *int `json:"size,omitempty"` - Commits []PushEventCommit `json:"commits,omitempty"` - Before *string `json:"before,omitempty"` - DistinctSize *int `json:"distinct_size,omitempty"` - - // The following fields are only populated by Webhook events. - After *string `json:"after,omitempty"` - Created *bool `json:"created,omitempty"` - Deleted *bool `json:"deleted,omitempty"` - Forced *bool `json:"forced,omitempty"` - BaseRef *string `json:"base_ref,omitempty"` - Compare *string `json:"compare,omitempty"` - Repo *PushEventRepository `json:"repository,omitempty"` - HeadCommit *PushEventCommit `json:"head_commit,omitempty"` - Pusher *User `json:"pusher,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -func (p PushEvent) String() string { - return Stringify(p) -} - -// PushEventCommit represents a git commit in a GitHub PushEvent. -type PushEventCommit struct { - Message *string `json:"message,omitempty"` - Author *CommitAuthor `json:"author,omitempty"` - URL *string `json:"url,omitempty"` - Distinct *bool `json:"distinct,omitempty"` - - // The following fields are only populated by Events API. - SHA *string `json:"sha,omitempty"` - - // The following fields are only populated by Webhook events. - ID *string `json:"id,omitempty"` - TreeID *string `json:"tree_id,omitempty"` - Timestamp *Timestamp `json:"timestamp,omitempty"` - Committer *CommitAuthor `json:"committer,omitempty"` - Added []string `json:"added,omitempty"` - Removed []string `json:"removed,omitempty"` - Modified []string `json:"modified,omitempty"` -} - -func (p PushEventCommit) String() string { - return Stringify(p) -} - -// PushEventRepository represents the repo object in a PushEvent payload. -type PushEventRepository struct { - ID *int64 `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - FullName *string `json:"full_name,omitempty"` - Owner *PushEventRepoOwner `json:"owner,omitempty"` - Private *bool `json:"private,omitempty"` - Description *string `json:"description,omitempty"` - Fork *bool `json:"fork,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - PushedAt *Timestamp `json:"pushed_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - Homepage *string `json:"homepage,omitempty"` - Size *int `json:"size,omitempty"` - StargazersCount *int `json:"stargazers_count,omitempty"` - WatchersCount *int `json:"watchers_count,omitempty"` - Language *string `json:"language,omitempty"` - HasIssues *bool `json:"has_issues,omitempty"` - HasDownloads *bool `json:"has_downloads,omitempty"` - HasWiki *bool `json:"has_wiki,omitempty"` - HasPages *bool `json:"has_pages,omitempty"` - ForksCount *int `json:"forks_count,omitempty"` - OpenIssuesCount *int `json:"open_issues_count,omitempty"` - DefaultBranch *string `json:"default_branch,omitempty"` - MasterBranch *string `json:"master_branch,omitempty"` - Organization *string `json:"organization,omitempty"` - URL *string `json:"url,omitempty"` - ArchiveURL *string `json:"archive_url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - StatusesURL *string `json:"statuses_url,omitempty"` - GitURL *string `json:"git_url,omitempty"` - SSHURL *string `json:"ssh_url,omitempty"` - CloneURL *string `json:"clone_url,omitempty"` - SVNURL *string `json:"svn_url,omitempty"` -} - -// PushEventRepoOwner is a basic representation of user/org in a PushEvent payload. -type PushEventRepoOwner struct { - Name *string `json:"name,omitempty"` - Email *string `json:"email,omitempty"` -} - -// ReleaseEvent is triggered when a release is published. -// The Webhook event name is "release". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#releaseevent -type ReleaseEvent struct { - // Action is the action that was performed. Possible value is: "published". - Action *string `json:"action,omitempty"` - Release *RepositoryRelease `json:"release,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// RepositoryEvent is triggered when a repository is created. -// The Webhook event name is "repository". -// -// Events of this type are not visible in timelines, they are only used to -// trigger organization webhooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#repositoryevent -type RepositoryEvent struct { - // Action is the action that was performed. Possible values are: "created", "deleted", - // "publicized", "privatized". - Action *string `json:"action,omitempty"` - Repo *Repository `json:"repository,omitempty"` - - // The following fields are only populated by Webhook events. - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// StatusEvent is triggered when the status of a Git commit changes. -// The Webhook event name is "status". -// -// Events of this type are not visible in timelines, they are only used to -// trigger hooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#statusevent -type StatusEvent struct { - SHA *string `json:"sha,omitempty"` - // State is the new state. Possible values are: "pending", "success", "failure", "error". - State *string `json:"state,omitempty"` - Description *string `json:"description,omitempty"` - TargetURL *string `json:"target_url,omitempty"` - Branches []*Branch `json:"branches,omitempty"` - - // The following fields are only populated by Webhook events. - ID *int64 `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Context *string `json:"context,omitempty"` - Commit *RepositoryCommit `json:"commit,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// TeamEvent is triggered when an organization's team is created, modified or deleted. -// The Webhook event name is "team". -// -// Events of this type are not visible in timelines. These events are only used -// to trigger hooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#teamevent -type TeamEvent struct { - Action *string `json:"action,omitempty"` - Team *Team `json:"team,omitempty"` - Changes *TeamChange `json:"changes,omitempty"` - Repo *Repository `json:"repository,omitempty"` - - // The following fields are only populated by Webhook events. - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// TeamAddEvent is triggered when a repository is added to a team. -// The Webhook event name is "team_add". -// -// Events of this type are not visible in timelines. These events are only used -// to trigger hooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#teamaddevent -type TeamAddEvent struct { - Team *Team `json:"team,omitempty"` - Repo *Repository `json:"repository,omitempty"` - - // The following fields are only populated by Webhook events. - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// WatchEvent is related to starring a repository, not watching. See this API -// blog post for an explanation: https://developer.github.com/changes/2012-09-05-watcher-api/ -// -// The event’s actor is the user who starred a repository, and the event’s -// repository is the repository that was starred. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#watchevent -type WatchEvent struct { - // Action is the action that was performed. Possible value is: "started". - Action *string `json:"action,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} diff --git a/vendor/github.com/google/go-github/github/gen-accessors.go b/vendor/github.com/google/go-github/github/gen-accessors.go deleted file mode 100644 index fe92206fcf8..00000000000 --- a/vendor/github.com/google/go-github/github/gen-accessors.go +++ /dev/null @@ -1,332 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// gen-accessors generates accessor methods for structs with pointer fields. -// -// It is meant to be used by the go-github authors in conjunction with the -// go generate tool before sending a commit to GitHub. -package main - -import ( - "bytes" - "flag" - "fmt" - "go/ast" - "go/format" - "go/parser" - "go/token" - "io/ioutil" - "log" - "os" - "sort" - "strings" - "text/template" -) - -const ( - fileSuffix = "-accessors.go" -) - -var ( - verbose = flag.Bool("v", false, "Print verbose log messages") - - sourceTmpl = template.Must(template.New("source").Parse(source)) - - // blacklistStructMethod lists "struct.method" combos to skip. - blacklistStructMethod = map[string]bool{ - "RepositoryContent.GetContent": true, - "Client.GetBaseURL": true, - "Client.GetUploadURL": true, - "ErrorResponse.GetResponse": true, - "RateLimitError.GetResponse": true, - "AbuseRateLimitError.GetResponse": true, - } - // blacklistStruct lists structs to skip. - blacklistStruct = map[string]bool{ - "Client": true, - } -) - -func logf(fmt string, args ...interface{}) { - if *verbose { - log.Printf(fmt, args...) - } -} - -func main() { - flag.Parse() - fset := token.NewFileSet() - - pkgs, err := parser.ParseDir(fset, ".", sourceFilter, 0) - if err != nil { - log.Fatal(err) - return - } - - for pkgName, pkg := range pkgs { - t := &templateData{ - filename: pkgName + fileSuffix, - Year: 2017, - Package: pkgName, - Imports: map[string]string{}, - } - for filename, f := range pkg.Files { - logf("Processing %v...", filename) - if err := t.processAST(f); err != nil { - log.Fatal(err) - } - } - if err := t.dump(); err != nil { - log.Fatal(err) - } - } - logf("Done.") -} - -func (t *templateData) processAST(f *ast.File) error { - for _, decl := range f.Decls { - gd, ok := decl.(*ast.GenDecl) - if !ok { - continue - } - for _, spec := range gd.Specs { - ts, ok := spec.(*ast.TypeSpec) - if !ok { - continue - } - // Skip unexported identifiers. - if !ts.Name.IsExported() { - logf("Struct %v is unexported; skipping.", ts.Name) - continue - } - // Check if the struct is blacklisted. - if blacklistStruct[ts.Name.Name] { - logf("Struct %v is blacklisted; skipping.", ts.Name) - continue - } - st, ok := ts.Type.(*ast.StructType) - if !ok { - continue - } - for _, field := range st.Fields.List { - se, ok := field.Type.(*ast.StarExpr) - if len(field.Names) == 0 || !ok { - continue - } - - fieldName := field.Names[0] - // Skip unexported identifiers. - if !fieldName.IsExported() { - logf("Field %v is unexported; skipping.", fieldName) - continue - } - // Check if "struct.method" is blacklisted. - if key := fmt.Sprintf("%v.Get%v", ts.Name, fieldName); blacklistStructMethod[key] { - logf("Method %v is blacklisted; skipping.", key) - continue - } - - switch x := se.X.(type) { - case *ast.ArrayType: - t.addArrayType(x, ts.Name.String(), fieldName.String()) - case *ast.Ident: - t.addIdent(x, ts.Name.String(), fieldName.String()) - case *ast.MapType: - t.addMapType(x, ts.Name.String(), fieldName.String()) - case *ast.SelectorExpr: - t.addSelectorExpr(x, ts.Name.String(), fieldName.String()) - default: - logf("processAST: type %q, field %q, unknown %T: %+v", ts.Name, fieldName, x, x) - } - } - } - } - return nil -} - -func sourceFilter(fi os.FileInfo) bool { - return !strings.HasSuffix(fi.Name(), "_test.go") && !strings.HasSuffix(fi.Name(), fileSuffix) -} - -func (t *templateData) dump() error { - if len(t.Getters) == 0 { - logf("No getters for %v; skipping.", t.filename) - return nil - } - - // Sort getters by ReceiverType.FieldName. - sort.Sort(byName(t.Getters)) - - var buf bytes.Buffer - if err := sourceTmpl.Execute(&buf, t); err != nil { - return err - } - clean, err := format.Source(buf.Bytes()) - if err != nil { - return err - } - - logf("Writing %v...", t.filename) - return ioutil.WriteFile(t.filename, clean, 0644) -} - -func newGetter(receiverType, fieldName, fieldType, zeroValue string, namedStruct bool) *getter { - return &getter{ - sortVal: strings.ToLower(receiverType) + "." + strings.ToLower(fieldName), - ReceiverVar: strings.ToLower(receiverType[:1]), - ReceiverType: receiverType, - FieldName: fieldName, - FieldType: fieldType, - ZeroValue: zeroValue, - NamedStruct: namedStruct, - } -} - -func (t *templateData) addArrayType(x *ast.ArrayType, receiverType, fieldName string) { - var eltType string - switch elt := x.Elt.(type) { - case *ast.Ident: - eltType = elt.String() - default: - logf("addArrayType: type %q, field %q: unknown elt type: %T %+v; skipping.", receiverType, fieldName, elt, elt) - return - } - - t.Getters = append(t.Getters, newGetter(receiverType, fieldName, "[]"+eltType, "nil", false)) -} - -func (t *templateData) addIdent(x *ast.Ident, receiverType, fieldName string) { - var zeroValue string - var namedStruct = false - switch x.String() { - case "int", "int64": - zeroValue = "0" - case "string": - zeroValue = `""` - case "bool": - zeroValue = "false" - case "Timestamp": - zeroValue = "Timestamp{}" - default: - zeroValue = "nil" - namedStruct = true - } - - t.Getters = append(t.Getters, newGetter(receiverType, fieldName, x.String(), zeroValue, namedStruct)) -} - -func (t *templateData) addMapType(x *ast.MapType, receiverType, fieldName string) { - var keyType string - switch key := x.Key.(type) { - case *ast.Ident: - keyType = key.String() - default: - logf("addMapType: type %q, field %q: unknown key type: %T %+v; skipping.", receiverType, fieldName, key, key) - return - } - - var valueType string - switch value := x.Value.(type) { - case *ast.Ident: - valueType = value.String() - default: - logf("addMapType: type %q, field %q: unknown value type: %T %+v; skipping.", receiverType, fieldName, value, value) - return - } - - fieldType := fmt.Sprintf("map[%v]%v", keyType, valueType) - zeroValue := fmt.Sprintf("map[%v]%v{}", keyType, valueType) - t.Getters = append(t.Getters, newGetter(receiverType, fieldName, fieldType, zeroValue, false)) -} - -func (t *templateData) addSelectorExpr(x *ast.SelectorExpr, receiverType, fieldName string) { - if strings.ToLower(fieldName[:1]) == fieldName[:1] { // Non-exported field. - return - } - - var xX string - if xx, ok := x.X.(*ast.Ident); ok { - xX = xx.String() - } - - switch xX { - case "time", "json": - if xX == "json" { - t.Imports["encoding/json"] = "encoding/json" - } else { - t.Imports[xX] = xX - } - fieldType := fmt.Sprintf("%v.%v", xX, x.Sel.Name) - zeroValue := fmt.Sprintf("%v.%v{}", xX, x.Sel.Name) - if xX == "time" && x.Sel.Name == "Duration" { - zeroValue = "0" - } - t.Getters = append(t.Getters, newGetter(receiverType, fieldName, fieldType, zeroValue, false)) - default: - logf("addSelectorExpr: xX %q, type %q, field %q: unknown x=%+v; skipping.", xX, receiverType, fieldName, x) - } -} - -type templateData struct { - filename string - Year int - Package string - Imports map[string]string - Getters []*getter -} - -type getter struct { - sortVal string // Lower-case version of "ReceiverType.FieldName". - ReceiverVar string // The one-letter variable name to match the ReceiverType. - ReceiverType string - FieldName string - FieldType string - ZeroValue string - NamedStruct bool // Getter for named struct. -} - -type byName []*getter - -func (b byName) Len() int { return len(b) } -func (b byName) Less(i, j int) bool { return b[i].sortVal < b[j].sortVal } -func (b byName) Swap(i, j int) { b[i], b[j] = b[j], b[i] } - -const source = `// Copyright {{.Year}} The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Code generated by gen-accessors; DO NOT EDIT. - -package {{.Package}} -{{with .Imports}} -import ( - {{- range . -}} - "{{.}}" - {{end -}} -) -{{end}} -{{range .Getters}} -{{if .NamedStruct}} -// Get{{.FieldName}} returns the {{.FieldName}} field. -func ({{.ReceiverVar}} *{{.ReceiverType}}) Get{{.FieldName}}() *{{.FieldType}} { - if {{.ReceiverVar}} == nil { - return {{.ZeroValue}} - } - return {{.ReceiverVar}}.{{.FieldName}} -} -{{else}} -// Get{{.FieldName}} returns the {{.FieldName}} field if it's non-nil, zero value otherwise. -func ({{.ReceiverVar}} *{{.ReceiverType}}) Get{{.FieldName}}() {{.FieldType}} { - if {{.ReceiverVar}} == nil || {{.ReceiverVar}}.{{.FieldName}} == nil { - return {{.ZeroValue}} - } - return *{{.ReceiverVar}}.{{.FieldName}} -} -{{end}} -{{end}} -` diff --git a/vendor/github.com/google/go-github/github/gists.go b/vendor/github.com/google/go-github/github/gists.go deleted file mode 100644 index 9108b642449..00000000000 --- a/vendor/github.com/google/go-github/github/gists.go +++ /dev/null @@ -1,388 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// GistsService handles communication with the Gist related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/gists/ -type GistsService service - -// Gist represents a GitHub's gist. -type Gist struct { - ID *string `json:"id,omitempty"` - Description *string `json:"description,omitempty"` - Public *bool `json:"public,omitempty"` - Owner *User `json:"owner,omitempty"` - Files map[GistFilename]GistFile `json:"files,omitempty"` - Comments *int `json:"comments,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - GitPullURL *string `json:"git_pull_url,omitempty"` - GitPushURL *string `json:"git_push_url,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -func (g Gist) String() string { - return Stringify(g) -} - -// GistFilename represents filename on a gist. -type GistFilename string - -// GistFile represents a file on a gist. -type GistFile struct { - Size *int `json:"size,omitempty"` - Filename *string `json:"filename,omitempty"` - Language *string `json:"language,omitempty"` - Type *string `json:"type,omitempty"` - RawURL *string `json:"raw_url,omitempty"` - Content *string `json:"content,omitempty"` -} - -func (g GistFile) String() string { - return Stringify(g) -} - -// GistCommit represents a commit on a gist. -type GistCommit struct { - URL *string `json:"url,omitempty"` - Version *string `json:"version,omitempty"` - User *User `json:"user,omitempty"` - ChangeStatus *CommitStats `json:"change_status,omitempty"` - CommittedAt *Timestamp `json:"committed_at,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -func (gc GistCommit) String() string { - return Stringify(gc) -} - -// GistFork represents a fork of a gist. -type GistFork struct { - URL *string `json:"url,omitempty"` - User *User `json:"user,omitempty"` - ID *string `json:"id,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -func (gf GistFork) String() string { - return Stringify(gf) -} - -// GistListOptions specifies the optional parameters to the -// GistsService.List, GistsService.ListAll, and GistsService.ListStarred methods. -type GistListOptions struct { - // Since filters Gists by time. - Since time.Time `url:"since,omitempty"` - - ListOptions -} - -// List gists for a user. Passing the empty string will list -// all public gists if called anonymously. However, if the call -// is authenticated, it will returns all gists for the authenticated -// user. -// -// GitHub API docs: https://developer.github.com/v3/gists/#list-gists -func (s *GistsService) List(ctx context.Context, user string, opt *GistListOptions) ([]*Gist, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/gists", user) - } else { - u = "gists" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - var gists []*Gist - resp, err := s.client.Do(ctx, req, &gists) - if err != nil { - return nil, resp, err - } - - return gists, resp, nil -} - -// ListAll lists all public gists. -// -// GitHub API docs: https://developer.github.com/v3/gists/#list-gists -func (s *GistsService) ListAll(ctx context.Context, opt *GistListOptions) ([]*Gist, *Response, error) { - u, err := addOptions("gists/public", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - var gists []*Gist - resp, err := s.client.Do(ctx, req, &gists) - if err != nil { - return nil, resp, err - } - - return gists, resp, nil -} - -// ListStarred lists starred gists of authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/gists/#list-gists -func (s *GistsService) ListStarred(ctx context.Context, opt *GistListOptions) ([]*Gist, *Response, error) { - u, err := addOptions("gists/starred", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - var gists []*Gist - resp, err := s.client.Do(ctx, req, &gists) - if err != nil { - return nil, resp, err - } - - return gists, resp, nil -} - -// Get a single gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#get-a-single-gist -func (s *GistsService) Get(ctx context.Context, id string) (*Gist, *Response, error) { - u := fmt.Sprintf("gists/%v", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - gist := new(Gist) - resp, err := s.client.Do(ctx, req, gist) - if err != nil { - return nil, resp, err - } - - return gist, resp, nil -} - -// GetRevision gets a specific revision of a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#get-a-specific-revision-of-a-gist -func (s *GistsService) GetRevision(ctx context.Context, id, sha string) (*Gist, *Response, error) { - u := fmt.Sprintf("gists/%v/%v", id, sha) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - gist := new(Gist) - resp, err := s.client.Do(ctx, req, gist) - if err != nil { - return nil, resp, err - } - - return gist, resp, nil -} - -// Create a gist for authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/gists/#create-a-gist -func (s *GistsService) Create(ctx context.Context, gist *Gist) (*Gist, *Response, error) { - u := "gists" - req, err := s.client.NewRequest("POST", u, gist) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - g := new(Gist) - resp, err := s.client.Do(ctx, req, g) - if err != nil { - return nil, resp, err - } - - return g, resp, nil -} - -// Edit a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#edit-a-gist -func (s *GistsService) Edit(ctx context.Context, id string, gist *Gist) (*Gist, *Response, error) { - u := fmt.Sprintf("gists/%v", id) - req, err := s.client.NewRequest("PATCH", u, gist) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - g := new(Gist) - resp, err := s.client.Do(ctx, req, g) - if err != nil { - return nil, resp, err - } - - return g, resp, nil -} - -// ListCommits lists commits of a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#list-gist-commits -func (s *GistsService) ListCommits(ctx context.Context, id string, opt *ListOptions) ([]*GistCommit, *Response, error) { - u := fmt.Sprintf("gists/%v/commits", id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - var gistCommits []*GistCommit - resp, err := s.client.Do(ctx, req, &gistCommits) - if err != nil { - return nil, resp, err - } - - return gistCommits, resp, nil -} - -// Delete a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#delete-a-gist -func (s *GistsService) Delete(ctx context.Context, id string) (*Response, error) { - u := fmt.Sprintf("gists/%v", id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// Star a gist on behalf of authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/gists/#star-a-gist -func (s *GistsService) Star(ctx context.Context, id string) (*Response, error) { - u := fmt.Sprintf("gists/%v/star", id) - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// Unstar a gist on a behalf of authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/gists/#unstar-a-gist -func (s *GistsService) Unstar(ctx context.Context, id string) (*Response, error) { - u := fmt.Sprintf("gists/%v/star", id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// IsStarred checks if a gist is starred by authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/gists/#check-if-a-gist-is-starred -func (s *GistsService) IsStarred(ctx context.Context, id string) (bool, *Response, error) { - u := fmt.Sprintf("gists/%v/star", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - resp, err := s.client.Do(ctx, req, nil) - starred, err := parseBoolResponse(err) - return starred, resp, err -} - -// Fork a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#fork-a-gist -func (s *GistsService) Fork(ctx context.Context, id string) (*Gist, *Response, error) { - u := fmt.Sprintf("gists/%v/forks", id) - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - g := new(Gist) - resp, err := s.client.Do(ctx, req, g) - if err != nil { - return nil, resp, err - } - - return g, resp, nil -} - -// ListForks lists forks of a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#list-gist-forks -func (s *GistsService) ListForks(ctx context.Context, id string) ([]*GistFork, *Response, error) { - u := fmt.Sprintf("gists/%v/forks", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - var gistForks []*GistFork - resp, err := s.client.Do(ctx, req, &gistForks) - if err != nil { - return nil, resp, err - } - - return gistForks, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/gists_comments.go b/vendor/github.com/google/go-github/github/gists_comments.go deleted file mode 100644 index d5322e3d852..00000000000 --- a/vendor/github.com/google/go-github/github/gists_comments.go +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// GistComment represents a Gist comment. -type GistComment struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - Body *string `json:"body,omitempty"` - User *User `json:"user,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` -} - -func (g GistComment) String() string { - return Stringify(g) -} - -// ListComments lists all comments for a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/comments/#list-comments-on-a-gist -func (s *GistsService) ListComments(ctx context.Context, gistID string, opt *ListOptions) ([]*GistComment, *Response, error) { - u := fmt.Sprintf("gists/%v/comments", gistID) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var comments []*GistComment - resp, err := s.client.Do(ctx, req, &comments) - if err != nil { - return nil, resp, err - } - - return comments, resp, nil -} - -// GetComment retrieves a single comment from a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/comments/#get-a-single-comment -func (s *GistsService) GetComment(ctx context.Context, gistID string, commentID int64) (*GistComment, *Response, error) { - u := fmt.Sprintf("gists/%v/comments/%v", gistID, commentID) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - c := new(GistComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// CreateComment creates a comment for a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/comments/#create-a-comment -func (s *GistsService) CreateComment(ctx context.Context, gistID string, comment *GistComment) (*GistComment, *Response, error) { - u := fmt.Sprintf("gists/%v/comments", gistID) - req, err := s.client.NewRequest("POST", u, comment) - if err != nil { - return nil, nil, err - } - - c := new(GistComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// EditComment edits an existing gist comment. -// -// GitHub API docs: https://developer.github.com/v3/gists/comments/#edit-a-comment -func (s *GistsService) EditComment(ctx context.Context, gistID string, commentID int64, comment *GistComment) (*GistComment, *Response, error) { - u := fmt.Sprintf("gists/%v/comments/%v", gistID, commentID) - req, err := s.client.NewRequest("PATCH", u, comment) - if err != nil { - return nil, nil, err - } - - c := new(GistComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// DeleteComment deletes a gist comment. -// -// GitHub API docs: https://developer.github.com/v3/gists/comments/#delete-a-comment -func (s *GistsService) DeleteComment(ctx context.Context, gistID string, commentID int64) (*Response, error) { - u := fmt.Sprintf("gists/%v/comments/%v", gistID, commentID) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/git.go b/vendor/github.com/google/go-github/github/git.go deleted file mode 100644 index 1ce47437bd3..00000000000 --- a/vendor/github.com/google/go-github/github/git.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -// GitService handles communication with the git data related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/git/ -type GitService service diff --git a/vendor/github.com/google/go-github/github/git_blobs.go b/vendor/github.com/google/go-github/github/git_blobs.go deleted file mode 100644 index 9d8fd27bcca..00000000000 --- a/vendor/github.com/google/go-github/github/git_blobs.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// Blob represents a blob object. -type Blob struct { - Content *string `json:"content,omitempty"` - Encoding *string `json:"encoding,omitempty"` - SHA *string `json:"sha,omitempty"` - Size *int `json:"size,omitempty"` - URL *string `json:"url,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -// GetBlob fetchs a blob from a repo given a SHA. -// -// GitHub API docs: https://developer.github.com/v3/git/blobs/#get-a-blob -func (s *GitService) GetBlob(ctx context.Context, owner string, repo string, sha string) (*Blob, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/blobs/%v", owner, repo, sha) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - blob := new(Blob) - resp, err := s.client.Do(ctx, req, blob) - return blob, resp, err -} - -// CreateBlob creates a blob object. -// -// GitHub API docs: https://developer.github.com/v3/git/blobs/#create-a-blob -func (s *GitService) CreateBlob(ctx context.Context, owner string, repo string, blob *Blob) (*Blob, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/blobs", owner, repo) - req, err := s.client.NewRequest("POST", u, blob) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - t := new(Blob) - resp, err := s.client.Do(ctx, req, t) - return t, resp, err -} diff --git a/vendor/github.com/google/go-github/github/git_commits.go b/vendor/github.com/google/go-github/github/git_commits.go deleted file mode 100644 index 29882569c94..00000000000 --- a/vendor/github.com/google/go-github/github/git_commits.go +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "strings" - "time" -) - -// SignatureVerification represents GPG signature verification. -type SignatureVerification struct { - Verified *bool `json:"verified,omitempty"` - Reason *string `json:"reason,omitempty"` - Signature *string `json:"signature,omitempty"` - Payload *string `json:"payload,omitempty"` -} - -// Commit represents a GitHub commit. -type Commit struct { - SHA *string `json:"sha,omitempty"` - Author *CommitAuthor `json:"author,omitempty"` - Committer *CommitAuthor `json:"committer,omitempty"` - Message *string `json:"message,omitempty"` - Tree *Tree `json:"tree,omitempty"` - Parents []Commit `json:"parents,omitempty"` - Stats *CommitStats `json:"stats,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - URL *string `json:"url,omitempty"` - Verification *SignatureVerification `json:"verification,omitempty"` - NodeID *string `json:"node_id,omitempty"` - - // CommentCount is the number of GitHub comments on the commit. This - // is only populated for requests that fetch GitHub data like - // Pulls.ListCommits, Repositories.ListCommits, etc. - CommentCount *int `json:"comment_count,omitempty"` -} - -func (c Commit) String() string { - return Stringify(c) -} - -// CommitAuthor represents the author or committer of a commit. The commit -// author may not correspond to a GitHub User. -type CommitAuthor struct { - Date *time.Time `json:"date,omitempty"` - Name *string `json:"name,omitempty"` - Email *string `json:"email,omitempty"` - - // The following fields are only populated by Webhook events. - Login *string `json:"username,omitempty"` // Renamed for go-github consistency. -} - -func (c CommitAuthor) String() string { - return Stringify(c) -} - -// GetCommit fetchs the Commit object for a given SHA. -// -// GitHub API docs: https://developer.github.com/v3/git/commits/#get-a-commit -func (s *GitService) GetCommit(ctx context.Context, owner string, repo string, sha string) (*Commit, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/commits/%v", owner, repo, sha) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - acceptHeaders := []string{mediaTypeGitSigningPreview, mediaTypeGraphQLNodeIDPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - c := new(Commit) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// createCommit represents the body of a CreateCommit request. -type createCommit struct { - Author *CommitAuthor `json:"author,omitempty"` - Committer *CommitAuthor `json:"committer,omitempty"` - Message *string `json:"message,omitempty"` - Tree *string `json:"tree,omitempty"` - Parents []string `json:"parents,omitempty"` -} - -// CreateCommit creates a new commit in a repository. -// commit must not be nil. -// -// The commit.Committer is optional and will be filled with the commit.Author -// data if omitted. If the commit.Author is omitted, it will be filled in with -// the authenticated user’s information and the current date. -// -// GitHub API docs: https://developer.github.com/v3/git/commits/#create-a-commit -func (s *GitService) CreateCommit(ctx context.Context, owner string, repo string, commit *Commit) (*Commit, *Response, error) { - if commit == nil { - return nil, nil, fmt.Errorf("commit must be provided") - } - - u := fmt.Sprintf("repos/%v/%v/git/commits", owner, repo) - - parents := make([]string, len(commit.Parents)) - for i, parent := range commit.Parents { - parents[i] = *parent.SHA - } - - body := &createCommit{ - Author: commit.Author, - Committer: commit.Committer, - Message: commit.Message, - Parents: parents, - } - if commit.Tree != nil { - body.Tree = commit.Tree.SHA - } - - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - c := new(Commit) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/git_refs.go b/vendor/github.com/google/go-github/github/git_refs.go deleted file mode 100644 index 0947d866ab6..00000000000 --- a/vendor/github.com/google/go-github/github/git_refs.go +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "strings" -) - -// Reference represents a GitHub reference. -type Reference struct { - Ref *string `json:"ref"` - URL *string `json:"url"` - Object *GitObject `json:"object"` - NodeID *string `json:"node_id,omitempty"` -} - -func (r Reference) String() string { - return Stringify(r) -} - -// GitObject represents a Git object. -type GitObject struct { - Type *string `json:"type"` - SHA *string `json:"sha"` - URL *string `json:"url"` -} - -func (o GitObject) String() string { - return Stringify(o) -} - -// createRefRequest represents the payload for creating a reference. -type createRefRequest struct { - Ref *string `json:"ref"` - SHA *string `json:"sha"` -} - -// updateRefRequest represents the payload for updating a reference. -type updateRefRequest struct { - SHA *string `json:"sha"` - Force *bool `json:"force"` -} - -// GetRef fetches a single Reference object for a given Git ref. -// If there is no exact match, GetRef will return an error. -// -// Note: The GitHub API can return multiple matches. -// If you wish to use this functionality please use the GetRefs() method. -// -// GitHub API docs: https://developer.github.com/v3/git/refs/#get-a-reference -func (s *GitService) GetRef(ctx context.Context, owner string, repo string, ref string) (*Reference, *Response, error) { - ref = strings.TrimPrefix(ref, "refs/") - u := fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, ref) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - r := new(Reference) - resp, err := s.client.Do(ctx, req, r) - if _, ok := err.(*json.UnmarshalTypeError); ok { - // Multiple refs, means there wasn't an exact match. - return nil, resp, errors.New("no exact match found for this ref") - } else if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// GetRefs fetches a slice of Reference objects for a given Git ref. -// If there is an exact match, only that ref is returned. -// If there is no exact match, GitHub returns all refs that start with ref. -// If returned error is nil, there will be at least 1 ref returned. -// For example: -// -// "heads/featureA" -> ["refs/heads/featureA"] // Exact match, single ref is returned. -// "heads/feature" -> ["refs/heads/featureA", "refs/heads/featureB"] // All refs that start with ref. -// "heads/notexist" -> [] // Returns an error. -// -// GitHub API docs: https://developer.github.com/v3/git/refs/#get-a-reference -func (s *GitService) GetRefs(ctx context.Context, owner string, repo string, ref string) ([]*Reference, *Response, error) { - ref = strings.TrimPrefix(ref, "refs/") - u := fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, ref) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - var rawJSON json.RawMessage - resp, err := s.client.Do(ctx, req, &rawJSON) - if err != nil { - return nil, resp, err - } - - // Prioritize the most common case: a single returned ref. - r := new(Reference) - singleUnmarshalError := json.Unmarshal(rawJSON, r) - if singleUnmarshalError == nil { - return []*Reference{r}, resp, nil - } - - // Attempt to unmarshal multiple refs. - var rs []*Reference - multipleUnmarshalError := json.Unmarshal(rawJSON, &rs) - if multipleUnmarshalError == nil { - if len(rs) == 0 { - return nil, resp, fmt.Errorf("unexpected response from GitHub API: an array of refs with length 0") - } - return rs, resp, nil - } - - return nil, resp, fmt.Errorf("unmarshalling failed for both single and multiple refs: %s and %s", singleUnmarshalError, multipleUnmarshalError) -} - -// ReferenceListOptions specifies optional parameters to the -// GitService.ListRefs method. -type ReferenceListOptions struct { - Type string `url:"-"` - - ListOptions -} - -// ListRefs lists all refs in a repository. -// -// GitHub API docs: https://developer.github.com/v3/git/refs/#get-all-references -func (s *GitService) ListRefs(ctx context.Context, owner, repo string, opt *ReferenceListOptions) ([]*Reference, *Response, error) { - var u string - if opt != nil && opt.Type != "" { - u = fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, opt.Type) - } else { - u = fmt.Sprintf("repos/%v/%v/git/refs", owner, repo) - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - var rs []*Reference - resp, err := s.client.Do(ctx, req, &rs) - if err != nil { - return nil, resp, err - } - - return rs, resp, nil -} - -// CreateRef creates a new ref in a repository. -// -// GitHub API docs: https://developer.github.com/v3/git/refs/#create-a-reference -func (s *GitService) CreateRef(ctx context.Context, owner string, repo string, ref *Reference) (*Reference, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/refs", owner, repo) - req, err := s.client.NewRequest("POST", u, &createRefRequest{ - // back-compat with previous behavior that didn't require 'refs/' prefix - Ref: String("refs/" + strings.TrimPrefix(*ref.Ref, "refs/")), - SHA: ref.Object.SHA, - }) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - r := new(Reference) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// UpdateRef updates an existing ref in a repository. -// -// GitHub API docs: https://developer.github.com/v3/git/refs/#update-a-reference -func (s *GitService) UpdateRef(ctx context.Context, owner string, repo string, ref *Reference, force bool) (*Reference, *Response, error) { - refPath := strings.TrimPrefix(*ref.Ref, "refs/") - u := fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, refPath) - req, err := s.client.NewRequest("PATCH", u, &updateRefRequest{ - SHA: ref.Object.SHA, - Force: &force, - }) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - r := new(Reference) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// DeleteRef deletes a ref from a repository. -// -// GitHub API docs: https://developer.github.com/v3/git/refs/#delete-a-reference -func (s *GitService) DeleteRef(ctx context.Context, owner string, repo string, ref string) (*Response, error) { - ref = strings.TrimPrefix(ref, "refs/") - u := fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, ref) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/git_tags.go b/vendor/github.com/google/go-github/github/git_tags.go deleted file mode 100644 index f3822ffaccc..00000000000 --- a/vendor/github.com/google/go-github/github/git_tags.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "strings" -) - -// Tag represents a tag object. -type Tag struct { - Tag *string `json:"tag,omitempty"` - SHA *string `json:"sha,omitempty"` - URL *string `json:"url,omitempty"` - Message *string `json:"message,omitempty"` - Tagger *CommitAuthor `json:"tagger,omitempty"` - Object *GitObject `json:"object,omitempty"` - Verification *SignatureVerification `json:"verification,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -// createTagRequest represents the body of a CreateTag request. This is mostly -// identical to Tag with the exception that the object SHA and Type are -// top-level fields, rather than being nested inside a JSON object. -type createTagRequest struct { - Tag *string `json:"tag,omitempty"` - Message *string `json:"message,omitempty"` - Object *string `json:"object,omitempty"` - Type *string `json:"type,omitempty"` - Tagger *CommitAuthor `json:"tagger,omitempty"` -} - -// GetTag fetchs a tag from a repo given a SHA. -// -// GitHub API docs: https://developer.github.com/v3/git/tags/#get-a-tag -func (s *GitService) GetTag(ctx context.Context, owner string, repo string, sha string) (*Tag, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/tags/%v", owner, repo, sha) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - acceptHeaders := []string{mediaTypeGitSigningPreview, mediaTypeGraphQLNodeIDPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - tag := new(Tag) - resp, err := s.client.Do(ctx, req, tag) - return tag, resp, err -} - -// CreateTag creates a tag object. -// -// GitHub API docs: https://developer.github.com/v3/git/tags/#create-a-tag-object -func (s *GitService) CreateTag(ctx context.Context, owner string, repo string, tag *Tag) (*Tag, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/tags", owner, repo) - - // convert Tag into a createTagRequest - tagRequest := &createTagRequest{ - Tag: tag.Tag, - Message: tag.Message, - Tagger: tag.Tagger, - } - if tag.Object != nil { - tagRequest.Object = tag.Object.SHA - tagRequest.Type = tag.Object.Type - } - - req, err := s.client.NewRequest("POST", u, tagRequest) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - t := new(Tag) - resp, err := s.client.Do(ctx, req, t) - return t, resp, err -} diff --git a/vendor/github.com/google/go-github/github/git_trees.go b/vendor/github.com/google/go-github/github/git_trees.go deleted file mode 100644 index 4d6809a880e..00000000000 --- a/vendor/github.com/google/go-github/github/git_trees.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// Tree represents a GitHub tree. -type Tree struct { - SHA *string `json:"sha,omitempty"` - Entries []TreeEntry `json:"tree,omitempty"` -} - -func (t Tree) String() string { - return Stringify(t) -} - -// TreeEntry represents the contents of a tree structure. TreeEntry can -// represent either a blob, a commit (in the case of a submodule), or another -// tree. -type TreeEntry struct { - SHA *string `json:"sha,omitempty"` - Path *string `json:"path,omitempty"` - Mode *string `json:"mode,omitempty"` - Type *string `json:"type,omitempty"` - Size *int `json:"size,omitempty"` - Content *string `json:"content,omitempty"` - URL *string `json:"url,omitempty"` -} - -func (t TreeEntry) String() string { - return Stringify(t) -} - -// GetTree fetches the Tree object for a given sha hash from a repository. -// -// GitHub API docs: https://developer.github.com/v3/git/trees/#get-a-tree -func (s *GitService) GetTree(ctx context.Context, owner string, repo string, sha string, recursive bool) (*Tree, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/trees/%v", owner, repo, sha) - if recursive { - u += "?recursive=1" - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - t := new(Tree) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} - -// createTree represents the body of a CreateTree request. -type createTree struct { - BaseTree string `json:"base_tree,omitempty"` - Entries []TreeEntry `json:"tree"` -} - -// CreateTree creates a new tree in a repository. If both a tree and a nested -// path modifying that tree are specified, it will overwrite the contents of -// that tree with the new path contents and write a new tree out. -// -// GitHub API docs: https://developer.github.com/v3/git/trees/#create-a-tree -func (s *GitService) CreateTree(ctx context.Context, owner string, repo string, baseTree string, entries []TreeEntry) (*Tree, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/trees", owner, repo) - - body := &createTree{ - BaseTree: baseTree, - Entries: entries, - } - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - t := new(Tree) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/github-accessors.go b/vendor/github.com/google/go-github/github/github-accessors.go deleted file mode 100644 index 30b7673977b..00000000000 --- a/vendor/github.com/google/go-github/github/github-accessors.go +++ /dev/null @@ -1,10429 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Code generated by gen-accessors; DO NOT EDIT. - -package github - -import ( - "encoding/json" - "time" -) - -// GetRetryAfter returns the RetryAfter field if it's non-nil, zero value otherwise. -func (a *AbuseRateLimitError) GetRetryAfter() time.Duration { - if a == nil || a.RetryAfter == nil { - return 0 - } - return *a.RetryAfter -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (a *AdminEnforcement) GetURL() string { - if a == nil || a.URL == nil { - return "" - } - return *a.URL -} - -// GetComments returns the Comments field. -func (a *AdminStats) GetComments() *CommentStats { - if a == nil { - return nil - } - return a.Comments -} - -// GetGists returns the Gists field. -func (a *AdminStats) GetGists() *GistStats { - if a == nil { - return nil - } - return a.Gists -} - -// GetHooks returns the Hooks field. -func (a *AdminStats) GetHooks() *HookStats { - if a == nil { - return nil - } - return a.Hooks -} - -// GetIssues returns the Issues field. -func (a *AdminStats) GetIssues() *IssueStats { - if a == nil { - return nil - } - return a.Issues -} - -// GetMilestones returns the Milestones field. -func (a *AdminStats) GetMilestones() *MilestoneStats { - if a == nil { - return nil - } - return a.Milestones -} - -// GetOrgs returns the Orgs field. -func (a *AdminStats) GetOrgs() *OrgStats { - if a == nil { - return nil - } - return a.Orgs -} - -// GetPages returns the Pages field. -func (a *AdminStats) GetPages() *PageStats { - if a == nil { - return nil - } - return a.Pages -} - -// GetPulls returns the Pulls field. -func (a *AdminStats) GetPulls() *PullStats { - if a == nil { - return nil - } - return a.Pulls -} - -// GetRepos returns the Repos field. -func (a *AdminStats) GetRepos() *RepoStats { - if a == nil { - return nil - } - return a.Repos -} - -// GetUsers returns the Users field. -func (a *AdminStats) GetUsers() *UserStats { - if a == nil { - return nil - } - return a.Users -} - -// GetVerifiablePasswordAuthentication returns the VerifiablePasswordAuthentication field if it's non-nil, zero value otherwise. -func (a *APIMeta) GetVerifiablePasswordAuthentication() bool { - if a == nil || a.VerifiablePasswordAuthentication == nil { - return false - } - return *a.VerifiablePasswordAuthentication -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (a *App) GetCreatedAt() time.Time { - if a == nil || a.CreatedAt == nil { - return time.Time{} - } - return *a.CreatedAt -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (a *App) GetDescription() string { - if a == nil || a.Description == nil { - return "" - } - return *a.Description -} - -// GetExternalURL returns the ExternalURL field if it's non-nil, zero value otherwise. -func (a *App) GetExternalURL() string { - if a == nil || a.ExternalURL == nil { - return "" - } - return *a.ExternalURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (a *App) GetHTMLURL() string { - if a == nil || a.HTMLURL == nil { - return "" - } - return *a.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (a *App) GetID() int64 { - if a == nil || a.ID == nil { - return 0 - } - return *a.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (a *App) GetName() string { - if a == nil || a.Name == nil { - return "" - } - return *a.Name -} - -// GetOwner returns the Owner field. -func (a *App) GetOwner() *User { - if a == nil { - return nil - } - return a.Owner -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (a *App) GetUpdatedAt() time.Time { - if a == nil || a.UpdatedAt == nil { - return time.Time{} - } - return *a.UpdatedAt -} - -// GetApp returns the App field. -func (a *Authorization) GetApp() *AuthorizationApp { - if a == nil { - return nil - } - return a.App -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (a *Authorization) GetCreatedAt() Timestamp { - if a == nil || a.CreatedAt == nil { - return Timestamp{} - } - return *a.CreatedAt -} - -// GetFingerprint returns the Fingerprint field if it's non-nil, zero value otherwise. -func (a *Authorization) GetFingerprint() string { - if a == nil || a.Fingerprint == nil { - return "" - } - return *a.Fingerprint -} - -// GetHashedToken returns the HashedToken field if it's non-nil, zero value otherwise. -func (a *Authorization) GetHashedToken() string { - if a == nil || a.HashedToken == nil { - return "" - } - return *a.HashedToken -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (a *Authorization) GetID() int64 { - if a == nil || a.ID == nil { - return 0 - } - return *a.ID -} - -// GetNote returns the Note field if it's non-nil, zero value otherwise. -func (a *Authorization) GetNote() string { - if a == nil || a.Note == nil { - return "" - } - return *a.Note -} - -// GetNoteURL returns the NoteURL field if it's non-nil, zero value otherwise. -func (a *Authorization) GetNoteURL() string { - if a == nil || a.NoteURL == nil { - return "" - } - return *a.NoteURL -} - -// GetToken returns the Token field if it's non-nil, zero value otherwise. -func (a *Authorization) GetToken() string { - if a == nil || a.Token == nil { - return "" - } - return *a.Token -} - -// GetTokenLastEight returns the TokenLastEight field if it's non-nil, zero value otherwise. -func (a *Authorization) GetTokenLastEight() string { - if a == nil || a.TokenLastEight == nil { - return "" - } - return *a.TokenLastEight -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (a *Authorization) GetUpdatedAt() Timestamp { - if a == nil || a.UpdatedAt == nil { - return Timestamp{} - } - return *a.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (a *Authorization) GetURL() string { - if a == nil || a.URL == nil { - return "" - } - return *a.URL -} - -// GetUser returns the User field. -func (a *Authorization) GetUser() *User { - if a == nil { - return nil - } - return a.User -} - -// GetClientID returns the ClientID field if it's non-nil, zero value otherwise. -func (a *AuthorizationApp) GetClientID() string { - if a == nil || a.ClientID == nil { - return "" - } - return *a.ClientID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (a *AuthorizationApp) GetName() string { - if a == nil || a.Name == nil { - return "" - } - return *a.Name -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (a *AuthorizationApp) GetURL() string { - if a == nil || a.URL == nil { - return "" - } - return *a.URL -} - -// GetClientID returns the ClientID field if it's non-nil, zero value otherwise. -func (a *AuthorizationRequest) GetClientID() string { - if a == nil || a.ClientID == nil { - return "" - } - return *a.ClientID -} - -// GetClientSecret returns the ClientSecret field if it's non-nil, zero value otherwise. -func (a *AuthorizationRequest) GetClientSecret() string { - if a == nil || a.ClientSecret == nil { - return "" - } - return *a.ClientSecret -} - -// GetFingerprint returns the Fingerprint field if it's non-nil, zero value otherwise. -func (a *AuthorizationRequest) GetFingerprint() string { - if a == nil || a.Fingerprint == nil { - return "" - } - return *a.Fingerprint -} - -// GetNote returns the Note field if it's non-nil, zero value otherwise. -func (a *AuthorizationRequest) GetNote() string { - if a == nil || a.Note == nil { - return "" - } - return *a.Note -} - -// GetNoteURL returns the NoteURL field if it's non-nil, zero value otherwise. -func (a *AuthorizationRequest) GetNoteURL() string { - if a == nil || a.NoteURL == nil { - return "" - } - return *a.NoteURL -} - -// GetFingerprint returns the Fingerprint field if it's non-nil, zero value otherwise. -func (a *AuthorizationUpdateRequest) GetFingerprint() string { - if a == nil || a.Fingerprint == nil { - return "" - } - return *a.Fingerprint -} - -// GetNote returns the Note field if it's non-nil, zero value otherwise. -func (a *AuthorizationUpdateRequest) GetNote() string { - if a == nil || a.Note == nil { - return "" - } - return *a.Note -} - -// GetNoteURL returns the NoteURL field if it's non-nil, zero value otherwise. -func (a *AuthorizationUpdateRequest) GetNoteURL() string { - if a == nil || a.NoteURL == nil { - return "" - } - return *a.NoteURL -} - -// GetContent returns the Content field if it's non-nil, zero value otherwise. -func (b *Blob) GetContent() string { - if b == nil || b.Content == nil { - return "" - } - return *b.Content -} - -// GetEncoding returns the Encoding field if it's non-nil, zero value otherwise. -func (b *Blob) GetEncoding() string { - if b == nil || b.Encoding == nil { - return "" - } - return *b.Encoding -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (b *Blob) GetNodeID() string { - if b == nil || b.NodeID == nil { - return "" - } - return *b.NodeID -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (b *Blob) GetSHA() string { - if b == nil || b.SHA == nil { - return "" - } - return *b.SHA -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (b *Blob) GetSize() int { - if b == nil || b.Size == nil { - return 0 - } - return *b.Size -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (b *Blob) GetURL() string { - if b == nil || b.URL == nil { - return "" - } - return *b.URL -} - -// GetCommit returns the Commit field. -func (b *Branch) GetCommit() *RepositoryCommit { - if b == nil { - return nil - } - return b.Commit -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (b *Branch) GetName() string { - if b == nil || b.Name == nil { - return "" - } - return *b.Name -} - -// GetProtected returns the Protected field if it's non-nil, zero value otherwise. -func (b *Branch) GetProtected() bool { - if b == nil || b.Protected == nil { - return false - } - return *b.Protected -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (c *CodeOfConduct) GetBody() string { - if c == nil || c.Body == nil { - return "" - } - return *c.Body -} - -// GetKey returns the Key field if it's non-nil, zero value otherwise. -func (c *CodeOfConduct) GetKey() string { - if c == nil || c.Key == nil { - return "" - } - return *c.Key -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (c *CodeOfConduct) GetName() string { - if c == nil || c.Name == nil { - return "" - } - return *c.Name -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (c *CodeOfConduct) GetURL() string { - if c == nil || c.URL == nil { - return "" - } - return *c.URL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (c *CodeResult) GetHTMLURL() string { - if c == nil || c.HTMLURL == nil { - return "" - } - return *c.HTMLURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (c *CodeResult) GetName() string { - if c == nil || c.Name == nil { - return "" - } - return *c.Name -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (c *CodeResult) GetPath() string { - if c == nil || c.Path == nil { - return "" - } - return *c.Path -} - -// GetRepository returns the Repository field. -func (c *CodeResult) GetRepository() *Repository { - if c == nil { - return nil - } - return c.Repository -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (c *CodeResult) GetSHA() string { - if c == nil || c.SHA == nil { - return "" - } - return *c.SHA -} - -// GetIncompleteResults returns the IncompleteResults field if it's non-nil, zero value otherwise. -func (c *CodeSearchResult) GetIncompleteResults() bool { - if c == nil || c.IncompleteResults == nil { - return false - } - return *c.IncompleteResults -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (c *CodeSearchResult) GetTotal() int { - if c == nil || c.Total == nil { - return 0 - } - return *c.Total -} - -// GetCommitURL returns the CommitURL field if it's non-nil, zero value otherwise. -func (c *CombinedStatus) GetCommitURL() string { - if c == nil || c.CommitURL == nil { - return "" - } - return *c.CommitURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (c *CombinedStatus) GetName() string { - if c == nil || c.Name == nil { - return "" - } - return *c.Name -} - -// GetRepositoryURL returns the RepositoryURL field if it's non-nil, zero value otherwise. -func (c *CombinedStatus) GetRepositoryURL() string { - if c == nil || c.RepositoryURL == nil { - return "" - } - return *c.RepositoryURL -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (c *CombinedStatus) GetSHA() string { - if c == nil || c.SHA == nil { - return "" - } - return *c.SHA -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (c *CombinedStatus) GetState() string { - if c == nil || c.State == nil { - return "" - } - return *c.State -} - -// GetTotalCount returns the TotalCount field if it's non-nil, zero value otherwise. -func (c *CombinedStatus) GetTotalCount() int { - if c == nil || c.TotalCount == nil { - return 0 - } - return *c.TotalCount -} - -// GetTotalCommitComments returns the TotalCommitComments field if it's non-nil, zero value otherwise. -func (c *CommentStats) GetTotalCommitComments() int { - if c == nil || c.TotalCommitComments == nil { - return 0 - } - return *c.TotalCommitComments -} - -// GetTotalGistComments returns the TotalGistComments field if it's non-nil, zero value otherwise. -func (c *CommentStats) GetTotalGistComments() int { - if c == nil || c.TotalGistComments == nil { - return 0 - } - return *c.TotalGistComments -} - -// GetTotalIssueComments returns the TotalIssueComments field if it's non-nil, zero value otherwise. -func (c *CommentStats) GetTotalIssueComments() int { - if c == nil || c.TotalIssueComments == nil { - return 0 - } - return *c.TotalIssueComments -} - -// GetTotalPullRequestComments returns the TotalPullRequestComments field if it's non-nil, zero value otherwise. -func (c *CommentStats) GetTotalPullRequestComments() int { - if c == nil || c.TotalPullRequestComments == nil { - return 0 - } - return *c.TotalPullRequestComments -} - -// GetAuthor returns the Author field. -func (c *Commit) GetAuthor() *CommitAuthor { - if c == nil { - return nil - } - return c.Author -} - -// GetCommentCount returns the CommentCount field if it's non-nil, zero value otherwise. -func (c *Commit) GetCommentCount() int { - if c == nil || c.CommentCount == nil { - return 0 - } - return *c.CommentCount -} - -// GetCommitter returns the Committer field. -func (c *Commit) GetCommitter() *CommitAuthor { - if c == nil { - return nil - } - return c.Committer -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (c *Commit) GetHTMLURL() string { - if c == nil || c.HTMLURL == nil { - return "" - } - return *c.HTMLURL -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (c *Commit) GetMessage() string { - if c == nil || c.Message == nil { - return "" - } - return *c.Message -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (c *Commit) GetNodeID() string { - if c == nil || c.NodeID == nil { - return "" - } - return *c.NodeID -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (c *Commit) GetSHA() string { - if c == nil || c.SHA == nil { - return "" - } - return *c.SHA -} - -// GetStats returns the Stats field. -func (c *Commit) GetStats() *CommitStats { - if c == nil { - return nil - } - return c.Stats -} - -// GetTree returns the Tree field. -func (c *Commit) GetTree() *Tree { - if c == nil { - return nil - } - return c.Tree -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (c *Commit) GetURL() string { - if c == nil || c.URL == nil { - return "" - } - return *c.URL -} - -// GetVerification returns the Verification field. -func (c *Commit) GetVerification() *SignatureVerification { - if c == nil { - return nil - } - return c.Verification -} - -// GetDate returns the Date field if it's non-nil, zero value otherwise. -func (c *CommitAuthor) GetDate() time.Time { - if c == nil || c.Date == nil { - return time.Time{} - } - return *c.Date -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (c *CommitAuthor) GetEmail() string { - if c == nil || c.Email == nil { - return "" - } - return *c.Email -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (c *CommitAuthor) GetLogin() string { - if c == nil || c.Login == nil { - return "" - } - return *c.Login -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (c *CommitAuthor) GetName() string { - if c == nil || c.Name == nil { - return "" - } - return *c.Name -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (c *CommitCommentEvent) GetAction() string { - if c == nil || c.Action == nil { - return "" - } - return *c.Action -} - -// GetComment returns the Comment field. -func (c *CommitCommentEvent) GetComment() *RepositoryComment { - if c == nil { - return nil - } - return c.Comment -} - -// GetInstallation returns the Installation field. -func (c *CommitCommentEvent) GetInstallation() *Installation { - if c == nil { - return nil - } - return c.Installation -} - -// GetRepo returns the Repo field. -func (c *CommitCommentEvent) GetRepo() *Repository { - if c == nil { - return nil - } - return c.Repo -} - -// GetSender returns the Sender field. -func (c *CommitCommentEvent) GetSender() *User { - if c == nil { - return nil - } - return c.Sender -} - -// GetAdditions returns the Additions field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetAdditions() int { - if c == nil || c.Additions == nil { - return 0 - } - return *c.Additions -} - -// GetBlobURL returns the BlobURL field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetBlobURL() string { - if c == nil || c.BlobURL == nil { - return "" - } - return *c.BlobURL -} - -// GetChanges returns the Changes field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetChanges() int { - if c == nil || c.Changes == nil { - return 0 - } - return *c.Changes -} - -// GetContentsURL returns the ContentsURL field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetContentsURL() string { - if c == nil || c.ContentsURL == nil { - return "" - } - return *c.ContentsURL -} - -// GetDeletions returns the Deletions field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetDeletions() int { - if c == nil || c.Deletions == nil { - return 0 - } - return *c.Deletions -} - -// GetFilename returns the Filename field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetFilename() string { - if c == nil || c.Filename == nil { - return "" - } - return *c.Filename -} - -// GetPatch returns the Patch field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetPatch() string { - if c == nil || c.Patch == nil { - return "" - } - return *c.Patch -} - -// GetRawURL returns the RawURL field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetRawURL() string { - if c == nil || c.RawURL == nil { - return "" - } - return *c.RawURL -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetSHA() string { - if c == nil || c.SHA == nil { - return "" - } - return *c.SHA -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetStatus() string { - if c == nil || c.Status == nil { - return "" - } - return *c.Status -} - -// GetAuthor returns the Author field. -func (c *CommitResult) GetAuthor() *User { - if c == nil { - return nil - } - return c.Author -} - -// GetCommentsURL returns the CommentsURL field if it's non-nil, zero value otherwise. -func (c *CommitResult) GetCommentsURL() string { - if c == nil || c.CommentsURL == nil { - return "" - } - return *c.CommentsURL -} - -// GetCommit returns the Commit field. -func (c *CommitResult) GetCommit() *Commit { - if c == nil { - return nil - } - return c.Commit -} - -// GetCommitter returns the Committer field. -func (c *CommitResult) GetCommitter() *User { - if c == nil { - return nil - } - return c.Committer -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (c *CommitResult) GetHTMLURL() string { - if c == nil || c.HTMLURL == nil { - return "" - } - return *c.HTMLURL -} - -// GetRepository returns the Repository field. -func (c *CommitResult) GetRepository() *Repository { - if c == nil { - return nil - } - return c.Repository -} - -// GetScore returns the Score field. -func (c *CommitResult) GetScore() *float64 { - if c == nil { - return nil - } - return c.Score -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (c *CommitResult) GetSHA() string { - if c == nil || c.SHA == nil { - return "" - } - return *c.SHA -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (c *CommitResult) GetURL() string { - if c == nil || c.URL == nil { - return "" - } - return *c.URL -} - -// GetAheadBy returns the AheadBy field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetAheadBy() int { - if c == nil || c.AheadBy == nil { - return 0 - } - return *c.AheadBy -} - -// GetBaseCommit returns the BaseCommit field. -func (c *CommitsComparison) GetBaseCommit() *RepositoryCommit { - if c == nil { - return nil - } - return c.BaseCommit -} - -// GetBehindBy returns the BehindBy field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetBehindBy() int { - if c == nil || c.BehindBy == nil { - return 0 - } - return *c.BehindBy -} - -// GetDiffURL returns the DiffURL field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetDiffURL() string { - if c == nil || c.DiffURL == nil { - return "" - } - return *c.DiffURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetHTMLURL() string { - if c == nil || c.HTMLURL == nil { - return "" - } - return *c.HTMLURL -} - -// GetMergeBaseCommit returns the MergeBaseCommit field. -func (c *CommitsComparison) GetMergeBaseCommit() *RepositoryCommit { - if c == nil { - return nil - } - return c.MergeBaseCommit -} - -// GetPatchURL returns the PatchURL field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetPatchURL() string { - if c == nil || c.PatchURL == nil { - return "" - } - return *c.PatchURL -} - -// GetPermalinkURL returns the PermalinkURL field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetPermalinkURL() string { - if c == nil || c.PermalinkURL == nil { - return "" - } - return *c.PermalinkURL -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetStatus() string { - if c == nil || c.Status == nil { - return "" - } - return *c.Status -} - -// GetTotalCommits returns the TotalCommits field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetTotalCommits() int { - if c == nil || c.TotalCommits == nil { - return 0 - } - return *c.TotalCommits -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetURL() string { - if c == nil || c.URL == nil { - return "" - } - return *c.URL -} - -// GetIncompleteResults returns the IncompleteResults field if it's non-nil, zero value otherwise. -func (c *CommitsSearchResult) GetIncompleteResults() bool { - if c == nil || c.IncompleteResults == nil { - return false - } - return *c.IncompleteResults -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (c *CommitsSearchResult) GetTotal() int { - if c == nil || c.Total == nil { - return 0 - } - return *c.Total -} - -// GetAdditions returns the Additions field if it's non-nil, zero value otherwise. -func (c *CommitStats) GetAdditions() int { - if c == nil || c.Additions == nil { - return 0 - } - return *c.Additions -} - -// GetDeletions returns the Deletions field if it's non-nil, zero value otherwise. -func (c *CommitStats) GetDeletions() int { - if c == nil || c.Deletions == nil { - return 0 - } - return *c.Deletions -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (c *CommitStats) GetTotal() int { - if c == nil || c.Total == nil { - return 0 - } - return *c.Total -} - -// GetCodeOfConduct returns the CodeOfConduct field. -func (c *CommunityHealthFiles) GetCodeOfConduct() *Metric { - if c == nil { - return nil - } - return c.CodeOfConduct -} - -// GetContributing returns the Contributing field. -func (c *CommunityHealthFiles) GetContributing() *Metric { - if c == nil { - return nil - } - return c.Contributing -} - -// GetLicense returns the License field. -func (c *CommunityHealthFiles) GetLicense() *Metric { - if c == nil { - return nil - } - return c.License -} - -// GetReadme returns the Readme field. -func (c *CommunityHealthFiles) GetReadme() *Metric { - if c == nil { - return nil - } - return c.Readme -} - -// GetFiles returns the Files field. -func (c *CommunityHealthMetrics) GetFiles() *CommunityHealthFiles { - if c == nil { - return nil - } - return c.Files -} - -// GetHealthPercentage returns the HealthPercentage field if it's non-nil, zero value otherwise. -func (c *CommunityHealthMetrics) GetHealthPercentage() int { - if c == nil || c.HealthPercentage == nil { - return 0 - } - return *c.HealthPercentage -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (c *CommunityHealthMetrics) GetUpdatedAt() time.Time { - if c == nil || c.UpdatedAt == nil { - return time.Time{} - } - return *c.UpdatedAt -} - -// GetAvatarURL returns the AvatarURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetAvatarURL() string { - if c == nil || c.AvatarURL == nil { - return "" - } - return *c.AvatarURL -} - -// GetContributions returns the Contributions field if it's non-nil, zero value otherwise. -func (c *Contributor) GetContributions() int { - if c == nil || c.Contributions == nil { - return 0 - } - return *c.Contributions -} - -// GetEventsURL returns the EventsURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetEventsURL() string { - if c == nil || c.EventsURL == nil { - return "" - } - return *c.EventsURL -} - -// GetFollowersURL returns the FollowersURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetFollowersURL() string { - if c == nil || c.FollowersURL == nil { - return "" - } - return *c.FollowersURL -} - -// GetFollowingURL returns the FollowingURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetFollowingURL() string { - if c == nil || c.FollowingURL == nil { - return "" - } - return *c.FollowingURL -} - -// GetGistsURL returns the GistsURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetGistsURL() string { - if c == nil || c.GistsURL == nil { - return "" - } - return *c.GistsURL -} - -// GetGravatarID returns the GravatarID field if it's non-nil, zero value otherwise. -func (c *Contributor) GetGravatarID() string { - if c == nil || c.GravatarID == nil { - return "" - } - return *c.GravatarID -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetHTMLURL() string { - if c == nil || c.HTMLURL == nil { - return "" - } - return *c.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (c *Contributor) GetID() int64 { - if c == nil || c.ID == nil { - return 0 - } - return *c.ID -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (c *Contributor) GetLogin() string { - if c == nil || c.Login == nil { - return "" - } - return *c.Login -} - -// GetOrganizationsURL returns the OrganizationsURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetOrganizationsURL() string { - if c == nil || c.OrganizationsURL == nil { - return "" - } - return *c.OrganizationsURL -} - -// GetReceivedEventsURL returns the ReceivedEventsURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetReceivedEventsURL() string { - if c == nil || c.ReceivedEventsURL == nil { - return "" - } - return *c.ReceivedEventsURL -} - -// GetReposURL returns the ReposURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetReposURL() string { - if c == nil || c.ReposURL == nil { - return "" - } - return *c.ReposURL -} - -// GetSiteAdmin returns the SiteAdmin field if it's non-nil, zero value otherwise. -func (c *Contributor) GetSiteAdmin() bool { - if c == nil || c.SiteAdmin == nil { - return false - } - return *c.SiteAdmin -} - -// GetStarredURL returns the StarredURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetStarredURL() string { - if c == nil || c.StarredURL == nil { - return "" - } - return *c.StarredURL -} - -// GetSubscriptionsURL returns the SubscriptionsURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetSubscriptionsURL() string { - if c == nil || c.SubscriptionsURL == nil { - return "" - } - return *c.SubscriptionsURL -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (c *Contributor) GetType() string { - if c == nil || c.Type == nil { - return "" - } - return *c.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetURL() string { - if c == nil || c.URL == nil { - return "" - } - return *c.URL -} - -// GetAuthor returns the Author field. -func (c *ContributorStats) GetAuthor() *Contributor { - if c == nil { - return nil - } - return c.Author -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (c *ContributorStats) GetTotal() int { - if c == nil || c.Total == nil { - return 0 - } - return *c.Total -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (c *CreateEvent) GetDescription() string { - if c == nil || c.Description == nil { - return "" - } - return *c.Description -} - -// GetInstallation returns the Installation field. -func (c *CreateEvent) GetInstallation() *Installation { - if c == nil { - return nil - } - return c.Installation -} - -// GetMasterBranch returns the MasterBranch field if it's non-nil, zero value otherwise. -func (c *CreateEvent) GetMasterBranch() string { - if c == nil || c.MasterBranch == nil { - return "" - } - return *c.MasterBranch -} - -// GetPusherType returns the PusherType field if it's non-nil, zero value otherwise. -func (c *CreateEvent) GetPusherType() string { - if c == nil || c.PusherType == nil { - return "" - } - return *c.PusherType -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (c *CreateEvent) GetRef() string { - if c == nil || c.Ref == nil { - return "" - } - return *c.Ref -} - -// GetRefType returns the RefType field if it's non-nil, zero value otherwise. -func (c *CreateEvent) GetRefType() string { - if c == nil || c.RefType == nil { - return "" - } - return *c.RefType -} - -// GetRepo returns the Repo field. -func (c *CreateEvent) GetRepo() *Repository { - if c == nil { - return nil - } - return c.Repo -} - -// GetSender returns the Sender field. -func (c *CreateEvent) GetSender() *User { - if c == nil { - return nil - } - return c.Sender -} - -// GetInstallation returns the Installation field. -func (d *DeleteEvent) GetInstallation() *Installation { - if d == nil { - return nil - } - return d.Installation -} - -// GetPusherType returns the PusherType field if it's non-nil, zero value otherwise. -func (d *DeleteEvent) GetPusherType() string { - if d == nil || d.PusherType == nil { - return "" - } - return *d.PusherType -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (d *DeleteEvent) GetRef() string { - if d == nil || d.Ref == nil { - return "" - } - return *d.Ref -} - -// GetRefType returns the RefType field if it's non-nil, zero value otherwise. -func (d *DeleteEvent) GetRefType() string { - if d == nil || d.RefType == nil { - return "" - } - return *d.RefType -} - -// GetRepo returns the Repo field. -func (d *DeleteEvent) GetRepo() *Repository { - if d == nil { - return nil - } - return d.Repo -} - -// GetSender returns the Sender field. -func (d *DeleteEvent) GetSender() *User { - if d == nil { - return nil - } - return d.Sender -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (d *Deployment) GetCreatedAt() Timestamp { - if d == nil || d.CreatedAt == nil { - return Timestamp{} - } - return *d.CreatedAt -} - -// GetCreator returns the Creator field. -func (d *Deployment) GetCreator() *User { - if d == nil { - return nil - } - return d.Creator -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (d *Deployment) GetDescription() string { - if d == nil || d.Description == nil { - return "" - } - return *d.Description -} - -// GetEnvironment returns the Environment field if it's non-nil, zero value otherwise. -func (d *Deployment) GetEnvironment() string { - if d == nil || d.Environment == nil { - return "" - } - return *d.Environment -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (d *Deployment) GetID() int64 { - if d == nil || d.ID == nil { - return 0 - } - return *d.ID -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (d *Deployment) GetNodeID() string { - if d == nil || d.NodeID == nil { - return "" - } - return *d.NodeID -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (d *Deployment) GetRef() string { - if d == nil || d.Ref == nil { - return "" - } - return *d.Ref -} - -// GetRepositoryURL returns the RepositoryURL field if it's non-nil, zero value otherwise. -func (d *Deployment) GetRepositoryURL() string { - if d == nil || d.RepositoryURL == nil { - return "" - } - return *d.RepositoryURL -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (d *Deployment) GetSHA() string { - if d == nil || d.SHA == nil { - return "" - } - return *d.SHA -} - -// GetStatusesURL returns the StatusesURL field if it's non-nil, zero value otherwise. -func (d *Deployment) GetStatusesURL() string { - if d == nil || d.StatusesURL == nil { - return "" - } - return *d.StatusesURL -} - -// GetTask returns the Task field if it's non-nil, zero value otherwise. -func (d *Deployment) GetTask() string { - if d == nil || d.Task == nil { - return "" - } - return *d.Task -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (d *Deployment) GetUpdatedAt() Timestamp { - if d == nil || d.UpdatedAt == nil { - return Timestamp{} - } - return *d.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (d *Deployment) GetURL() string { - if d == nil || d.URL == nil { - return "" - } - return *d.URL -} - -// GetDeployment returns the Deployment field. -func (d *DeploymentEvent) GetDeployment() *Deployment { - if d == nil { - return nil - } - return d.Deployment -} - -// GetInstallation returns the Installation field. -func (d *DeploymentEvent) GetInstallation() *Installation { - if d == nil { - return nil - } - return d.Installation -} - -// GetRepo returns the Repo field. -func (d *DeploymentEvent) GetRepo() *Repository { - if d == nil { - return nil - } - return d.Repo -} - -// GetSender returns the Sender field. -func (d *DeploymentEvent) GetSender() *User { - if d == nil { - return nil - } - return d.Sender -} - -// GetAutoMerge returns the AutoMerge field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetAutoMerge() bool { - if d == nil || d.AutoMerge == nil { - return false - } - return *d.AutoMerge -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetDescription() string { - if d == nil || d.Description == nil { - return "" - } - return *d.Description -} - -// GetEnvironment returns the Environment field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetEnvironment() string { - if d == nil || d.Environment == nil { - return "" - } - return *d.Environment -} - -// GetPayload returns the Payload field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetPayload() string { - if d == nil || d.Payload == nil { - return "" - } - return *d.Payload -} - -// GetProductionEnvironment returns the ProductionEnvironment field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetProductionEnvironment() bool { - if d == nil || d.ProductionEnvironment == nil { - return false - } - return *d.ProductionEnvironment -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetRef() string { - if d == nil || d.Ref == nil { - return "" - } - return *d.Ref -} - -// GetRequiredContexts returns the RequiredContexts field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetRequiredContexts() []string { - if d == nil || d.RequiredContexts == nil { - return nil - } - return *d.RequiredContexts -} - -// GetTask returns the Task field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetTask() string { - if d == nil || d.Task == nil { - return "" - } - return *d.Task -} - -// GetTransientEnvironment returns the TransientEnvironment field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetTransientEnvironment() bool { - if d == nil || d.TransientEnvironment == nil { - return false - } - return *d.TransientEnvironment -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetCreatedAt() Timestamp { - if d == nil || d.CreatedAt == nil { - return Timestamp{} - } - return *d.CreatedAt -} - -// GetCreator returns the Creator field. -func (d *DeploymentStatus) GetCreator() *User { - if d == nil { - return nil - } - return d.Creator -} - -// GetDeploymentURL returns the DeploymentURL field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetDeploymentURL() string { - if d == nil || d.DeploymentURL == nil { - return "" - } - return *d.DeploymentURL -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetDescription() string { - if d == nil || d.Description == nil { - return "" - } - return *d.Description -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetID() int64 { - if d == nil || d.ID == nil { - return 0 - } - return *d.ID -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetNodeID() string { - if d == nil || d.NodeID == nil { - return "" - } - return *d.NodeID -} - -// GetRepositoryURL returns the RepositoryURL field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetRepositoryURL() string { - if d == nil || d.RepositoryURL == nil { - return "" - } - return *d.RepositoryURL -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetState() string { - if d == nil || d.State == nil { - return "" - } - return *d.State -} - -// GetTargetURL returns the TargetURL field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetTargetURL() string { - if d == nil || d.TargetURL == nil { - return "" - } - return *d.TargetURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetUpdatedAt() Timestamp { - if d == nil || d.UpdatedAt == nil { - return Timestamp{} - } - return *d.UpdatedAt -} - -// GetDeployment returns the Deployment field. -func (d *DeploymentStatusEvent) GetDeployment() *Deployment { - if d == nil { - return nil - } - return d.Deployment -} - -// GetDeploymentStatus returns the DeploymentStatus field. -func (d *DeploymentStatusEvent) GetDeploymentStatus() *DeploymentStatus { - if d == nil { - return nil - } - return d.DeploymentStatus -} - -// GetInstallation returns the Installation field. -func (d *DeploymentStatusEvent) GetInstallation() *Installation { - if d == nil { - return nil - } - return d.Installation -} - -// GetRepo returns the Repo field. -func (d *DeploymentStatusEvent) GetRepo() *Repository { - if d == nil { - return nil - } - return d.Repo -} - -// GetSender returns the Sender field. -func (d *DeploymentStatusEvent) GetSender() *User { - if d == nil { - return nil - } - return d.Sender -} - -// GetAutoInactive returns the AutoInactive field if it's non-nil, zero value otherwise. -func (d *DeploymentStatusRequest) GetAutoInactive() bool { - if d == nil || d.AutoInactive == nil { - return false - } - return *d.AutoInactive -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (d *DeploymentStatusRequest) GetDescription() string { - if d == nil || d.Description == nil { - return "" - } - return *d.Description -} - -// GetEnvironmentURL returns the EnvironmentURL field if it's non-nil, zero value otherwise. -func (d *DeploymentStatusRequest) GetEnvironmentURL() string { - if d == nil || d.EnvironmentURL == nil { - return "" - } - return *d.EnvironmentURL -} - -// GetLogURL returns the LogURL field if it's non-nil, zero value otherwise. -func (d *DeploymentStatusRequest) GetLogURL() string { - if d == nil || d.LogURL == nil { - return "" - } - return *d.LogURL -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (d *DeploymentStatusRequest) GetState() string { - if d == nil || d.State == nil { - return "" - } - return *d.State -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (d *DraftReviewComment) GetBody() string { - if d == nil || d.Body == nil { - return "" - } - return *d.Body -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (d *DraftReviewComment) GetPath() string { - if d == nil || d.Path == nil { - return "" - } - return *d.Path -} - -// GetPosition returns the Position field if it's non-nil, zero value otherwise. -func (d *DraftReviewComment) GetPosition() int { - if d == nil || d.Position == nil { - return 0 - } - return *d.Position -} - -// GetActor returns the Actor field. -func (e *Event) GetActor() *User { - if e == nil { - return nil - } - return e.Actor -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (e *Event) GetCreatedAt() time.Time { - if e == nil || e.CreatedAt == nil { - return time.Time{} - } - return *e.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (e *Event) GetID() string { - if e == nil || e.ID == nil { - return "" - } - return *e.ID -} - -// GetOrg returns the Org field. -func (e *Event) GetOrg() *Organization { - if e == nil { - return nil - } - return e.Org -} - -// GetPublic returns the Public field if it's non-nil, zero value otherwise. -func (e *Event) GetPublic() bool { - if e == nil || e.Public == nil { - return false - } - return *e.Public -} - -// GetRawPayload returns the RawPayload field if it's non-nil, zero value otherwise. -func (e *Event) GetRawPayload() json.RawMessage { - if e == nil || e.RawPayload == nil { - return json.RawMessage{} - } - return *e.RawPayload -} - -// GetRepo returns the Repo field. -func (e *Event) GetRepo() *Repository { - if e == nil { - return nil - } - return e.Repo -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (e *Event) GetType() string { - if e == nil || e.Type == nil { - return "" - } - return *e.Type -} - -// GetHRef returns the HRef field if it's non-nil, zero value otherwise. -func (f *FeedLink) GetHRef() string { - if f == nil || f.HRef == nil { - return "" - } - return *f.HRef -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (f *FeedLink) GetType() string { - if f == nil || f.Type == nil { - return "" - } - return *f.Type -} - -// GetCurrentUserActorURL returns the CurrentUserActorURL field if it's non-nil, zero value otherwise. -func (f *Feeds) GetCurrentUserActorURL() string { - if f == nil || f.CurrentUserActorURL == nil { - return "" - } - return *f.CurrentUserActorURL -} - -// GetCurrentUserOrganizationURL returns the CurrentUserOrganizationURL field if it's non-nil, zero value otherwise. -func (f *Feeds) GetCurrentUserOrganizationURL() string { - if f == nil || f.CurrentUserOrganizationURL == nil { - return "" - } - return *f.CurrentUserOrganizationURL -} - -// GetCurrentUserPublicURL returns the CurrentUserPublicURL field if it's non-nil, zero value otherwise. -func (f *Feeds) GetCurrentUserPublicURL() string { - if f == nil || f.CurrentUserPublicURL == nil { - return "" - } - return *f.CurrentUserPublicURL -} - -// GetCurrentUserURL returns the CurrentUserURL field if it's non-nil, zero value otherwise. -func (f *Feeds) GetCurrentUserURL() string { - if f == nil || f.CurrentUserURL == nil { - return "" - } - return *f.CurrentUserURL -} - -// GetTimelineURL returns the TimelineURL field if it's non-nil, zero value otherwise. -func (f *Feeds) GetTimelineURL() string { - if f == nil || f.TimelineURL == nil { - return "" - } - return *f.TimelineURL -} - -// GetUserURL returns the UserURL field if it's non-nil, zero value otherwise. -func (f *Feeds) GetUserURL() string { - if f == nil || f.UserURL == nil { - return "" - } - return *f.UserURL -} - -// GetForkee returns the Forkee field. -func (f *ForkEvent) GetForkee() *Repository { - if f == nil { - return nil - } - return f.Forkee -} - -// GetInstallation returns the Installation field. -func (f *ForkEvent) GetInstallation() *Installation { - if f == nil { - return nil - } - return f.Installation -} - -// GetRepo returns the Repo field. -func (f *ForkEvent) GetRepo() *Repository { - if f == nil { - return nil - } - return f.Repo -} - -// GetSender returns the Sender field. -func (f *ForkEvent) GetSender() *User { - if f == nil { - return nil - } - return f.Sender -} - -// GetComments returns the Comments field if it's non-nil, zero value otherwise. -func (g *Gist) GetComments() int { - if g == nil || g.Comments == nil { - return 0 - } - return *g.Comments -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (g *Gist) GetCreatedAt() time.Time { - if g == nil || g.CreatedAt == nil { - return time.Time{} - } - return *g.CreatedAt -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (g *Gist) GetDescription() string { - if g == nil || g.Description == nil { - return "" - } - return *g.Description -} - -// GetGitPullURL returns the GitPullURL field if it's non-nil, zero value otherwise. -func (g *Gist) GetGitPullURL() string { - if g == nil || g.GitPullURL == nil { - return "" - } - return *g.GitPullURL -} - -// GetGitPushURL returns the GitPushURL field if it's non-nil, zero value otherwise. -func (g *Gist) GetGitPushURL() string { - if g == nil || g.GitPushURL == nil { - return "" - } - return *g.GitPushURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (g *Gist) GetHTMLURL() string { - if g == nil || g.HTMLURL == nil { - return "" - } - return *g.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (g *Gist) GetID() string { - if g == nil || g.ID == nil { - return "" - } - return *g.ID -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (g *Gist) GetNodeID() string { - if g == nil || g.NodeID == nil { - return "" - } - return *g.NodeID -} - -// GetOwner returns the Owner field. -func (g *Gist) GetOwner() *User { - if g == nil { - return nil - } - return g.Owner -} - -// GetPublic returns the Public field if it's non-nil, zero value otherwise. -func (g *Gist) GetPublic() bool { - if g == nil || g.Public == nil { - return false - } - return *g.Public -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (g *Gist) GetUpdatedAt() time.Time { - if g == nil || g.UpdatedAt == nil { - return time.Time{} - } - return *g.UpdatedAt -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (g *GistComment) GetBody() string { - if g == nil || g.Body == nil { - return "" - } - return *g.Body -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (g *GistComment) GetCreatedAt() time.Time { - if g == nil || g.CreatedAt == nil { - return time.Time{} - } - return *g.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (g *GistComment) GetID() int64 { - if g == nil || g.ID == nil { - return 0 - } - return *g.ID -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (g *GistComment) GetURL() string { - if g == nil || g.URL == nil { - return "" - } - return *g.URL -} - -// GetUser returns the User field. -func (g *GistComment) GetUser() *User { - if g == nil { - return nil - } - return g.User -} - -// GetChangeStatus returns the ChangeStatus field. -func (g *GistCommit) GetChangeStatus() *CommitStats { - if g == nil { - return nil - } - return g.ChangeStatus -} - -// GetCommittedAt returns the CommittedAt field if it's non-nil, zero value otherwise. -func (g *GistCommit) GetCommittedAt() Timestamp { - if g == nil || g.CommittedAt == nil { - return Timestamp{} - } - return *g.CommittedAt -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (g *GistCommit) GetNodeID() string { - if g == nil || g.NodeID == nil { - return "" - } - return *g.NodeID -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (g *GistCommit) GetURL() string { - if g == nil || g.URL == nil { - return "" - } - return *g.URL -} - -// GetUser returns the User field. -func (g *GistCommit) GetUser() *User { - if g == nil { - return nil - } - return g.User -} - -// GetVersion returns the Version field if it's non-nil, zero value otherwise. -func (g *GistCommit) GetVersion() string { - if g == nil || g.Version == nil { - return "" - } - return *g.Version -} - -// GetContent returns the Content field if it's non-nil, zero value otherwise. -func (g *GistFile) GetContent() string { - if g == nil || g.Content == nil { - return "" - } - return *g.Content -} - -// GetFilename returns the Filename field if it's non-nil, zero value otherwise. -func (g *GistFile) GetFilename() string { - if g == nil || g.Filename == nil { - return "" - } - return *g.Filename -} - -// GetLanguage returns the Language field if it's non-nil, zero value otherwise. -func (g *GistFile) GetLanguage() string { - if g == nil || g.Language == nil { - return "" - } - return *g.Language -} - -// GetRawURL returns the RawURL field if it's non-nil, zero value otherwise. -func (g *GistFile) GetRawURL() string { - if g == nil || g.RawURL == nil { - return "" - } - return *g.RawURL -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (g *GistFile) GetSize() int { - if g == nil || g.Size == nil { - return 0 - } - return *g.Size -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (g *GistFile) GetType() string { - if g == nil || g.Type == nil { - return "" - } - return *g.Type -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (g *GistFork) GetCreatedAt() Timestamp { - if g == nil || g.CreatedAt == nil { - return Timestamp{} - } - return *g.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (g *GistFork) GetID() string { - if g == nil || g.ID == nil { - return "" - } - return *g.ID -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (g *GistFork) GetNodeID() string { - if g == nil || g.NodeID == nil { - return "" - } - return *g.NodeID -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (g *GistFork) GetUpdatedAt() Timestamp { - if g == nil || g.UpdatedAt == nil { - return Timestamp{} - } - return *g.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (g *GistFork) GetURL() string { - if g == nil || g.URL == nil { - return "" - } - return *g.URL -} - -// GetUser returns the User field. -func (g *GistFork) GetUser() *User { - if g == nil { - return nil - } - return g.User -} - -// GetPrivateGists returns the PrivateGists field if it's non-nil, zero value otherwise. -func (g *GistStats) GetPrivateGists() int { - if g == nil || g.PrivateGists == nil { - return 0 - } - return *g.PrivateGists -} - -// GetPublicGists returns the PublicGists field if it's non-nil, zero value otherwise. -func (g *GistStats) GetPublicGists() int { - if g == nil || g.PublicGists == nil { - return 0 - } - return *g.PublicGists -} - -// GetTotalGists returns the TotalGists field if it's non-nil, zero value otherwise. -func (g *GistStats) GetTotalGists() int { - if g == nil || g.TotalGists == nil { - return 0 - } - return *g.TotalGists -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (g *Gitignore) GetName() string { - if g == nil || g.Name == nil { - return "" - } - return *g.Name -} - -// GetSource returns the Source field if it's non-nil, zero value otherwise. -func (g *Gitignore) GetSource() string { - if g == nil || g.Source == nil { - return "" - } - return *g.Source -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (g *GitObject) GetSHA() string { - if g == nil || g.SHA == nil { - return "" - } - return *g.SHA -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (g *GitObject) GetType() string { - if g == nil || g.Type == nil { - return "" - } - return *g.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (g *GitObject) GetURL() string { - if g == nil || g.URL == nil { - return "" - } - return *g.URL -} - -// GetInstallation returns the Installation field. -func (g *GollumEvent) GetInstallation() *Installation { - if g == nil { - return nil - } - return g.Installation -} - -// GetRepo returns the Repo field. -func (g *GollumEvent) GetRepo() *Repository { - if g == nil { - return nil - } - return g.Repo -} - -// GetSender returns the Sender field. -func (g *GollumEvent) GetSender() *User { - if g == nil { - return nil - } - return g.Sender -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (g *GPGEmail) GetEmail() string { - if g == nil || g.Email == nil { - return "" - } - return *g.Email -} - -// GetVerified returns the Verified field if it's non-nil, zero value otherwise. -func (g *GPGEmail) GetVerified() bool { - if g == nil || g.Verified == nil { - return false - } - return *g.Verified -} - -// GetCanCertify returns the CanCertify field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetCanCertify() bool { - if g == nil || g.CanCertify == nil { - return false - } - return *g.CanCertify -} - -// GetCanEncryptComms returns the CanEncryptComms field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetCanEncryptComms() bool { - if g == nil || g.CanEncryptComms == nil { - return false - } - return *g.CanEncryptComms -} - -// GetCanEncryptStorage returns the CanEncryptStorage field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetCanEncryptStorage() bool { - if g == nil || g.CanEncryptStorage == nil { - return false - } - return *g.CanEncryptStorage -} - -// GetCanSign returns the CanSign field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetCanSign() bool { - if g == nil || g.CanSign == nil { - return false - } - return *g.CanSign -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetCreatedAt() time.Time { - if g == nil || g.CreatedAt == nil { - return time.Time{} - } - return *g.CreatedAt -} - -// GetExpiresAt returns the ExpiresAt field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetExpiresAt() time.Time { - if g == nil || g.ExpiresAt == nil { - return time.Time{} - } - return *g.ExpiresAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetID() int64 { - if g == nil || g.ID == nil { - return 0 - } - return *g.ID -} - -// GetKeyID returns the KeyID field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetKeyID() string { - if g == nil || g.KeyID == nil { - return "" - } - return *g.KeyID -} - -// GetPrimaryKeyID returns the PrimaryKeyID field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetPrimaryKeyID() int64 { - if g == nil || g.PrimaryKeyID == nil { - return 0 - } - return *g.PrimaryKeyID -} - -// GetPublicKey returns the PublicKey field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetPublicKey() string { - if g == nil || g.PublicKey == nil { - return "" - } - return *g.PublicKey -} - -// GetApp returns the App field. -func (g *Grant) GetApp() *AuthorizationApp { - if g == nil { - return nil - } - return g.App -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (g *Grant) GetCreatedAt() Timestamp { - if g == nil || g.CreatedAt == nil { - return Timestamp{} - } - return *g.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (g *Grant) GetID() int64 { - if g == nil || g.ID == nil { - return 0 - } - return *g.ID -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (g *Grant) GetUpdatedAt() Timestamp { - if g == nil || g.UpdatedAt == nil { - return Timestamp{} - } - return *g.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (g *Grant) GetURL() string { - if g == nil || g.URL == nil { - return "" - } - return *g.URL -} - -// GetActive returns the Active field if it's non-nil, zero value otherwise. -func (h *Hook) GetActive() bool { - if h == nil || h.Active == nil { - return false - } - return *h.Active -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (h *Hook) GetCreatedAt() time.Time { - if h == nil || h.CreatedAt == nil { - return time.Time{} - } - return *h.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (h *Hook) GetID() int64 { - if h == nil || h.ID == nil { - return 0 - } - return *h.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (h *Hook) GetName() string { - if h == nil || h.Name == nil { - return "" - } - return *h.Name -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (h *Hook) GetUpdatedAt() time.Time { - if h == nil || h.UpdatedAt == nil { - return time.Time{} - } - return *h.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (h *Hook) GetURL() string { - if h == nil || h.URL == nil { - return "" - } - return *h.URL -} - -// GetActiveHooks returns the ActiveHooks field if it's non-nil, zero value otherwise. -func (h *HookStats) GetActiveHooks() int { - if h == nil || h.ActiveHooks == nil { - return 0 - } - return *h.ActiveHooks -} - -// GetInactiveHooks returns the InactiveHooks field if it's non-nil, zero value otherwise. -func (h *HookStats) GetInactiveHooks() int { - if h == nil || h.InactiveHooks == nil { - return 0 - } - return *h.InactiveHooks -} - -// GetTotalHooks returns the TotalHooks field if it's non-nil, zero value otherwise. -func (h *HookStats) GetTotalHooks() int { - if h == nil || h.TotalHooks == nil { - return 0 - } - return *h.TotalHooks -} - -// GetAuthorsCount returns the AuthorsCount field if it's non-nil, zero value otherwise. -func (i *Import) GetAuthorsCount() int { - if i == nil || i.AuthorsCount == nil { - return 0 - } - return *i.AuthorsCount -} - -// GetAuthorsURL returns the AuthorsURL field if it's non-nil, zero value otherwise. -func (i *Import) GetAuthorsURL() string { - if i == nil || i.AuthorsURL == nil { - return "" - } - return *i.AuthorsURL -} - -// GetCommitCount returns the CommitCount field if it's non-nil, zero value otherwise. -func (i *Import) GetCommitCount() int { - if i == nil || i.CommitCount == nil { - return 0 - } - return *i.CommitCount -} - -// GetFailedStep returns the FailedStep field if it's non-nil, zero value otherwise. -func (i *Import) GetFailedStep() string { - if i == nil || i.FailedStep == nil { - return "" - } - return *i.FailedStep -} - -// GetHasLargeFiles returns the HasLargeFiles field if it's non-nil, zero value otherwise. -func (i *Import) GetHasLargeFiles() bool { - if i == nil || i.HasLargeFiles == nil { - return false - } - return *i.HasLargeFiles -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (i *Import) GetHTMLURL() string { - if i == nil || i.HTMLURL == nil { - return "" - } - return *i.HTMLURL -} - -// GetHumanName returns the HumanName field if it's non-nil, zero value otherwise. -func (i *Import) GetHumanName() string { - if i == nil || i.HumanName == nil { - return "" - } - return *i.HumanName -} - -// GetLargeFilesCount returns the LargeFilesCount field if it's non-nil, zero value otherwise. -func (i *Import) GetLargeFilesCount() int { - if i == nil || i.LargeFilesCount == nil { - return 0 - } - return *i.LargeFilesCount -} - -// GetLargeFilesSize returns the LargeFilesSize field if it's non-nil, zero value otherwise. -func (i *Import) GetLargeFilesSize() int { - if i == nil || i.LargeFilesSize == nil { - return 0 - } - return *i.LargeFilesSize -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (i *Import) GetMessage() string { - if i == nil || i.Message == nil { - return "" - } - return *i.Message -} - -// GetPercent returns the Percent field if it's non-nil, zero value otherwise. -func (i *Import) GetPercent() int { - if i == nil || i.Percent == nil { - return 0 - } - return *i.Percent -} - -// GetPushPercent returns the PushPercent field if it's non-nil, zero value otherwise. -func (i *Import) GetPushPercent() int { - if i == nil || i.PushPercent == nil { - return 0 - } - return *i.PushPercent -} - -// GetRepositoryURL returns the RepositoryURL field if it's non-nil, zero value otherwise. -func (i *Import) GetRepositoryURL() string { - if i == nil || i.RepositoryURL == nil { - return "" - } - return *i.RepositoryURL -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (i *Import) GetStatus() string { - if i == nil || i.Status == nil { - return "" - } - return *i.Status -} - -// GetStatusText returns the StatusText field if it's non-nil, zero value otherwise. -func (i *Import) GetStatusText() string { - if i == nil || i.StatusText == nil { - return "" - } - return *i.StatusText -} - -// GetTFVCProject returns the TFVCProject field if it's non-nil, zero value otherwise. -func (i *Import) GetTFVCProject() string { - if i == nil || i.TFVCProject == nil { - return "" - } - return *i.TFVCProject -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (i *Import) GetURL() string { - if i == nil || i.URL == nil { - return "" - } - return *i.URL -} - -// GetUseLFS returns the UseLFS field if it's non-nil, zero value otherwise. -func (i *Import) GetUseLFS() string { - if i == nil || i.UseLFS == nil { - return "" - } - return *i.UseLFS -} - -// GetVCS returns the VCS field if it's non-nil, zero value otherwise. -func (i *Import) GetVCS() string { - if i == nil || i.VCS == nil { - return "" - } - return *i.VCS -} - -// GetVCSPassword returns the VCSPassword field if it's non-nil, zero value otherwise. -func (i *Import) GetVCSPassword() string { - if i == nil || i.VCSPassword == nil { - return "" - } - return *i.VCSPassword -} - -// GetVCSURL returns the VCSURL field if it's non-nil, zero value otherwise. -func (i *Import) GetVCSURL() string { - if i == nil || i.VCSURL == nil { - return "" - } - return *i.VCSURL -} - -// GetVCSUsername returns the VCSUsername field if it's non-nil, zero value otherwise. -func (i *Import) GetVCSUsername() string { - if i == nil || i.VCSUsername == nil { - return "" - } - return *i.VCSUsername -} - -// GetAccessTokensURL returns the AccessTokensURL field if it's non-nil, zero value otherwise. -func (i *Installation) GetAccessTokensURL() string { - if i == nil || i.AccessTokensURL == nil { - return "" - } - return *i.AccessTokensURL -} - -// GetAccount returns the Account field. -func (i *Installation) GetAccount() *User { - if i == nil { - return nil - } - return i.Account -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (i *Installation) GetHTMLURL() string { - if i == nil || i.HTMLURL == nil { - return "" - } - return *i.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (i *Installation) GetID() int64 { - if i == nil || i.ID == nil { - return 0 - } - return *i.ID -} - -// GetRepositoriesURL returns the RepositoriesURL field if it's non-nil, zero value otherwise. -func (i *Installation) GetRepositoriesURL() string { - if i == nil || i.RepositoriesURL == nil { - return "" - } - return *i.RepositoriesURL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (i *InstallationEvent) GetAction() string { - if i == nil || i.Action == nil { - return "" - } - return *i.Action -} - -// GetInstallation returns the Installation field. -func (i *InstallationEvent) GetInstallation() *Installation { - if i == nil { - return nil - } - return i.Installation -} - -// GetSender returns the Sender field. -func (i *InstallationEvent) GetSender() *User { - if i == nil { - return nil - } - return i.Sender -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (i *InstallationRepositoriesEvent) GetAction() string { - if i == nil || i.Action == nil { - return "" - } - return *i.Action -} - -// GetInstallation returns the Installation field. -func (i *InstallationRepositoriesEvent) GetInstallation() *Installation { - if i == nil { - return nil - } - return i.Installation -} - -// GetRepositorySelection returns the RepositorySelection field if it's non-nil, zero value otherwise. -func (i *InstallationRepositoriesEvent) GetRepositorySelection() string { - if i == nil || i.RepositorySelection == nil { - return "" - } - return *i.RepositorySelection -} - -// GetSender returns the Sender field. -func (i *InstallationRepositoriesEvent) GetSender() *User { - if i == nil { - return nil - } - return i.Sender -} - -// GetExpiresAt returns the ExpiresAt field if it's non-nil, zero value otherwise. -func (i *InstallationToken) GetExpiresAt() time.Time { - if i == nil || i.ExpiresAt == nil { - return time.Time{} - } - return *i.ExpiresAt -} - -// GetToken returns the Token field if it's non-nil, zero value otherwise. -func (i *InstallationToken) GetToken() string { - if i == nil || i.Token == nil { - return "" - } - return *i.Token -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (i *Invitation) GetCreatedAt() time.Time { - if i == nil || i.CreatedAt == nil { - return time.Time{} - } - return *i.CreatedAt -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (i *Invitation) GetEmail() string { - if i == nil || i.Email == nil { - return "" - } - return *i.Email -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (i *Invitation) GetID() int64 { - if i == nil || i.ID == nil { - return 0 - } - return *i.ID -} - -// GetInviter returns the Inviter field. -func (i *Invitation) GetInviter() *User { - if i == nil { - return nil - } - return i.Inviter -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (i *Invitation) GetLogin() string { - if i == nil || i.Login == nil { - return "" - } - return *i.Login -} - -// GetRole returns the Role field if it's non-nil, zero value otherwise. -func (i *Invitation) GetRole() string { - if i == nil || i.Role == nil { - return "" - } - return *i.Role -} - -// GetAssignee returns the Assignee field. -func (i *Issue) GetAssignee() *User { - if i == nil { - return nil - } - return i.Assignee -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (i *Issue) GetBody() string { - if i == nil || i.Body == nil { - return "" - } - return *i.Body -} - -// GetClosedAt returns the ClosedAt field if it's non-nil, zero value otherwise. -func (i *Issue) GetClosedAt() time.Time { - if i == nil || i.ClosedAt == nil { - return time.Time{} - } - return *i.ClosedAt -} - -// GetClosedBy returns the ClosedBy field. -func (i *Issue) GetClosedBy() *User { - if i == nil { - return nil - } - return i.ClosedBy -} - -// GetComments returns the Comments field if it's non-nil, zero value otherwise. -func (i *Issue) GetComments() int { - if i == nil || i.Comments == nil { - return 0 - } - return *i.Comments -} - -// GetCommentsURL returns the CommentsURL field if it's non-nil, zero value otherwise. -func (i *Issue) GetCommentsURL() string { - if i == nil || i.CommentsURL == nil { - return "" - } - return *i.CommentsURL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (i *Issue) GetCreatedAt() time.Time { - if i == nil || i.CreatedAt == nil { - return time.Time{} - } - return *i.CreatedAt -} - -// GetEventsURL returns the EventsURL field if it's non-nil, zero value otherwise. -func (i *Issue) GetEventsURL() string { - if i == nil || i.EventsURL == nil { - return "" - } - return *i.EventsURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (i *Issue) GetHTMLURL() string { - if i == nil || i.HTMLURL == nil { - return "" - } - return *i.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (i *Issue) GetID() int64 { - if i == nil || i.ID == nil { - return 0 - } - return *i.ID -} - -// GetLabelsURL returns the LabelsURL field if it's non-nil, zero value otherwise. -func (i *Issue) GetLabelsURL() string { - if i == nil || i.LabelsURL == nil { - return "" - } - return *i.LabelsURL -} - -// GetLocked returns the Locked field if it's non-nil, zero value otherwise. -func (i *Issue) GetLocked() bool { - if i == nil || i.Locked == nil { - return false - } - return *i.Locked -} - -// GetMilestone returns the Milestone field. -func (i *Issue) GetMilestone() *Milestone { - if i == nil { - return nil - } - return i.Milestone -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (i *Issue) GetNodeID() string { - if i == nil || i.NodeID == nil { - return "" - } - return *i.NodeID -} - -// GetNumber returns the Number field if it's non-nil, zero value otherwise. -func (i *Issue) GetNumber() int { - if i == nil || i.Number == nil { - return 0 - } - return *i.Number -} - -// GetPullRequestLinks returns the PullRequestLinks field. -func (i *Issue) GetPullRequestLinks() *PullRequestLinks { - if i == nil { - return nil - } - return i.PullRequestLinks -} - -// GetReactions returns the Reactions field. -func (i *Issue) GetReactions() *Reactions { - if i == nil { - return nil - } - return i.Reactions -} - -// GetRepository returns the Repository field. -func (i *Issue) GetRepository() *Repository { - if i == nil { - return nil - } - return i.Repository -} - -// GetRepositoryURL returns the RepositoryURL field if it's non-nil, zero value otherwise. -func (i *Issue) GetRepositoryURL() string { - if i == nil || i.RepositoryURL == nil { - return "" - } - return *i.RepositoryURL -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (i *Issue) GetState() string { - if i == nil || i.State == nil { - return "" - } - return *i.State -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (i *Issue) GetTitle() string { - if i == nil || i.Title == nil { - return "" - } - return *i.Title -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (i *Issue) GetUpdatedAt() time.Time { - if i == nil || i.UpdatedAt == nil { - return time.Time{} - } - return *i.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (i *Issue) GetURL() string { - if i == nil || i.URL == nil { - return "" - } - return *i.URL -} - -// GetUser returns the User field. -func (i *Issue) GetUser() *User { - if i == nil { - return nil - } - return i.User -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetBody() string { - if i == nil || i.Body == nil { - return "" - } - return *i.Body -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetCreatedAt() time.Time { - if i == nil || i.CreatedAt == nil { - return time.Time{} - } - return *i.CreatedAt -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetHTMLURL() string { - if i == nil || i.HTMLURL == nil { - return "" - } - return *i.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetID() int64 { - if i == nil || i.ID == nil { - return 0 - } - return *i.ID -} - -// GetIssueURL returns the IssueURL field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetIssueURL() string { - if i == nil || i.IssueURL == nil { - return "" - } - return *i.IssueURL -} - -// GetReactions returns the Reactions field. -func (i *IssueComment) GetReactions() *Reactions { - if i == nil { - return nil - } - return i.Reactions -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetUpdatedAt() time.Time { - if i == nil || i.UpdatedAt == nil { - return time.Time{} - } - return *i.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetURL() string { - if i == nil || i.URL == nil { - return "" - } - return *i.URL -} - -// GetUser returns the User field. -func (i *IssueComment) GetUser() *User { - if i == nil { - return nil - } - return i.User -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (i *IssueCommentEvent) GetAction() string { - if i == nil || i.Action == nil { - return "" - } - return *i.Action -} - -// GetChanges returns the Changes field. -func (i *IssueCommentEvent) GetChanges() *EditChange { - if i == nil { - return nil - } - return i.Changes -} - -// GetComment returns the Comment field. -func (i *IssueCommentEvent) GetComment() *IssueComment { - if i == nil { - return nil - } - return i.Comment -} - -// GetInstallation returns the Installation field. -func (i *IssueCommentEvent) GetInstallation() *Installation { - if i == nil { - return nil - } - return i.Installation -} - -// GetIssue returns the Issue field. -func (i *IssueCommentEvent) GetIssue() *Issue { - if i == nil { - return nil - } - return i.Issue -} - -// GetRepo returns the Repo field. -func (i *IssueCommentEvent) GetRepo() *Repository { - if i == nil { - return nil - } - return i.Repo -} - -// GetSender returns the Sender field. -func (i *IssueCommentEvent) GetSender() *User { - if i == nil { - return nil - } - return i.Sender -} - -// GetActor returns the Actor field. -func (i *IssueEvent) GetActor() *User { - if i == nil { - return nil - } - return i.Actor -} - -// GetAssignee returns the Assignee field. -func (i *IssueEvent) GetAssignee() *User { - if i == nil { - return nil - } - return i.Assignee -} - -// GetAssigner returns the Assigner field. -func (i *IssueEvent) GetAssigner() *User { - if i == nil { - return nil - } - return i.Assigner -} - -// GetCommitID returns the CommitID field if it's non-nil, zero value otherwise. -func (i *IssueEvent) GetCommitID() string { - if i == nil || i.CommitID == nil { - return "" - } - return *i.CommitID -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (i *IssueEvent) GetCreatedAt() time.Time { - if i == nil || i.CreatedAt == nil { - return time.Time{} - } - return *i.CreatedAt -} - -// GetEvent returns the Event field if it's non-nil, zero value otherwise. -func (i *IssueEvent) GetEvent() string { - if i == nil || i.Event == nil { - return "" - } - return *i.Event -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (i *IssueEvent) GetID() int64 { - if i == nil || i.ID == nil { - return 0 - } - return *i.ID -} - -// GetIssue returns the Issue field. -func (i *IssueEvent) GetIssue() *Issue { - if i == nil { - return nil - } - return i.Issue -} - -// GetLabel returns the Label field. -func (i *IssueEvent) GetLabel() *Label { - if i == nil { - return nil - } - return i.Label -} - -// GetMilestone returns the Milestone field. -func (i *IssueEvent) GetMilestone() *Milestone { - if i == nil { - return nil - } - return i.Milestone -} - -// GetRename returns the Rename field. -func (i *IssueEvent) GetRename() *Rename { - if i == nil { - return nil - } - return i.Rename -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (i *IssueEvent) GetURL() string { - if i == nil || i.URL == nil { - return "" - } - return *i.URL -} - -// GetAssignee returns the Assignee field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetAssignee() string { - if i == nil || i.Assignee == nil { - return "" - } - return *i.Assignee -} - -// GetAssignees returns the Assignees field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetAssignees() []string { - if i == nil || i.Assignees == nil { - return nil - } - return *i.Assignees -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetBody() string { - if i == nil || i.Body == nil { - return "" - } - return *i.Body -} - -// GetLabels returns the Labels field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetLabels() []string { - if i == nil || i.Labels == nil { - return nil - } - return *i.Labels -} - -// GetMilestone returns the Milestone field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetMilestone() int { - if i == nil || i.Milestone == nil { - return 0 - } - return *i.Milestone -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetState() string { - if i == nil || i.State == nil { - return "" - } - return *i.State -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetTitle() string { - if i == nil || i.Title == nil { - return "" - } - return *i.Title -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (i *IssuesEvent) GetAction() string { - if i == nil || i.Action == nil { - return "" - } - return *i.Action -} - -// GetAssignee returns the Assignee field. -func (i *IssuesEvent) GetAssignee() *User { - if i == nil { - return nil - } - return i.Assignee -} - -// GetChanges returns the Changes field. -func (i *IssuesEvent) GetChanges() *EditChange { - if i == nil { - return nil - } - return i.Changes -} - -// GetInstallation returns the Installation field. -func (i *IssuesEvent) GetInstallation() *Installation { - if i == nil { - return nil - } - return i.Installation -} - -// GetIssue returns the Issue field. -func (i *IssuesEvent) GetIssue() *Issue { - if i == nil { - return nil - } - return i.Issue -} - -// GetLabel returns the Label field. -func (i *IssuesEvent) GetLabel() *Label { - if i == nil { - return nil - } - return i.Label -} - -// GetRepo returns the Repo field. -func (i *IssuesEvent) GetRepo() *Repository { - if i == nil { - return nil - } - return i.Repo -} - -// GetSender returns the Sender field. -func (i *IssuesEvent) GetSender() *User { - if i == nil { - return nil - } - return i.Sender -} - -// GetIncompleteResults returns the IncompleteResults field if it's non-nil, zero value otherwise. -func (i *IssuesSearchResult) GetIncompleteResults() bool { - if i == nil || i.IncompleteResults == nil { - return false - } - return *i.IncompleteResults -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (i *IssuesSearchResult) GetTotal() int { - if i == nil || i.Total == nil { - return 0 - } - return *i.Total -} - -// GetClosedIssues returns the ClosedIssues field if it's non-nil, zero value otherwise. -func (i *IssueStats) GetClosedIssues() int { - if i == nil || i.ClosedIssues == nil { - return 0 - } - return *i.ClosedIssues -} - -// GetOpenIssues returns the OpenIssues field if it's non-nil, zero value otherwise. -func (i *IssueStats) GetOpenIssues() int { - if i == nil || i.OpenIssues == nil { - return 0 - } - return *i.OpenIssues -} - -// GetTotalIssues returns the TotalIssues field if it's non-nil, zero value otherwise. -func (i *IssueStats) GetTotalIssues() int { - if i == nil || i.TotalIssues == nil { - return 0 - } - return *i.TotalIssues -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (k *Key) GetID() int64 { - if k == nil || k.ID == nil { - return 0 - } - return *k.ID -} - -// GetKey returns the Key field if it's non-nil, zero value otherwise. -func (k *Key) GetKey() string { - if k == nil || k.Key == nil { - return "" - } - return *k.Key -} - -// GetReadOnly returns the ReadOnly field if it's non-nil, zero value otherwise. -func (k *Key) GetReadOnly() bool { - if k == nil || k.ReadOnly == nil { - return false - } - return *k.ReadOnly -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (k *Key) GetTitle() string { - if k == nil || k.Title == nil { - return "" - } - return *k.Title -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (k *Key) GetURL() string { - if k == nil || k.URL == nil { - return "" - } - return *k.URL -} - -// GetColor returns the Color field if it's non-nil, zero value otherwise. -func (l *Label) GetColor() string { - if l == nil || l.Color == nil { - return "" - } - return *l.Color -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (l *Label) GetID() int64 { - if l == nil || l.ID == nil { - return 0 - } - return *l.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (l *Label) GetName() string { - if l == nil || l.Name == nil { - return "" - } - return *l.Name -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (l *Label) GetNodeID() string { - if l == nil || l.NodeID == nil { - return "" - } - return *l.NodeID -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (l *Label) GetURL() string { - if l == nil || l.URL == nil { - return "" - } - return *l.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (l *LabelEvent) GetAction() string { - if l == nil || l.Action == nil { - return "" - } - return *l.Action -} - -// GetChanges returns the Changes field. -func (l *LabelEvent) GetChanges() *EditChange { - if l == nil { - return nil - } - return l.Changes -} - -// GetInstallation returns the Installation field. -func (l *LabelEvent) GetInstallation() *Installation { - if l == nil { - return nil - } - return l.Installation -} - -// GetLabel returns the Label field. -func (l *LabelEvent) GetLabel() *Label { - if l == nil { - return nil - } - return l.Label -} - -// GetOrg returns the Org field. -func (l *LabelEvent) GetOrg() *Organization { - if l == nil { - return nil - } - return l.Org -} - -// GetRepo returns the Repo field. -func (l *LabelEvent) GetRepo() *Repository { - if l == nil { - return nil - } - return l.Repo -} - -// GetOID returns the OID field if it's non-nil, zero value otherwise. -func (l *LargeFile) GetOID() string { - if l == nil || l.OID == nil { - return "" - } - return *l.OID -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (l *LargeFile) GetPath() string { - if l == nil || l.Path == nil { - return "" - } - return *l.Path -} - -// GetRefName returns the RefName field if it's non-nil, zero value otherwise. -func (l *LargeFile) GetRefName() string { - if l == nil || l.RefName == nil { - return "" - } - return *l.RefName -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (l *LargeFile) GetSize() int { - if l == nil || l.Size == nil { - return 0 - } - return *l.Size -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (l *License) GetBody() string { - if l == nil || l.Body == nil { - return "" - } - return *l.Body -} - -// GetConditions returns the Conditions field if it's non-nil, zero value otherwise. -func (l *License) GetConditions() []string { - if l == nil || l.Conditions == nil { - return nil - } - return *l.Conditions -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (l *License) GetDescription() string { - if l == nil || l.Description == nil { - return "" - } - return *l.Description -} - -// GetFeatured returns the Featured field if it's non-nil, zero value otherwise. -func (l *License) GetFeatured() bool { - if l == nil || l.Featured == nil { - return false - } - return *l.Featured -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (l *License) GetHTMLURL() string { - if l == nil || l.HTMLURL == nil { - return "" - } - return *l.HTMLURL -} - -// GetImplementation returns the Implementation field if it's non-nil, zero value otherwise. -func (l *License) GetImplementation() string { - if l == nil || l.Implementation == nil { - return "" - } - return *l.Implementation -} - -// GetKey returns the Key field if it's non-nil, zero value otherwise. -func (l *License) GetKey() string { - if l == nil || l.Key == nil { - return "" - } - return *l.Key -} - -// GetLimitations returns the Limitations field if it's non-nil, zero value otherwise. -func (l *License) GetLimitations() []string { - if l == nil || l.Limitations == nil { - return nil - } - return *l.Limitations -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (l *License) GetName() string { - if l == nil || l.Name == nil { - return "" - } - return *l.Name -} - -// GetPermissions returns the Permissions field if it's non-nil, zero value otherwise. -func (l *License) GetPermissions() []string { - if l == nil || l.Permissions == nil { - return nil - } - return *l.Permissions -} - -// GetSPDXID returns the SPDXID field if it's non-nil, zero value otherwise. -func (l *License) GetSPDXID() string { - if l == nil || l.SPDXID == nil { - return "" - } - return *l.SPDXID -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (l *License) GetURL() string { - if l == nil || l.URL == nil { - return "" - } - return *l.URL -} - -// GetAccountsURL returns the AccountsURL field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetAccountsURL() string { - if m == nil || m.AccountsURL == nil { - return "" - } - return *m.AccountsURL -} - -// GetBullets returns the Bullets field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetBullets() []string { - if m == nil || m.Bullets == nil { - return nil - } - return *m.Bullets -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetDescription() string { - if m == nil || m.Description == nil { - return "" - } - return *m.Description -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetID() int64 { - if m == nil || m.ID == nil { - return 0 - } - return *m.ID -} - -// GetMonthlyPriceInCents returns the MonthlyPriceInCents field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetMonthlyPriceInCents() int { - if m == nil || m.MonthlyPriceInCents == nil { - return 0 - } - return *m.MonthlyPriceInCents -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetName() string { - if m == nil || m.Name == nil { - return "" - } - return *m.Name -} - -// GetPriceModel returns the PriceModel field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetPriceModel() string { - if m == nil || m.PriceModel == nil { - return "" - } - return *m.PriceModel -} - -// GetUnitName returns the UnitName field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetUnitName() string { - if m == nil || m.UnitName == nil { - return "" - } - return *m.UnitName -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetURL() string { - if m == nil || m.URL == nil { - return "" - } - return *m.URL -} - -// GetYearlyPriceInCents returns the YearlyPriceInCents field if it's non-nil, zero value otherwise. -func (m *MarketplacePlan) GetYearlyPriceInCents() int { - if m == nil || m.YearlyPriceInCents == nil { - return 0 - } - return *m.YearlyPriceInCents -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (m *MarketplacePlanAccount) GetEmail() string { - if m == nil || m.Email == nil { - return "" - } - return *m.Email -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (m *MarketplacePlanAccount) GetID() int64 { - if m == nil || m.ID == nil { - return 0 - } - return *m.ID -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (m *MarketplacePlanAccount) GetLogin() string { - if m == nil || m.Login == nil { - return "" - } - return *m.Login -} - -// GetMarketplacePurchase returns the MarketplacePurchase field. -func (m *MarketplacePlanAccount) GetMarketplacePurchase() *MarketplacePurchase { - if m == nil { - return nil - } - return m.MarketplacePurchase -} - -// GetOrganizationBillingEmail returns the OrganizationBillingEmail field if it's non-nil, zero value otherwise. -func (m *MarketplacePlanAccount) GetOrganizationBillingEmail() string { - if m == nil || m.OrganizationBillingEmail == nil { - return "" - } - return *m.OrganizationBillingEmail -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (m *MarketplacePlanAccount) GetType() string { - if m == nil || m.Type == nil { - return "" - } - return *m.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (m *MarketplacePlanAccount) GetURL() string { - if m == nil || m.URL == nil { - return "" - } - return *m.URL -} - -// GetAccount returns the Account field. -func (m *MarketplacePurchase) GetAccount() *MarketplacePlanAccount { - if m == nil { - return nil - } - return m.Account -} - -// GetBillingCycle returns the BillingCycle field if it's non-nil, zero value otherwise. -func (m *MarketplacePurchase) GetBillingCycle() string { - if m == nil || m.BillingCycle == nil { - return "" - } - return *m.BillingCycle -} - -// GetNextBillingDate returns the NextBillingDate field if it's non-nil, zero value otherwise. -func (m *MarketplacePurchase) GetNextBillingDate() string { - if m == nil || m.NextBillingDate == nil { - return "" - } - return *m.NextBillingDate -} - -// GetPlan returns the Plan field. -func (m *MarketplacePurchase) GetPlan() *MarketplacePlan { - if m == nil { - return nil - } - return m.Plan -} - -// GetUnitCount returns the UnitCount field if it's non-nil, zero value otherwise. -func (m *MarketplacePurchase) GetUnitCount() int { - if m == nil || m.UnitCount == nil { - return 0 - } - return *m.UnitCount -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (m *MarketplacePurchaseEvent) GetAction() string { - if m == nil || m.Action == nil { - return "" - } - return *m.Action -} - -// GetEffectiveDate returns the EffectiveDate field if it's non-nil, zero value otherwise. -func (m *MarketplacePurchaseEvent) GetEffectiveDate() Timestamp { - if m == nil || m.EffectiveDate == nil { - return Timestamp{} - } - return *m.EffectiveDate -} - -// GetInstallation returns the Installation field. -func (m *MarketplacePurchaseEvent) GetInstallation() *Installation { - if m == nil { - return nil - } - return m.Installation -} - -// GetMarketplacePurchase returns the MarketplacePurchase field. -func (m *MarketplacePurchaseEvent) GetMarketplacePurchase() *MarketplacePurchase { - if m == nil { - return nil - } - return m.MarketplacePurchase -} - -// GetPreviousMarketplacePurchase returns the PreviousMarketplacePurchase field. -func (m *MarketplacePurchaseEvent) GetPreviousMarketplacePurchase() *MarketplacePurchase { - if m == nil { - return nil - } - return m.PreviousMarketplacePurchase -} - -// GetSender returns the Sender field. -func (m *MarketplacePurchaseEvent) GetSender() *User { - if m == nil { - return nil - } - return m.Sender -} - -// GetText returns the Text field if it's non-nil, zero value otherwise. -func (m *Match) GetText() string { - if m == nil || m.Text == nil { - return "" - } - return *m.Text -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (m *MemberEvent) GetAction() string { - if m == nil || m.Action == nil { - return "" - } - return *m.Action -} - -// GetInstallation returns the Installation field. -func (m *MemberEvent) GetInstallation() *Installation { - if m == nil { - return nil - } - return m.Installation -} - -// GetMember returns the Member field. -func (m *MemberEvent) GetMember() *User { - if m == nil { - return nil - } - return m.Member -} - -// GetRepo returns the Repo field. -func (m *MemberEvent) GetRepo() *Repository { - if m == nil { - return nil - } - return m.Repo -} - -// GetSender returns the Sender field. -func (m *MemberEvent) GetSender() *User { - if m == nil { - return nil - } - return m.Sender -} - -// GetOrganization returns the Organization field. -func (m *Membership) GetOrganization() *Organization { - if m == nil { - return nil - } - return m.Organization -} - -// GetOrganizationURL returns the OrganizationURL field if it's non-nil, zero value otherwise. -func (m *Membership) GetOrganizationURL() string { - if m == nil || m.OrganizationURL == nil { - return "" - } - return *m.OrganizationURL -} - -// GetRole returns the Role field if it's non-nil, zero value otherwise. -func (m *Membership) GetRole() string { - if m == nil || m.Role == nil { - return "" - } - return *m.Role -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (m *Membership) GetState() string { - if m == nil || m.State == nil { - return "" - } - return *m.State -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (m *Membership) GetURL() string { - if m == nil || m.URL == nil { - return "" - } - return *m.URL -} - -// GetUser returns the User field. -func (m *Membership) GetUser() *User { - if m == nil { - return nil - } - return m.User -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (m *MembershipEvent) GetAction() string { - if m == nil || m.Action == nil { - return "" - } - return *m.Action -} - -// GetInstallation returns the Installation field. -func (m *MembershipEvent) GetInstallation() *Installation { - if m == nil { - return nil - } - return m.Installation -} - -// GetMember returns the Member field. -func (m *MembershipEvent) GetMember() *User { - if m == nil { - return nil - } - return m.Member -} - -// GetOrg returns the Org field. -func (m *MembershipEvent) GetOrg() *Organization { - if m == nil { - return nil - } - return m.Org -} - -// GetScope returns the Scope field if it's non-nil, zero value otherwise. -func (m *MembershipEvent) GetScope() string { - if m == nil || m.Scope == nil { - return "" - } - return *m.Scope -} - -// GetSender returns the Sender field. -func (m *MembershipEvent) GetSender() *User { - if m == nil { - return nil - } - return m.Sender -} - -// GetTeam returns the Team field. -func (m *MembershipEvent) GetTeam() *Team { - if m == nil { - return nil - } - return m.Team -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (m *Metric) GetHTMLURL() string { - if m == nil || m.HTMLURL == nil { - return "" - } - return *m.HTMLURL -} - -// GetKey returns the Key field if it's non-nil, zero value otherwise. -func (m *Metric) GetKey() string { - if m == nil || m.Key == nil { - return "" - } - return *m.Key -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (m *Metric) GetName() string { - if m == nil || m.Name == nil { - return "" - } - return *m.Name -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (m *Metric) GetURL() string { - if m == nil || m.URL == nil { - return "" - } - return *m.URL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (m *Migration) GetCreatedAt() string { - if m == nil || m.CreatedAt == nil { - return "" - } - return *m.CreatedAt -} - -// GetExcludeAttachments returns the ExcludeAttachments field if it's non-nil, zero value otherwise. -func (m *Migration) GetExcludeAttachments() bool { - if m == nil || m.ExcludeAttachments == nil { - return false - } - return *m.ExcludeAttachments -} - -// GetGUID returns the GUID field if it's non-nil, zero value otherwise. -func (m *Migration) GetGUID() string { - if m == nil || m.GUID == nil { - return "" - } - return *m.GUID -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (m *Migration) GetID() int64 { - if m == nil || m.ID == nil { - return 0 - } - return *m.ID -} - -// GetLockRepositories returns the LockRepositories field if it's non-nil, zero value otherwise. -func (m *Migration) GetLockRepositories() bool { - if m == nil || m.LockRepositories == nil { - return false - } - return *m.LockRepositories -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (m *Migration) GetState() string { - if m == nil || m.State == nil { - return "" - } - return *m.State -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (m *Migration) GetUpdatedAt() string { - if m == nil || m.UpdatedAt == nil { - return "" - } - return *m.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (m *Migration) GetURL() string { - if m == nil || m.URL == nil { - return "" - } - return *m.URL -} - -// GetClosedAt returns the ClosedAt field if it's non-nil, zero value otherwise. -func (m *Milestone) GetClosedAt() time.Time { - if m == nil || m.ClosedAt == nil { - return time.Time{} - } - return *m.ClosedAt -} - -// GetClosedIssues returns the ClosedIssues field if it's non-nil, zero value otherwise. -func (m *Milestone) GetClosedIssues() int { - if m == nil || m.ClosedIssues == nil { - return 0 - } - return *m.ClosedIssues -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (m *Milestone) GetCreatedAt() time.Time { - if m == nil || m.CreatedAt == nil { - return time.Time{} - } - return *m.CreatedAt -} - -// GetCreator returns the Creator field. -func (m *Milestone) GetCreator() *User { - if m == nil { - return nil - } - return m.Creator -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (m *Milestone) GetDescription() string { - if m == nil || m.Description == nil { - return "" - } - return *m.Description -} - -// GetDueOn returns the DueOn field if it's non-nil, zero value otherwise. -func (m *Milestone) GetDueOn() time.Time { - if m == nil || m.DueOn == nil { - return time.Time{} - } - return *m.DueOn -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (m *Milestone) GetHTMLURL() string { - if m == nil || m.HTMLURL == nil { - return "" - } - return *m.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (m *Milestone) GetID() int64 { - if m == nil || m.ID == nil { - return 0 - } - return *m.ID -} - -// GetLabelsURL returns the LabelsURL field if it's non-nil, zero value otherwise. -func (m *Milestone) GetLabelsURL() string { - if m == nil || m.LabelsURL == nil { - return "" - } - return *m.LabelsURL -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (m *Milestone) GetNodeID() string { - if m == nil || m.NodeID == nil { - return "" - } - return *m.NodeID -} - -// GetNumber returns the Number field if it's non-nil, zero value otherwise. -func (m *Milestone) GetNumber() int { - if m == nil || m.Number == nil { - return 0 - } - return *m.Number -} - -// GetOpenIssues returns the OpenIssues field if it's non-nil, zero value otherwise. -func (m *Milestone) GetOpenIssues() int { - if m == nil || m.OpenIssues == nil { - return 0 - } - return *m.OpenIssues -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (m *Milestone) GetState() string { - if m == nil || m.State == nil { - return "" - } - return *m.State -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (m *Milestone) GetTitle() string { - if m == nil || m.Title == nil { - return "" - } - return *m.Title -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (m *Milestone) GetUpdatedAt() time.Time { - if m == nil || m.UpdatedAt == nil { - return time.Time{} - } - return *m.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (m *Milestone) GetURL() string { - if m == nil || m.URL == nil { - return "" - } - return *m.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (m *MilestoneEvent) GetAction() string { - if m == nil || m.Action == nil { - return "" - } - return *m.Action -} - -// GetChanges returns the Changes field. -func (m *MilestoneEvent) GetChanges() *EditChange { - if m == nil { - return nil - } - return m.Changes -} - -// GetInstallation returns the Installation field. -func (m *MilestoneEvent) GetInstallation() *Installation { - if m == nil { - return nil - } - return m.Installation -} - -// GetMilestone returns the Milestone field. -func (m *MilestoneEvent) GetMilestone() *Milestone { - if m == nil { - return nil - } - return m.Milestone -} - -// GetOrg returns the Org field. -func (m *MilestoneEvent) GetOrg() *Organization { - if m == nil { - return nil - } - return m.Org -} - -// GetRepo returns the Repo field. -func (m *MilestoneEvent) GetRepo() *Repository { - if m == nil { - return nil - } - return m.Repo -} - -// GetSender returns the Sender field. -func (m *MilestoneEvent) GetSender() *User { - if m == nil { - return nil - } - return m.Sender -} - -// GetClosedMilestones returns the ClosedMilestones field if it's non-nil, zero value otherwise. -func (m *MilestoneStats) GetClosedMilestones() int { - if m == nil || m.ClosedMilestones == nil { - return 0 - } - return *m.ClosedMilestones -} - -// GetOpenMilestones returns the OpenMilestones field if it's non-nil, zero value otherwise. -func (m *MilestoneStats) GetOpenMilestones() int { - if m == nil || m.OpenMilestones == nil { - return 0 - } - return *m.OpenMilestones -} - -// GetTotalMilestones returns the TotalMilestones field if it's non-nil, zero value otherwise. -func (m *MilestoneStats) GetTotalMilestones() int { - if m == nil || m.TotalMilestones == nil { - return 0 - } - return *m.TotalMilestones -} - -// GetBase returns the Base field if it's non-nil, zero value otherwise. -func (n *NewPullRequest) GetBase() string { - if n == nil || n.Base == nil { - return "" - } - return *n.Base -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (n *NewPullRequest) GetBody() string { - if n == nil || n.Body == nil { - return "" - } - return *n.Body -} - -// GetHead returns the Head field if it's non-nil, zero value otherwise. -func (n *NewPullRequest) GetHead() string { - if n == nil || n.Head == nil { - return "" - } - return *n.Head -} - -// GetIssue returns the Issue field if it's non-nil, zero value otherwise. -func (n *NewPullRequest) GetIssue() int { - if n == nil || n.Issue == nil { - return 0 - } - return *n.Issue -} - -// GetMaintainerCanModify returns the MaintainerCanModify field if it's non-nil, zero value otherwise. -func (n *NewPullRequest) GetMaintainerCanModify() bool { - if n == nil || n.MaintainerCanModify == nil { - return false - } - return *n.MaintainerCanModify -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (n *NewPullRequest) GetTitle() string { - if n == nil || n.Title == nil { - return "" - } - return *n.Title -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (n *NewTeam) GetDescription() string { - if n == nil || n.Description == nil { - return "" - } - return *n.Description -} - -// GetLDAPDN returns the LDAPDN field if it's non-nil, zero value otherwise. -func (n *NewTeam) GetLDAPDN() string { - if n == nil || n.LDAPDN == nil { - return "" - } - return *n.LDAPDN -} - -// GetParentTeamID returns the ParentTeamID field if it's non-nil, zero value otherwise. -func (n *NewTeam) GetParentTeamID() int64 { - if n == nil || n.ParentTeamID == nil { - return 0 - } - return *n.ParentTeamID -} - -// GetPermission returns the Permission field if it's non-nil, zero value otherwise. -func (n *NewTeam) GetPermission() string { - if n == nil || n.Permission == nil { - return "" - } - return *n.Permission -} - -// GetPrivacy returns the Privacy field if it's non-nil, zero value otherwise. -func (n *NewTeam) GetPrivacy() string { - if n == nil || n.Privacy == nil { - return "" - } - return *n.Privacy -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (n *Notification) GetID() string { - if n == nil || n.ID == nil { - return "" - } - return *n.ID -} - -// GetLastReadAt returns the LastReadAt field if it's non-nil, zero value otherwise. -func (n *Notification) GetLastReadAt() time.Time { - if n == nil || n.LastReadAt == nil { - return time.Time{} - } - return *n.LastReadAt -} - -// GetReason returns the Reason field if it's non-nil, zero value otherwise. -func (n *Notification) GetReason() string { - if n == nil || n.Reason == nil { - return "" - } - return *n.Reason -} - -// GetRepository returns the Repository field. -func (n *Notification) GetRepository() *Repository { - if n == nil { - return nil - } - return n.Repository -} - -// GetSubject returns the Subject field. -func (n *Notification) GetSubject() *NotificationSubject { - if n == nil { - return nil - } - return n.Subject -} - -// GetUnread returns the Unread field if it's non-nil, zero value otherwise. -func (n *Notification) GetUnread() bool { - if n == nil || n.Unread == nil { - return false - } - return *n.Unread -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (n *Notification) GetUpdatedAt() time.Time { - if n == nil || n.UpdatedAt == nil { - return time.Time{} - } - return *n.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (n *Notification) GetURL() string { - if n == nil || n.URL == nil { - return "" - } - return *n.URL -} - -// GetLatestCommentURL returns the LatestCommentURL field if it's non-nil, zero value otherwise. -func (n *NotificationSubject) GetLatestCommentURL() string { - if n == nil || n.LatestCommentURL == nil { - return "" - } - return *n.LatestCommentURL -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (n *NotificationSubject) GetTitle() string { - if n == nil || n.Title == nil { - return "" - } - return *n.Title -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (n *NotificationSubject) GetType() string { - if n == nil || n.Type == nil { - return "" - } - return *n.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (n *NotificationSubject) GetURL() string { - if n == nil || n.URL == nil { - return "" - } - return *n.URL -} - -// GetAvatarURL returns the AvatarURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetAvatarURL() string { - if o == nil || o.AvatarURL == nil { - return "" - } - return *o.AvatarURL -} - -// GetBillingEmail returns the BillingEmail field if it's non-nil, zero value otherwise. -func (o *Organization) GetBillingEmail() string { - if o == nil || o.BillingEmail == nil { - return "" - } - return *o.BillingEmail -} - -// GetBlog returns the Blog field if it's non-nil, zero value otherwise. -func (o *Organization) GetBlog() string { - if o == nil || o.Blog == nil { - return "" - } - return *o.Blog -} - -// GetCollaborators returns the Collaborators field if it's non-nil, zero value otherwise. -func (o *Organization) GetCollaborators() int { - if o == nil || o.Collaborators == nil { - return 0 - } - return *o.Collaborators -} - -// GetCompany returns the Company field if it's non-nil, zero value otherwise. -func (o *Organization) GetCompany() string { - if o == nil || o.Company == nil { - return "" - } - return *o.Company -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (o *Organization) GetCreatedAt() time.Time { - if o == nil || o.CreatedAt == nil { - return time.Time{} - } - return *o.CreatedAt -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (o *Organization) GetDescription() string { - if o == nil || o.Description == nil { - return "" - } - return *o.Description -} - -// GetDiskUsage returns the DiskUsage field if it's non-nil, zero value otherwise. -func (o *Organization) GetDiskUsage() int { - if o == nil || o.DiskUsage == nil { - return 0 - } - return *o.DiskUsage -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (o *Organization) GetEmail() string { - if o == nil || o.Email == nil { - return "" - } - return *o.Email -} - -// GetEventsURL returns the EventsURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetEventsURL() string { - if o == nil || o.EventsURL == nil { - return "" - } - return *o.EventsURL -} - -// GetFollowers returns the Followers field if it's non-nil, zero value otherwise. -func (o *Organization) GetFollowers() int { - if o == nil || o.Followers == nil { - return 0 - } - return *o.Followers -} - -// GetFollowing returns the Following field if it's non-nil, zero value otherwise. -func (o *Organization) GetFollowing() int { - if o == nil || o.Following == nil { - return 0 - } - return *o.Following -} - -// GetHooksURL returns the HooksURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetHooksURL() string { - if o == nil || o.HooksURL == nil { - return "" - } - return *o.HooksURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetHTMLURL() string { - if o == nil || o.HTMLURL == nil { - return "" - } - return *o.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (o *Organization) GetID() int64 { - if o == nil || o.ID == nil { - return 0 - } - return *o.ID -} - -// GetIssuesURL returns the IssuesURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetIssuesURL() string { - if o == nil || o.IssuesURL == nil { - return "" - } - return *o.IssuesURL -} - -// GetLocation returns the Location field if it's non-nil, zero value otherwise. -func (o *Organization) GetLocation() string { - if o == nil || o.Location == nil { - return "" - } - return *o.Location -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (o *Organization) GetLogin() string { - if o == nil || o.Login == nil { - return "" - } - return *o.Login -} - -// GetMembersURL returns the MembersURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetMembersURL() string { - if o == nil || o.MembersURL == nil { - return "" - } - return *o.MembersURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (o *Organization) GetName() string { - if o == nil || o.Name == nil { - return "" - } - return *o.Name -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (o *Organization) GetNodeID() string { - if o == nil || o.NodeID == nil { - return "" - } - return *o.NodeID -} - -// GetOwnedPrivateRepos returns the OwnedPrivateRepos field if it's non-nil, zero value otherwise. -func (o *Organization) GetOwnedPrivateRepos() int { - if o == nil || o.OwnedPrivateRepos == nil { - return 0 - } - return *o.OwnedPrivateRepos -} - -// GetPlan returns the Plan field. -func (o *Organization) GetPlan() *Plan { - if o == nil { - return nil - } - return o.Plan -} - -// GetPrivateGists returns the PrivateGists field if it's non-nil, zero value otherwise. -func (o *Organization) GetPrivateGists() int { - if o == nil || o.PrivateGists == nil { - return 0 - } - return *o.PrivateGists -} - -// GetPublicGists returns the PublicGists field if it's non-nil, zero value otherwise. -func (o *Organization) GetPublicGists() int { - if o == nil || o.PublicGists == nil { - return 0 - } - return *o.PublicGists -} - -// GetPublicMembersURL returns the PublicMembersURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetPublicMembersURL() string { - if o == nil || o.PublicMembersURL == nil { - return "" - } - return *o.PublicMembersURL -} - -// GetPublicRepos returns the PublicRepos field if it's non-nil, zero value otherwise. -func (o *Organization) GetPublicRepos() int { - if o == nil || o.PublicRepos == nil { - return 0 - } - return *o.PublicRepos -} - -// GetReposURL returns the ReposURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetReposURL() string { - if o == nil || o.ReposURL == nil { - return "" - } - return *o.ReposURL -} - -// GetTotalPrivateRepos returns the TotalPrivateRepos field if it's non-nil, zero value otherwise. -func (o *Organization) GetTotalPrivateRepos() int { - if o == nil || o.TotalPrivateRepos == nil { - return 0 - } - return *o.TotalPrivateRepos -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (o *Organization) GetType() string { - if o == nil || o.Type == nil { - return "" - } - return *o.Type -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (o *Organization) GetUpdatedAt() time.Time { - if o == nil || o.UpdatedAt == nil { - return time.Time{} - } - return *o.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (o *Organization) GetURL() string { - if o == nil || o.URL == nil { - return "" - } - return *o.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (o *OrganizationEvent) GetAction() string { - if o == nil || o.Action == nil { - return "" - } - return *o.Action -} - -// GetInstallation returns the Installation field. -func (o *OrganizationEvent) GetInstallation() *Installation { - if o == nil { - return nil - } - return o.Installation -} - -// GetInvitation returns the Invitation field. -func (o *OrganizationEvent) GetInvitation() *Invitation { - if o == nil { - return nil - } - return o.Invitation -} - -// GetMembership returns the Membership field. -func (o *OrganizationEvent) GetMembership() *Membership { - if o == nil { - return nil - } - return o.Membership -} - -// GetOrganization returns the Organization field. -func (o *OrganizationEvent) GetOrganization() *Organization { - if o == nil { - return nil - } - return o.Organization -} - -// GetSender returns the Sender field. -func (o *OrganizationEvent) GetSender() *User { - if o == nil { - return nil - } - return o.Sender -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (o *OrgBlockEvent) GetAction() string { - if o == nil || o.Action == nil { - return "" - } - return *o.Action -} - -// GetBlockedUser returns the BlockedUser field. -func (o *OrgBlockEvent) GetBlockedUser() *User { - if o == nil { - return nil - } - return o.BlockedUser -} - -// GetInstallation returns the Installation field. -func (o *OrgBlockEvent) GetInstallation() *Installation { - if o == nil { - return nil - } - return o.Installation -} - -// GetOrganization returns the Organization field. -func (o *OrgBlockEvent) GetOrganization() *Organization { - if o == nil { - return nil - } - return o.Organization -} - -// GetSender returns the Sender field. -func (o *OrgBlockEvent) GetSender() *User { - if o == nil { - return nil - } - return o.Sender -} - -// GetDisabledOrgs returns the DisabledOrgs field if it's non-nil, zero value otherwise. -func (o *OrgStats) GetDisabledOrgs() int { - if o == nil || o.DisabledOrgs == nil { - return 0 - } - return *o.DisabledOrgs -} - -// GetTotalOrgs returns the TotalOrgs field if it's non-nil, zero value otherwise. -func (o *OrgStats) GetTotalOrgs() int { - if o == nil || o.TotalOrgs == nil { - return 0 - } - return *o.TotalOrgs -} - -// GetTotalTeamMembers returns the TotalTeamMembers field if it's non-nil, zero value otherwise. -func (o *OrgStats) GetTotalTeamMembers() int { - if o == nil || o.TotalTeamMembers == nil { - return 0 - } - return *o.TotalTeamMembers -} - -// GetTotalTeams returns the TotalTeams field if it's non-nil, zero value otherwise. -func (o *OrgStats) GetTotalTeams() int { - if o == nil || o.TotalTeams == nil { - return 0 - } - return *o.TotalTeams -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *Page) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *Page) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetPageName returns the PageName field if it's non-nil, zero value otherwise. -func (p *Page) GetPageName() string { - if p == nil || p.PageName == nil { - return "" - } - return *p.PageName -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (p *Page) GetSHA() string { - if p == nil || p.SHA == nil { - return "" - } - return *p.SHA -} - -// GetSummary returns the Summary field if it's non-nil, zero value otherwise. -func (p *Page) GetSummary() string { - if p == nil || p.Summary == nil { - return "" - } - return *p.Summary -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (p *Page) GetTitle() string { - if p == nil || p.Title == nil { - return "" - } - return *p.Title -} - -// GetBuild returns the Build field. -func (p *PageBuildEvent) GetBuild() *PagesBuild { - if p == nil { - return nil - } - return p.Build -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *PageBuildEvent) GetID() int64 { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetInstallation returns the Installation field. -func (p *PageBuildEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetRepo returns the Repo field. -func (p *PageBuildEvent) GetRepo() *Repository { - if p == nil { - return nil - } - return p.Repo -} - -// GetSender returns the Sender field. -func (p *PageBuildEvent) GetSender() *User { - if p == nil { - return nil - } - return p.Sender -} - -// GetCNAME returns the CNAME field if it's non-nil, zero value otherwise. -func (p *Pages) GetCNAME() string { - if p == nil || p.CNAME == nil { - return "" - } - return *p.CNAME -} - -// GetCustom404 returns the Custom404 field if it's non-nil, zero value otherwise. -func (p *Pages) GetCustom404() bool { - if p == nil || p.Custom404 == nil { - return false - } - return *p.Custom404 -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *Pages) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (p *Pages) GetStatus() string { - if p == nil || p.Status == nil { - return "" - } - return *p.Status -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *Pages) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetCommit returns the Commit field if it's non-nil, zero value otherwise. -func (p *PagesBuild) GetCommit() string { - if p == nil || p.Commit == nil { - return "" - } - return *p.Commit -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *PagesBuild) GetCreatedAt() Timestamp { - if p == nil || p.CreatedAt == nil { - return Timestamp{} - } - return *p.CreatedAt -} - -// GetDuration returns the Duration field if it's non-nil, zero value otherwise. -func (p *PagesBuild) GetDuration() int { - if p == nil || p.Duration == nil { - return 0 - } - return *p.Duration -} - -// GetError returns the Error field. -func (p *PagesBuild) GetError() *PagesError { - if p == nil { - return nil - } - return p.Error -} - -// GetPusher returns the Pusher field. -func (p *PagesBuild) GetPusher() *User { - if p == nil { - return nil - } - return p.Pusher -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (p *PagesBuild) GetStatus() string { - if p == nil || p.Status == nil { - return "" - } - return *p.Status -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *PagesBuild) GetUpdatedAt() Timestamp { - if p == nil || p.UpdatedAt == nil { - return Timestamp{} - } - return *p.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *PagesBuild) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (p *PagesError) GetMessage() string { - if p == nil || p.Message == nil { - return "" - } - return *p.Message -} - -// GetTotalPages returns the TotalPages field if it's non-nil, zero value otherwise. -func (p *PageStats) GetTotalPages() int { - if p == nil || p.TotalPages == nil { - return 0 - } - return *p.TotalPages -} - -// GetHook returns the Hook field. -func (p *PingEvent) GetHook() *Hook { - if p == nil { - return nil - } - return p.Hook -} - -// GetHookID returns the HookID field if it's non-nil, zero value otherwise. -func (p *PingEvent) GetHookID() int64 { - if p == nil || p.HookID == nil { - return 0 - } - return *p.HookID -} - -// GetInstallation returns the Installation field. -func (p *PingEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetZen returns the Zen field if it's non-nil, zero value otherwise. -func (p *PingEvent) GetZen() string { - if p == nil || p.Zen == nil { - return "" - } - return *p.Zen -} - -// GetCollaborators returns the Collaborators field if it's non-nil, zero value otherwise. -func (p *Plan) GetCollaborators() int { - if p == nil || p.Collaborators == nil { - return 0 - } - return *p.Collaborators -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (p *Plan) GetName() string { - if p == nil || p.Name == nil { - return "" - } - return *p.Name -} - -// GetPrivateRepos returns the PrivateRepos field if it's non-nil, zero value otherwise. -func (p *Plan) GetPrivateRepos() int { - if p == nil || p.PrivateRepos == nil { - return 0 - } - return *p.PrivateRepos -} - -// GetSpace returns the Space field if it's non-nil, zero value otherwise. -func (p *Plan) GetSpace() int { - if p == nil || p.Space == nil { - return 0 - } - return *p.Space -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (p *Project) GetBody() string { - if p == nil || p.Body == nil { - return "" - } - return *p.Body -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *Project) GetCreatedAt() Timestamp { - if p == nil || p.CreatedAt == nil { - return Timestamp{} - } - return *p.CreatedAt -} - -// GetCreator returns the Creator field. -func (p *Project) GetCreator() *User { - if p == nil { - return nil - } - return p.Creator -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *Project) GetID() int64 { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (p *Project) GetName() string { - if p == nil || p.Name == nil { - return "" - } - return *p.Name -} - -// GetNumber returns the Number field if it's non-nil, zero value otherwise. -func (p *Project) GetNumber() int { - if p == nil || p.Number == nil { - return 0 - } - return *p.Number -} - -// GetOwnerURL returns the OwnerURL field if it's non-nil, zero value otherwise. -func (p *Project) GetOwnerURL() string { - if p == nil || p.OwnerURL == nil { - return "" - } - return *p.OwnerURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *Project) GetUpdatedAt() Timestamp { - if p == nil || p.UpdatedAt == nil { - return Timestamp{} - } - return *p.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *Project) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetColumnID returns the ColumnID field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetColumnID() int64 { - if p == nil || p.ColumnID == nil { - return 0 - } - return *p.ColumnID -} - -// GetColumnURL returns the ColumnURL field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetColumnURL() string { - if p == nil || p.ColumnURL == nil { - return "" - } - return *p.ColumnURL -} - -// GetContentURL returns the ContentURL field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetContentURL() string { - if p == nil || p.ContentURL == nil { - return "" - } - return *p.ContentURL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetCreatedAt() Timestamp { - if p == nil || p.CreatedAt == nil { - return Timestamp{} - } - return *p.CreatedAt -} - -// GetCreator returns the Creator field. -func (p *ProjectCard) GetCreator() *User { - if p == nil { - return nil - } - return p.Creator -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetID() int64 { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetNote returns the Note field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetNote() string { - if p == nil || p.Note == nil { - return "" - } - return *p.Note -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetUpdatedAt() Timestamp { - if p == nil || p.UpdatedAt == nil { - return Timestamp{} - } - return *p.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *ProjectCardEvent) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetAfterID returns the AfterID field if it's non-nil, zero value otherwise. -func (p *ProjectCardEvent) GetAfterID() int64 { - if p == nil || p.AfterID == nil { - return 0 - } - return *p.AfterID -} - -// GetChanges returns the Changes field. -func (p *ProjectCardEvent) GetChanges() *ProjectCardChange { - if p == nil { - return nil - } - return p.Changes -} - -// GetInstallation returns the Installation field. -func (p *ProjectCardEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetOrg returns the Org field. -func (p *ProjectCardEvent) GetOrg() *Organization { - if p == nil { - return nil - } - return p.Org -} - -// GetProjectCard returns the ProjectCard field. -func (p *ProjectCardEvent) GetProjectCard() *ProjectCard { - if p == nil { - return nil - } - return p.ProjectCard -} - -// GetRepo returns the Repo field. -func (p *ProjectCardEvent) GetRepo() *Repository { - if p == nil { - return nil - } - return p.Repo -} - -// GetSender returns the Sender field. -func (p *ProjectCardEvent) GetSender() *User { - if p == nil { - return nil - } - return p.Sender -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *ProjectColumn) GetCreatedAt() Timestamp { - if p == nil || p.CreatedAt == nil { - return Timestamp{} - } - return *p.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *ProjectColumn) GetID() int64 { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (p *ProjectColumn) GetName() string { - if p == nil || p.Name == nil { - return "" - } - return *p.Name -} - -// GetProjectURL returns the ProjectURL field if it's non-nil, zero value otherwise. -func (p *ProjectColumn) GetProjectURL() string { - if p == nil || p.ProjectURL == nil { - return "" - } - return *p.ProjectURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *ProjectColumn) GetUpdatedAt() Timestamp { - if p == nil || p.UpdatedAt == nil { - return Timestamp{} - } - return *p.UpdatedAt -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *ProjectColumnEvent) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetAfterID returns the AfterID field if it's non-nil, zero value otherwise. -func (p *ProjectColumnEvent) GetAfterID() int64 { - if p == nil || p.AfterID == nil { - return 0 - } - return *p.AfterID -} - -// GetChanges returns the Changes field. -func (p *ProjectColumnEvent) GetChanges() *ProjectColumnChange { - if p == nil { - return nil - } - return p.Changes -} - -// GetInstallation returns the Installation field. -func (p *ProjectColumnEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetOrg returns the Org field. -func (p *ProjectColumnEvent) GetOrg() *Organization { - if p == nil { - return nil - } - return p.Org -} - -// GetProjectColumn returns the ProjectColumn field. -func (p *ProjectColumnEvent) GetProjectColumn() *ProjectColumn { - if p == nil { - return nil - } - return p.ProjectColumn -} - -// GetRepo returns the Repo field. -func (p *ProjectColumnEvent) GetRepo() *Repository { - if p == nil { - return nil - } - return p.Repo -} - -// GetSender returns the Sender field. -func (p *ProjectColumnEvent) GetSender() *User { - if p == nil { - return nil - } - return p.Sender -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *ProjectEvent) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetChanges returns the Changes field. -func (p *ProjectEvent) GetChanges() *ProjectChange { - if p == nil { - return nil - } - return p.Changes -} - -// GetInstallation returns the Installation field. -func (p *ProjectEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetOrg returns the Org field. -func (p *ProjectEvent) GetOrg() *Organization { - if p == nil { - return nil - } - return p.Org -} - -// GetProject returns the Project field. -func (p *ProjectEvent) GetProject() *Project { - if p == nil { - return nil - } - return p.Project -} - -// GetRepo returns the Repo field. -func (p *ProjectEvent) GetRepo() *Repository { - if p == nil { - return nil - } - return p.Repo -} - -// GetSender returns the Sender field. -func (p *ProjectEvent) GetSender() *User { - if p == nil { - return nil - } - return p.Sender -} - -// GetEnforceAdmins returns the EnforceAdmins field. -func (p *Protection) GetEnforceAdmins() *AdminEnforcement { - if p == nil { - return nil - } - return p.EnforceAdmins -} - -// GetRequiredPullRequestReviews returns the RequiredPullRequestReviews field. -func (p *Protection) GetRequiredPullRequestReviews() *PullRequestReviewsEnforcement { - if p == nil { - return nil - } - return p.RequiredPullRequestReviews -} - -// GetRequiredStatusChecks returns the RequiredStatusChecks field. -func (p *Protection) GetRequiredStatusChecks() *RequiredStatusChecks { - if p == nil { - return nil - } - return p.RequiredStatusChecks -} - -// GetRestrictions returns the Restrictions field. -func (p *Protection) GetRestrictions() *BranchRestrictions { - if p == nil { - return nil - } - return p.Restrictions -} - -// GetRequiredPullRequestReviews returns the RequiredPullRequestReviews field. -func (p *ProtectionRequest) GetRequiredPullRequestReviews() *PullRequestReviewsEnforcementRequest { - if p == nil { - return nil - } - return p.RequiredPullRequestReviews -} - -// GetRequiredStatusChecks returns the RequiredStatusChecks field. -func (p *ProtectionRequest) GetRequiredStatusChecks() *RequiredStatusChecks { - if p == nil { - return nil - } - return p.RequiredStatusChecks -} - -// GetRestrictions returns the Restrictions field. -func (p *ProtectionRequest) GetRestrictions() *BranchRestrictionsRequest { - if p == nil { - return nil - } - return p.Restrictions -} - -// GetInstallation returns the Installation field. -func (p *PublicEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetRepo returns the Repo field. -func (p *PublicEvent) GetRepo() *Repository { - if p == nil { - return nil - } - return p.Repo -} - -// GetSender returns the Sender field. -func (p *PublicEvent) GetSender() *User { - if p == nil { - return nil - } - return p.Sender -} - -// GetAdditions returns the Additions field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetAdditions() int { - if p == nil || p.Additions == nil { - return 0 - } - return *p.Additions -} - -// GetAssignee returns the Assignee field. -func (p *PullRequest) GetAssignee() *User { - if p == nil { - return nil - } - return p.Assignee -} - -// GetAuthorAssociation returns the AuthorAssociation field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetAuthorAssociation() string { - if p == nil || p.AuthorAssociation == nil { - return "" - } - return *p.AuthorAssociation -} - -// GetBase returns the Base field. -func (p *PullRequest) GetBase() *PullRequestBranch { - if p == nil { - return nil - } - return p.Base -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetBody() string { - if p == nil || p.Body == nil { - return "" - } - return *p.Body -} - -// GetChangedFiles returns the ChangedFiles field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetChangedFiles() int { - if p == nil || p.ChangedFiles == nil { - return 0 - } - return *p.ChangedFiles -} - -// GetClosedAt returns the ClosedAt field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetClosedAt() time.Time { - if p == nil || p.ClosedAt == nil { - return time.Time{} - } - return *p.ClosedAt -} - -// GetComments returns the Comments field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetComments() int { - if p == nil || p.Comments == nil { - return 0 - } - return *p.Comments -} - -// GetCommits returns the Commits field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetCommits() int { - if p == nil || p.Commits == nil { - return 0 - } - return *p.Commits -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetCreatedAt() time.Time { - if p == nil || p.CreatedAt == nil { - return time.Time{} - } - return *p.CreatedAt -} - -// GetDeletions returns the Deletions field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetDeletions() int { - if p == nil || p.Deletions == nil { - return 0 - } - return *p.Deletions -} - -// GetDiffURL returns the DiffURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetDiffURL() string { - if p == nil || p.DiffURL == nil { - return "" - } - return *p.DiffURL -} - -// GetHead returns the Head field. -func (p *PullRequest) GetHead() *PullRequestBranch { - if p == nil { - return nil - } - return p.Head -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetID() int64 { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetIssueURL returns the IssueURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetIssueURL() string { - if p == nil || p.IssueURL == nil { - return "" - } - return *p.IssueURL -} - -// GetMaintainerCanModify returns the MaintainerCanModify field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetMaintainerCanModify() bool { - if p == nil || p.MaintainerCanModify == nil { - return false - } - return *p.MaintainerCanModify -} - -// GetMergeable returns the Mergeable field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetMergeable() bool { - if p == nil || p.Mergeable == nil { - return false - } - return *p.Mergeable -} - -// GetMergeableState returns the MergeableState field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetMergeableState() string { - if p == nil || p.MergeableState == nil { - return "" - } - return *p.MergeableState -} - -// GetMergeCommitSHA returns the MergeCommitSHA field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetMergeCommitSHA() string { - if p == nil || p.MergeCommitSHA == nil { - return "" - } - return *p.MergeCommitSHA -} - -// GetMerged returns the Merged field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetMerged() bool { - if p == nil || p.Merged == nil { - return false - } - return *p.Merged -} - -// GetMergedAt returns the MergedAt field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetMergedAt() time.Time { - if p == nil || p.MergedAt == nil { - return time.Time{} - } - return *p.MergedAt -} - -// GetMergedBy returns the MergedBy field. -func (p *PullRequest) GetMergedBy() *User { - if p == nil { - return nil - } - return p.MergedBy -} - -// GetMilestone returns the Milestone field. -func (p *PullRequest) GetMilestone() *Milestone { - if p == nil { - return nil - } - return p.Milestone -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetNodeID() string { - if p == nil || p.NodeID == nil { - return "" - } - return *p.NodeID -} - -// GetNumber returns the Number field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetNumber() int { - if p == nil || p.Number == nil { - return 0 - } - return *p.Number -} - -// GetPatchURL returns the PatchURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetPatchURL() string { - if p == nil || p.PatchURL == nil { - return "" - } - return *p.PatchURL -} - -// GetReviewCommentsURL returns the ReviewCommentsURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetReviewCommentsURL() string { - if p == nil || p.ReviewCommentsURL == nil { - return "" - } - return *p.ReviewCommentsURL -} - -// GetReviewCommentURL returns the ReviewCommentURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetReviewCommentURL() string { - if p == nil || p.ReviewCommentURL == nil { - return "" - } - return *p.ReviewCommentURL -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetState() string { - if p == nil || p.State == nil { - return "" - } - return *p.State -} - -// GetStatusesURL returns the StatusesURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetStatusesURL() string { - if p == nil || p.StatusesURL == nil { - return "" - } - return *p.StatusesURL -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetTitle() string { - if p == nil || p.Title == nil { - return "" - } - return *p.Title -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetUpdatedAt() time.Time { - if p == nil || p.UpdatedAt == nil { - return time.Time{} - } - return *p.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetUser returns the User field. -func (p *PullRequest) GetUser() *User { - if p == nil { - return nil - } - return p.User -} - -// GetLabel returns the Label field if it's non-nil, zero value otherwise. -func (p *PullRequestBranch) GetLabel() string { - if p == nil || p.Label == nil { - return "" - } - return *p.Label -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (p *PullRequestBranch) GetRef() string { - if p == nil || p.Ref == nil { - return "" - } - return *p.Ref -} - -// GetRepo returns the Repo field. -func (p *PullRequestBranch) GetRepo() *Repository { - if p == nil { - return nil - } - return p.Repo -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (p *PullRequestBranch) GetSHA() string { - if p == nil || p.SHA == nil { - return "" - } - return *p.SHA -} - -// GetUser returns the User field. -func (p *PullRequestBranch) GetUser() *User { - if p == nil { - return nil - } - return p.User -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetBody() string { - if p == nil || p.Body == nil { - return "" - } - return *p.Body -} - -// GetCommitID returns the CommitID field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetCommitID() string { - if p == nil || p.CommitID == nil { - return "" - } - return *p.CommitID -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetCreatedAt() time.Time { - if p == nil || p.CreatedAt == nil { - return time.Time{} - } - return *p.CreatedAt -} - -// GetDiffHunk returns the DiffHunk field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetDiffHunk() string { - if p == nil || p.DiffHunk == nil { - return "" - } - return *p.DiffHunk -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetID() int64 { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetInReplyTo returns the InReplyTo field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetInReplyTo() int64 { - if p == nil || p.InReplyTo == nil { - return 0 - } - return *p.InReplyTo -} - -// GetOriginalCommitID returns the OriginalCommitID field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetOriginalCommitID() string { - if p == nil || p.OriginalCommitID == nil { - return "" - } - return *p.OriginalCommitID -} - -// GetOriginalPosition returns the OriginalPosition field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetOriginalPosition() int { - if p == nil || p.OriginalPosition == nil { - return 0 - } - return *p.OriginalPosition -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetPath() string { - if p == nil || p.Path == nil { - return "" - } - return *p.Path -} - -// GetPosition returns the Position field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetPosition() int { - if p == nil || p.Position == nil { - return 0 - } - return *p.Position -} - -// GetPullRequestURL returns the PullRequestURL field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetPullRequestURL() string { - if p == nil || p.PullRequestURL == nil { - return "" - } - return *p.PullRequestURL -} - -// GetReactions returns the Reactions field. -func (p *PullRequestComment) GetReactions() *Reactions { - if p == nil { - return nil - } - return p.Reactions -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetUpdatedAt() time.Time { - if p == nil || p.UpdatedAt == nil { - return time.Time{} - } - return *p.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetUser returns the User field. -func (p *PullRequestComment) GetUser() *User { - if p == nil { - return nil - } - return p.User -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *PullRequestEvent) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetChanges returns the Changes field. -func (p *PullRequestEvent) GetChanges() *EditChange { - if p == nil { - return nil - } - return p.Changes -} - -// GetInstallation returns the Installation field. -func (p *PullRequestEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetNumber returns the Number field if it's non-nil, zero value otherwise. -func (p *PullRequestEvent) GetNumber() int { - if p == nil || p.Number == nil { - return 0 - } - return *p.Number -} - -// GetPullRequest returns the PullRequest field. -func (p *PullRequestEvent) GetPullRequest() *PullRequest { - if p == nil { - return nil - } - return p.PullRequest -} - -// GetRepo returns the Repo field. -func (p *PullRequestEvent) GetRepo() *Repository { - if p == nil { - return nil - } - return p.Repo -} - -// GetSender returns the Sender field. -func (p *PullRequestEvent) GetSender() *User { - if p == nil { - return nil - } - return p.Sender -} - -// GetDiffURL returns the DiffURL field if it's non-nil, zero value otherwise. -func (p *PullRequestLinks) GetDiffURL() string { - if p == nil || p.DiffURL == nil { - return "" - } - return *p.DiffURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *PullRequestLinks) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetPatchURL returns the PatchURL field if it's non-nil, zero value otherwise. -func (p *PullRequestLinks) GetPatchURL() string { - if p == nil || p.PatchURL == nil { - return "" - } - return *p.PatchURL -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *PullRequestLinks) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetMerged returns the Merged field if it's non-nil, zero value otherwise. -func (p *PullRequestMergeResult) GetMerged() bool { - if p == nil || p.Merged == nil { - return false - } - return *p.Merged -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (p *PullRequestMergeResult) GetMessage() string { - if p == nil || p.Message == nil { - return "" - } - return *p.Message -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (p *PullRequestMergeResult) GetSHA() string { - if p == nil || p.SHA == nil { - return "" - } - return *p.SHA -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetBody() string { - if p == nil || p.Body == nil { - return "" - } - return *p.Body -} - -// GetCommitID returns the CommitID field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetCommitID() string { - if p == nil || p.CommitID == nil { - return "" - } - return *p.CommitID -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetID() int64 { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetPullRequestURL returns the PullRequestURL field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetPullRequestURL() string { - if p == nil || p.PullRequestURL == nil { - return "" - } - return *p.PullRequestURL -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetState() string { - if p == nil || p.State == nil { - return "" - } - return *p.State -} - -// GetSubmittedAt returns the SubmittedAt field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetSubmittedAt() time.Time { - if p == nil || p.SubmittedAt == nil { - return time.Time{} - } - return *p.SubmittedAt -} - -// GetUser returns the User field. -func (p *PullRequestReview) GetUser() *User { - if p == nil { - return nil - } - return p.User -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewCommentEvent) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetChanges returns the Changes field. -func (p *PullRequestReviewCommentEvent) GetChanges() *EditChange { - if p == nil { - return nil - } - return p.Changes -} - -// GetComment returns the Comment field. -func (p *PullRequestReviewCommentEvent) GetComment() *PullRequestComment { - if p == nil { - return nil - } - return p.Comment -} - -// GetInstallation returns the Installation field. -func (p *PullRequestReviewCommentEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetPullRequest returns the PullRequest field. -func (p *PullRequestReviewCommentEvent) GetPullRequest() *PullRequest { - if p == nil { - return nil - } - return p.PullRequest -} - -// GetRepo returns the Repo field. -func (p *PullRequestReviewCommentEvent) GetRepo() *Repository { - if p == nil { - return nil - } - return p.Repo -} - -// GetSender returns the Sender field. -func (p *PullRequestReviewCommentEvent) GetSender() *User { - if p == nil { - return nil - } - return p.Sender -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewDismissalRequest) GetMessage() string { - if p == nil || p.Message == nil { - return "" - } - return *p.Message -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewEvent) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetInstallation returns the Installation field. -func (p *PullRequestReviewEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetOrganization returns the Organization field. -func (p *PullRequestReviewEvent) GetOrganization() *Organization { - if p == nil { - return nil - } - return p.Organization -} - -// GetPullRequest returns the PullRequest field. -func (p *PullRequestReviewEvent) GetPullRequest() *PullRequest { - if p == nil { - return nil - } - return p.PullRequest -} - -// GetRepo returns the Repo field. -func (p *PullRequestReviewEvent) GetRepo() *Repository { - if p == nil { - return nil - } - return p.Repo -} - -// GetReview returns the Review field. -func (p *PullRequestReviewEvent) GetReview() *PullRequestReview { - if p == nil { - return nil - } - return p.Review -} - -// GetSender returns the Sender field. -func (p *PullRequestReviewEvent) GetSender() *User { - if p == nil { - return nil - } - return p.Sender -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewRequest) GetBody() string { - if p == nil || p.Body == nil { - return "" - } - return *p.Body -} - -// GetCommitID returns the CommitID field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewRequest) GetCommitID() string { - if p == nil || p.CommitID == nil { - return "" - } - return *p.CommitID -} - -// GetEvent returns the Event field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewRequest) GetEvent() string { - if p == nil || p.Event == nil { - return "" - } - return *p.Event -} - -// GetDismissalRestrictionsRequest returns the DismissalRestrictionsRequest field. -func (p *PullRequestReviewsEnforcementRequest) GetDismissalRestrictionsRequest() *DismissalRestrictionsRequest { - if p == nil { - return nil - } - return p.DismissalRestrictionsRequest -} - -// GetDismissalRestrictionsRequest returns the DismissalRestrictionsRequest field. -func (p *PullRequestReviewsEnforcementUpdate) GetDismissalRestrictionsRequest() *DismissalRestrictionsRequest { - if p == nil { - return nil - } - return p.DismissalRestrictionsRequest -} - -// GetDismissStaleReviews returns the DismissStaleReviews field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewsEnforcementUpdate) GetDismissStaleReviews() bool { - if p == nil || p.DismissStaleReviews == nil { - return false - } - return *p.DismissStaleReviews -} - -// GetMergablePulls returns the MergablePulls field if it's non-nil, zero value otherwise. -func (p *PullStats) GetMergablePulls() int { - if p == nil || p.MergablePulls == nil { - return 0 - } - return *p.MergablePulls -} - -// GetMergedPulls returns the MergedPulls field if it's non-nil, zero value otherwise. -func (p *PullStats) GetMergedPulls() int { - if p == nil || p.MergedPulls == nil { - return 0 - } - return *p.MergedPulls -} - -// GetTotalPulls returns the TotalPulls field if it's non-nil, zero value otherwise. -func (p *PullStats) GetTotalPulls() int { - if p == nil || p.TotalPulls == nil { - return 0 - } - return *p.TotalPulls -} - -// GetUnmergablePulls returns the UnmergablePulls field if it's non-nil, zero value otherwise. -func (p *PullStats) GetUnmergablePulls() int { - if p == nil || p.UnmergablePulls == nil { - return 0 - } - return *p.UnmergablePulls -} - -// GetCommits returns the Commits field if it's non-nil, zero value otherwise. -func (p *PunchCard) GetCommits() int { - if p == nil || p.Commits == nil { - return 0 - } - return *p.Commits -} - -// GetDay returns the Day field if it's non-nil, zero value otherwise. -func (p *PunchCard) GetDay() int { - if p == nil || p.Day == nil { - return 0 - } - return *p.Day -} - -// GetHour returns the Hour field if it's non-nil, zero value otherwise. -func (p *PunchCard) GetHour() int { - if p == nil || p.Hour == nil { - return 0 - } - return *p.Hour -} - -// GetAfter returns the After field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetAfter() string { - if p == nil || p.After == nil { - return "" - } - return *p.After -} - -// GetBaseRef returns the BaseRef field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetBaseRef() string { - if p == nil || p.BaseRef == nil { - return "" - } - return *p.BaseRef -} - -// GetBefore returns the Before field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetBefore() string { - if p == nil || p.Before == nil { - return "" - } - return *p.Before -} - -// GetCompare returns the Compare field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetCompare() string { - if p == nil || p.Compare == nil { - return "" - } - return *p.Compare -} - -// GetCreated returns the Created field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetCreated() bool { - if p == nil || p.Created == nil { - return false - } - return *p.Created -} - -// GetDeleted returns the Deleted field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetDeleted() bool { - if p == nil || p.Deleted == nil { - return false - } - return *p.Deleted -} - -// GetDistinctSize returns the DistinctSize field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetDistinctSize() int { - if p == nil || p.DistinctSize == nil { - return 0 - } - return *p.DistinctSize -} - -// GetForced returns the Forced field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetForced() bool { - if p == nil || p.Forced == nil { - return false - } - return *p.Forced -} - -// GetHead returns the Head field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetHead() string { - if p == nil || p.Head == nil { - return "" - } - return *p.Head -} - -// GetHeadCommit returns the HeadCommit field. -func (p *PushEvent) GetHeadCommit() *PushEventCommit { - if p == nil { - return nil - } - return p.HeadCommit -} - -// GetInstallation returns the Installation field. -func (p *PushEvent) GetInstallation() *Installation { - if p == nil { - return nil - } - return p.Installation -} - -// GetPusher returns the Pusher field. -func (p *PushEvent) GetPusher() *User { - if p == nil { - return nil - } - return p.Pusher -} - -// GetPushID returns the PushID field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetPushID() int64 { - if p == nil || p.PushID == nil { - return 0 - } - return *p.PushID -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetRef() string { - if p == nil || p.Ref == nil { - return "" - } - return *p.Ref -} - -// GetRepo returns the Repo field. -func (p *PushEvent) GetRepo() *PushEventRepository { - if p == nil { - return nil - } - return p.Repo -} - -// GetSender returns the Sender field. -func (p *PushEvent) GetSender() *User { - if p == nil { - return nil - } - return p.Sender -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetSize() int { - if p == nil || p.Size == nil { - return 0 - } - return *p.Size -} - -// GetAuthor returns the Author field. -func (p *PushEventCommit) GetAuthor() *CommitAuthor { - if p == nil { - return nil - } - return p.Author -} - -// GetCommitter returns the Committer field. -func (p *PushEventCommit) GetCommitter() *CommitAuthor { - if p == nil { - return nil - } - return p.Committer -} - -// GetDistinct returns the Distinct field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetDistinct() bool { - if p == nil || p.Distinct == nil { - return false - } - return *p.Distinct -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetID() string { - if p == nil || p.ID == nil { - return "" - } - return *p.ID -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetMessage() string { - if p == nil || p.Message == nil { - return "" - } - return *p.Message -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetSHA() string { - if p == nil || p.SHA == nil { - return "" - } - return *p.SHA -} - -// GetTimestamp returns the Timestamp field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetTimestamp() Timestamp { - if p == nil || p.Timestamp == nil { - return Timestamp{} - } - return *p.Timestamp -} - -// GetTreeID returns the TreeID field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetTreeID() string { - if p == nil || p.TreeID == nil { - return "" - } - return *p.TreeID -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (p *PushEventRepoOwner) GetEmail() string { - if p == nil || p.Email == nil { - return "" - } - return *p.Email -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (p *PushEventRepoOwner) GetName() string { - if p == nil || p.Name == nil { - return "" - } - return *p.Name -} - -// GetArchiveURL returns the ArchiveURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetArchiveURL() string { - if p == nil || p.ArchiveURL == nil { - return "" - } - return *p.ArchiveURL -} - -// GetCloneURL returns the CloneURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetCloneURL() string { - if p == nil || p.CloneURL == nil { - return "" - } - return *p.CloneURL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetCreatedAt() Timestamp { - if p == nil || p.CreatedAt == nil { - return Timestamp{} - } - return *p.CreatedAt -} - -// GetDefaultBranch returns the DefaultBranch field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetDefaultBranch() string { - if p == nil || p.DefaultBranch == nil { - return "" - } - return *p.DefaultBranch -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetDescription() string { - if p == nil || p.Description == nil { - return "" - } - return *p.Description -} - -// GetFork returns the Fork field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetFork() bool { - if p == nil || p.Fork == nil { - return false - } - return *p.Fork -} - -// GetForksCount returns the ForksCount field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetForksCount() int { - if p == nil || p.ForksCount == nil { - return 0 - } - return *p.ForksCount -} - -// GetFullName returns the FullName field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetFullName() string { - if p == nil || p.FullName == nil { - return "" - } - return *p.FullName -} - -// GetGitURL returns the GitURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetGitURL() string { - if p == nil || p.GitURL == nil { - return "" - } - return *p.GitURL -} - -// GetHasDownloads returns the HasDownloads field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetHasDownloads() bool { - if p == nil || p.HasDownloads == nil { - return false - } - return *p.HasDownloads -} - -// GetHasIssues returns the HasIssues field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetHasIssues() bool { - if p == nil || p.HasIssues == nil { - return false - } - return *p.HasIssues -} - -// GetHasPages returns the HasPages field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetHasPages() bool { - if p == nil || p.HasPages == nil { - return false - } - return *p.HasPages -} - -// GetHasWiki returns the HasWiki field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetHasWiki() bool { - if p == nil || p.HasWiki == nil { - return false - } - return *p.HasWiki -} - -// GetHomepage returns the Homepage field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetHomepage() string { - if p == nil || p.Homepage == nil { - return "" - } - return *p.Homepage -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetID() int64 { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetLanguage returns the Language field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetLanguage() string { - if p == nil || p.Language == nil { - return "" - } - return *p.Language -} - -// GetMasterBranch returns the MasterBranch field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetMasterBranch() string { - if p == nil || p.MasterBranch == nil { - return "" - } - return *p.MasterBranch -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetName() string { - if p == nil || p.Name == nil { - return "" - } - return *p.Name -} - -// GetOpenIssuesCount returns the OpenIssuesCount field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetOpenIssuesCount() int { - if p == nil || p.OpenIssuesCount == nil { - return 0 - } - return *p.OpenIssuesCount -} - -// GetOrganization returns the Organization field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetOrganization() string { - if p == nil || p.Organization == nil { - return "" - } - return *p.Organization -} - -// GetOwner returns the Owner field. -func (p *PushEventRepository) GetOwner() *PushEventRepoOwner { - if p == nil { - return nil - } - return p.Owner -} - -// GetPrivate returns the Private field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetPrivate() bool { - if p == nil || p.Private == nil { - return false - } - return *p.Private -} - -// GetPushedAt returns the PushedAt field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetPushedAt() Timestamp { - if p == nil || p.PushedAt == nil { - return Timestamp{} - } - return *p.PushedAt -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetSize() int { - if p == nil || p.Size == nil { - return 0 - } - return *p.Size -} - -// GetSSHURL returns the SSHURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetSSHURL() string { - if p == nil || p.SSHURL == nil { - return "" - } - return *p.SSHURL -} - -// GetStargazersCount returns the StargazersCount field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetStargazersCount() int { - if p == nil || p.StargazersCount == nil { - return 0 - } - return *p.StargazersCount -} - -// GetStatusesURL returns the StatusesURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetStatusesURL() string { - if p == nil || p.StatusesURL == nil { - return "" - } - return *p.StatusesURL -} - -// GetSVNURL returns the SVNURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetSVNURL() string { - if p == nil || p.SVNURL == nil { - return "" - } - return *p.SVNURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetUpdatedAt() Timestamp { - if p == nil || p.UpdatedAt == nil { - return Timestamp{} - } - return *p.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetWatchersCount returns the WatchersCount field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetWatchersCount() int { - if p == nil || p.WatchersCount == nil { - return 0 - } - return *p.WatchersCount -} - -// GetCore returns the Core field. -func (r *RateLimits) GetCore() *Rate { - if r == nil { - return nil - } - return r.Core -} - -// GetSearch returns the Search field. -func (r *RateLimits) GetSearch() *Rate { - if r == nil { - return nil - } - return r.Search -} - -// GetContent returns the Content field if it's non-nil, zero value otherwise. -func (r *Reaction) GetContent() string { - if r == nil || r.Content == nil { - return "" - } - return *r.Content -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *Reaction) GetID() int64 { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetUser returns the User field. -func (r *Reaction) GetUser() *User { - if r == nil { - return nil - } - return r.User -} - -// GetConfused returns the Confused field if it's non-nil, zero value otherwise. -func (r *Reactions) GetConfused() int { - if r == nil || r.Confused == nil { - return 0 - } - return *r.Confused -} - -// GetHeart returns the Heart field if it's non-nil, zero value otherwise. -func (r *Reactions) GetHeart() int { - if r == nil || r.Heart == nil { - return 0 - } - return *r.Heart -} - -// GetHooray returns the Hooray field if it's non-nil, zero value otherwise. -func (r *Reactions) GetHooray() int { - if r == nil || r.Hooray == nil { - return 0 - } - return *r.Hooray -} - -// GetLaugh returns the Laugh field if it's non-nil, zero value otherwise. -func (r *Reactions) GetLaugh() int { - if r == nil || r.Laugh == nil { - return 0 - } - return *r.Laugh -} - -// GetMinusOne returns the MinusOne field if it's non-nil, zero value otherwise. -func (r *Reactions) GetMinusOne() int { - if r == nil || r.MinusOne == nil { - return 0 - } - return *r.MinusOne -} - -// GetPlusOne returns the PlusOne field if it's non-nil, zero value otherwise. -func (r *Reactions) GetPlusOne() int { - if r == nil || r.PlusOne == nil { - return 0 - } - return *r.PlusOne -} - -// GetTotalCount returns the TotalCount field if it's non-nil, zero value otherwise. -func (r *Reactions) GetTotalCount() int { - if r == nil || r.TotalCount == nil { - return 0 - } - return *r.TotalCount -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *Reactions) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (r *Reference) GetNodeID() string { - if r == nil || r.NodeID == nil { - return "" - } - return *r.NodeID -} - -// GetObject returns the Object field. -func (r *Reference) GetObject() *GitObject { - if r == nil { - return nil - } - return r.Object -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (r *Reference) GetRef() string { - if r == nil || r.Ref == nil { - return "" - } - return *r.Ref -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *Reference) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetBrowserDownloadURL returns the BrowserDownloadURL field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetBrowserDownloadURL() string { - if r == nil || r.BrowserDownloadURL == nil { - return "" - } - return *r.BrowserDownloadURL -} - -// GetContentType returns the ContentType field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetContentType() string { - if r == nil || r.ContentType == nil { - return "" - } - return *r.ContentType -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetCreatedAt() Timestamp { - if r == nil || r.CreatedAt == nil { - return Timestamp{} - } - return *r.CreatedAt -} - -// GetDownloadCount returns the DownloadCount field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetDownloadCount() int { - if r == nil || r.DownloadCount == nil { - return 0 - } - return *r.DownloadCount -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetID() int64 { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetLabel returns the Label field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetLabel() string { - if r == nil || r.Label == nil { - return "" - } - return *r.Label -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetName() string { - if r == nil || r.Name == nil { - return "" - } - return *r.Name -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetSize() int { - if r == nil || r.Size == nil { - return 0 - } - return *r.Size -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetState() string { - if r == nil || r.State == nil { - return "" - } - return *r.State -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetUpdatedAt() Timestamp { - if r == nil || r.UpdatedAt == nil { - return Timestamp{} - } - return *r.UpdatedAt -} - -// GetUploader returns the Uploader field. -func (r *ReleaseAsset) GetUploader() *User { - if r == nil { - return nil - } - return r.Uploader -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (r *ReleaseEvent) GetAction() string { - if r == nil || r.Action == nil { - return "" - } - return *r.Action -} - -// GetInstallation returns the Installation field. -func (r *ReleaseEvent) GetInstallation() *Installation { - if r == nil { - return nil - } - return r.Installation -} - -// GetRelease returns the Release field. -func (r *ReleaseEvent) GetRelease() *RepositoryRelease { - if r == nil { - return nil - } - return r.Release -} - -// GetRepo returns the Repo field. -func (r *ReleaseEvent) GetRepo() *Repository { - if r == nil { - return nil - } - return r.Repo -} - -// GetSender returns the Sender field. -func (r *ReleaseEvent) GetSender() *User { - if r == nil { - return nil - } - return r.Sender -} - -// GetFrom returns the From field if it's non-nil, zero value otherwise. -func (r *Rename) GetFrom() string { - if r == nil || r.From == nil { - return "" - } - return *r.From -} - -// GetTo returns the To field if it's non-nil, zero value otherwise. -func (r *Rename) GetTo() string { - if r == nil || r.To == nil { - return "" - } - return *r.To -} - -// GetIncompleteResults returns the IncompleteResults field if it's non-nil, zero value otherwise. -func (r *RepositoriesSearchResult) GetIncompleteResults() bool { - if r == nil || r.IncompleteResults == nil { - return false - } - return *r.IncompleteResults -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (r *RepositoriesSearchResult) GetTotal() int { - if r == nil || r.Total == nil { - return 0 - } - return *r.Total -} - -// GetAllowMergeCommit returns the AllowMergeCommit field if it's non-nil, zero value otherwise. -func (r *Repository) GetAllowMergeCommit() bool { - if r == nil || r.AllowMergeCommit == nil { - return false - } - return *r.AllowMergeCommit -} - -// GetAllowRebaseMerge returns the AllowRebaseMerge field if it's non-nil, zero value otherwise. -func (r *Repository) GetAllowRebaseMerge() bool { - if r == nil || r.AllowRebaseMerge == nil { - return false - } - return *r.AllowRebaseMerge -} - -// GetAllowSquashMerge returns the AllowSquashMerge field if it's non-nil, zero value otherwise. -func (r *Repository) GetAllowSquashMerge() bool { - if r == nil || r.AllowSquashMerge == nil { - return false - } - return *r.AllowSquashMerge -} - -// GetArchived returns the Archived field if it's non-nil, zero value otherwise. -func (r *Repository) GetArchived() bool { - if r == nil || r.Archived == nil { - return false - } - return *r.Archived -} - -// GetArchiveURL returns the ArchiveURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetArchiveURL() string { - if r == nil || r.ArchiveURL == nil { - return "" - } - return *r.ArchiveURL -} - -// GetAssigneesURL returns the AssigneesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetAssigneesURL() string { - if r == nil || r.AssigneesURL == nil { - return "" - } - return *r.AssigneesURL -} - -// GetAutoInit returns the AutoInit field if it's non-nil, zero value otherwise. -func (r *Repository) GetAutoInit() bool { - if r == nil || r.AutoInit == nil { - return false - } - return *r.AutoInit -} - -// GetBlobsURL returns the BlobsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetBlobsURL() string { - if r == nil || r.BlobsURL == nil { - return "" - } - return *r.BlobsURL -} - -// GetBranchesURL returns the BranchesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetBranchesURL() string { - if r == nil || r.BranchesURL == nil { - return "" - } - return *r.BranchesURL -} - -// GetCloneURL returns the CloneURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetCloneURL() string { - if r == nil || r.CloneURL == nil { - return "" - } - return *r.CloneURL -} - -// GetCodeOfConduct returns the CodeOfConduct field. -func (r *Repository) GetCodeOfConduct() *CodeOfConduct { - if r == nil { - return nil - } - return r.CodeOfConduct -} - -// GetCollaboratorsURL returns the CollaboratorsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetCollaboratorsURL() string { - if r == nil || r.CollaboratorsURL == nil { - return "" - } - return *r.CollaboratorsURL -} - -// GetCommentsURL returns the CommentsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetCommentsURL() string { - if r == nil || r.CommentsURL == nil { - return "" - } - return *r.CommentsURL -} - -// GetCommitsURL returns the CommitsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetCommitsURL() string { - if r == nil || r.CommitsURL == nil { - return "" - } - return *r.CommitsURL -} - -// GetCompareURL returns the CompareURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetCompareURL() string { - if r == nil || r.CompareURL == nil { - return "" - } - return *r.CompareURL -} - -// GetContentsURL returns the ContentsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetContentsURL() string { - if r == nil || r.ContentsURL == nil { - return "" - } - return *r.ContentsURL -} - -// GetContributorsURL returns the ContributorsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetContributorsURL() string { - if r == nil || r.ContributorsURL == nil { - return "" - } - return *r.ContributorsURL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (r *Repository) GetCreatedAt() Timestamp { - if r == nil || r.CreatedAt == nil { - return Timestamp{} - } - return *r.CreatedAt -} - -// GetDefaultBranch returns the DefaultBranch field if it's non-nil, zero value otherwise. -func (r *Repository) GetDefaultBranch() string { - if r == nil || r.DefaultBranch == nil { - return "" - } - return *r.DefaultBranch -} - -// GetDeploymentsURL returns the DeploymentsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetDeploymentsURL() string { - if r == nil || r.DeploymentsURL == nil { - return "" - } - return *r.DeploymentsURL -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (r *Repository) GetDescription() string { - if r == nil || r.Description == nil { - return "" - } - return *r.Description -} - -// GetDownloadsURL returns the DownloadsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetDownloadsURL() string { - if r == nil || r.DownloadsURL == nil { - return "" - } - return *r.DownloadsURL -} - -// GetEventsURL returns the EventsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetEventsURL() string { - if r == nil || r.EventsURL == nil { - return "" - } - return *r.EventsURL -} - -// GetFork returns the Fork field if it's non-nil, zero value otherwise. -func (r *Repository) GetFork() bool { - if r == nil || r.Fork == nil { - return false - } - return *r.Fork -} - -// GetForksCount returns the ForksCount field if it's non-nil, zero value otherwise. -func (r *Repository) GetForksCount() int { - if r == nil || r.ForksCount == nil { - return 0 - } - return *r.ForksCount -} - -// GetForksURL returns the ForksURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetForksURL() string { - if r == nil || r.ForksURL == nil { - return "" - } - return *r.ForksURL -} - -// GetFullName returns the FullName field if it's non-nil, zero value otherwise. -func (r *Repository) GetFullName() string { - if r == nil || r.FullName == nil { - return "" - } - return *r.FullName -} - -// GetGitCommitsURL returns the GitCommitsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetGitCommitsURL() string { - if r == nil || r.GitCommitsURL == nil { - return "" - } - return *r.GitCommitsURL -} - -// GetGitignoreTemplate returns the GitignoreTemplate field if it's non-nil, zero value otherwise. -func (r *Repository) GetGitignoreTemplate() string { - if r == nil || r.GitignoreTemplate == nil { - return "" - } - return *r.GitignoreTemplate -} - -// GetGitRefsURL returns the GitRefsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetGitRefsURL() string { - if r == nil || r.GitRefsURL == nil { - return "" - } - return *r.GitRefsURL -} - -// GetGitTagsURL returns the GitTagsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetGitTagsURL() string { - if r == nil || r.GitTagsURL == nil { - return "" - } - return *r.GitTagsURL -} - -// GetGitURL returns the GitURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetGitURL() string { - if r == nil || r.GitURL == nil { - return "" - } - return *r.GitURL -} - -// GetHasDownloads returns the HasDownloads field if it's non-nil, zero value otherwise. -func (r *Repository) GetHasDownloads() bool { - if r == nil || r.HasDownloads == nil { - return false - } - return *r.HasDownloads -} - -// GetHasIssues returns the HasIssues field if it's non-nil, zero value otherwise. -func (r *Repository) GetHasIssues() bool { - if r == nil || r.HasIssues == nil { - return false - } - return *r.HasIssues -} - -// GetHasPages returns the HasPages field if it's non-nil, zero value otherwise. -func (r *Repository) GetHasPages() bool { - if r == nil || r.HasPages == nil { - return false - } - return *r.HasPages -} - -// GetHasProjects returns the HasProjects field if it's non-nil, zero value otherwise. -func (r *Repository) GetHasProjects() bool { - if r == nil || r.HasProjects == nil { - return false - } - return *r.HasProjects -} - -// GetHasWiki returns the HasWiki field if it's non-nil, zero value otherwise. -func (r *Repository) GetHasWiki() bool { - if r == nil || r.HasWiki == nil { - return false - } - return *r.HasWiki -} - -// GetHomepage returns the Homepage field if it's non-nil, zero value otherwise. -func (r *Repository) GetHomepage() string { - if r == nil || r.Homepage == nil { - return "" - } - return *r.Homepage -} - -// GetHooksURL returns the HooksURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetHooksURL() string { - if r == nil || r.HooksURL == nil { - return "" - } - return *r.HooksURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *Repository) GetID() int64 { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetIssueCommentURL returns the IssueCommentURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetIssueCommentURL() string { - if r == nil || r.IssueCommentURL == nil { - return "" - } - return *r.IssueCommentURL -} - -// GetIssueEventsURL returns the IssueEventsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetIssueEventsURL() string { - if r == nil || r.IssueEventsURL == nil { - return "" - } - return *r.IssueEventsURL -} - -// GetIssuesURL returns the IssuesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetIssuesURL() string { - if r == nil || r.IssuesURL == nil { - return "" - } - return *r.IssuesURL -} - -// GetKeysURL returns the KeysURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetKeysURL() string { - if r == nil || r.KeysURL == nil { - return "" - } - return *r.KeysURL -} - -// GetLabelsURL returns the LabelsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetLabelsURL() string { - if r == nil || r.LabelsURL == nil { - return "" - } - return *r.LabelsURL -} - -// GetLanguage returns the Language field if it's non-nil, zero value otherwise. -func (r *Repository) GetLanguage() string { - if r == nil || r.Language == nil { - return "" - } - return *r.Language -} - -// GetLanguagesURL returns the LanguagesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetLanguagesURL() string { - if r == nil || r.LanguagesURL == nil { - return "" - } - return *r.LanguagesURL -} - -// GetLicense returns the License field. -func (r *Repository) GetLicense() *License { - if r == nil { - return nil - } - return r.License -} - -// GetLicenseTemplate returns the LicenseTemplate field if it's non-nil, zero value otherwise. -func (r *Repository) GetLicenseTemplate() string { - if r == nil || r.LicenseTemplate == nil { - return "" - } - return *r.LicenseTemplate -} - -// GetMasterBranch returns the MasterBranch field if it's non-nil, zero value otherwise. -func (r *Repository) GetMasterBranch() string { - if r == nil || r.MasterBranch == nil { - return "" - } - return *r.MasterBranch -} - -// GetMergesURL returns the MergesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetMergesURL() string { - if r == nil || r.MergesURL == nil { - return "" - } - return *r.MergesURL -} - -// GetMilestonesURL returns the MilestonesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetMilestonesURL() string { - if r == nil || r.MilestonesURL == nil { - return "" - } - return *r.MilestonesURL -} - -// GetMirrorURL returns the MirrorURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetMirrorURL() string { - if r == nil || r.MirrorURL == nil { - return "" - } - return *r.MirrorURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (r *Repository) GetName() string { - if r == nil || r.Name == nil { - return "" - } - return *r.Name -} - -// GetNetworkCount returns the NetworkCount field if it's non-nil, zero value otherwise. -func (r *Repository) GetNetworkCount() int { - if r == nil || r.NetworkCount == nil { - return 0 - } - return *r.NetworkCount -} - -// GetNotificationsURL returns the NotificationsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetNotificationsURL() string { - if r == nil || r.NotificationsURL == nil { - return "" - } - return *r.NotificationsURL -} - -// GetOpenIssuesCount returns the OpenIssuesCount field if it's non-nil, zero value otherwise. -func (r *Repository) GetOpenIssuesCount() int { - if r == nil || r.OpenIssuesCount == nil { - return 0 - } - return *r.OpenIssuesCount -} - -// GetOrganization returns the Organization field. -func (r *Repository) GetOrganization() *Organization { - if r == nil { - return nil - } - return r.Organization -} - -// GetOwner returns the Owner field. -func (r *Repository) GetOwner() *User { - if r == nil { - return nil - } - return r.Owner -} - -// GetParent returns the Parent field. -func (r *Repository) GetParent() *Repository { - if r == nil { - return nil - } - return r.Parent -} - -// GetPermissions returns the Permissions field if it's non-nil, zero value otherwise. -func (r *Repository) GetPermissions() map[string]bool { - if r == nil || r.Permissions == nil { - return map[string]bool{} - } - return *r.Permissions -} - -// GetPrivate returns the Private field if it's non-nil, zero value otherwise. -func (r *Repository) GetPrivate() bool { - if r == nil || r.Private == nil { - return false - } - return *r.Private -} - -// GetPullsURL returns the PullsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetPullsURL() string { - if r == nil || r.PullsURL == nil { - return "" - } - return *r.PullsURL -} - -// GetPushedAt returns the PushedAt field if it's non-nil, zero value otherwise. -func (r *Repository) GetPushedAt() Timestamp { - if r == nil || r.PushedAt == nil { - return Timestamp{} - } - return *r.PushedAt -} - -// GetReleasesURL returns the ReleasesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetReleasesURL() string { - if r == nil || r.ReleasesURL == nil { - return "" - } - return *r.ReleasesURL -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (r *Repository) GetSize() int { - if r == nil || r.Size == nil { - return 0 - } - return *r.Size -} - -// GetSource returns the Source field. -func (r *Repository) GetSource() *Repository { - if r == nil { - return nil - } - return r.Source -} - -// GetSSHURL returns the SSHURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetSSHURL() string { - if r == nil || r.SSHURL == nil { - return "" - } - return *r.SSHURL -} - -// GetStargazersCount returns the StargazersCount field if it's non-nil, zero value otherwise. -func (r *Repository) GetStargazersCount() int { - if r == nil || r.StargazersCount == nil { - return 0 - } - return *r.StargazersCount -} - -// GetStargazersURL returns the StargazersURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetStargazersURL() string { - if r == nil || r.StargazersURL == nil { - return "" - } - return *r.StargazersURL -} - -// GetStatusesURL returns the StatusesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetStatusesURL() string { - if r == nil || r.StatusesURL == nil { - return "" - } - return *r.StatusesURL -} - -// GetSubscribersCount returns the SubscribersCount field if it's non-nil, zero value otherwise. -func (r *Repository) GetSubscribersCount() int { - if r == nil || r.SubscribersCount == nil { - return 0 - } - return *r.SubscribersCount -} - -// GetSubscribersURL returns the SubscribersURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetSubscribersURL() string { - if r == nil || r.SubscribersURL == nil { - return "" - } - return *r.SubscribersURL -} - -// GetSubscriptionURL returns the SubscriptionURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetSubscriptionURL() string { - if r == nil || r.SubscriptionURL == nil { - return "" - } - return *r.SubscriptionURL -} - -// GetSVNURL returns the SVNURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetSVNURL() string { - if r == nil || r.SVNURL == nil { - return "" - } - return *r.SVNURL -} - -// GetTagsURL returns the TagsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetTagsURL() string { - if r == nil || r.TagsURL == nil { - return "" - } - return *r.TagsURL -} - -// GetTeamID returns the TeamID field if it's non-nil, zero value otherwise. -func (r *Repository) GetTeamID() int64 { - if r == nil || r.TeamID == nil { - return 0 - } - return *r.TeamID -} - -// GetTeamsURL returns the TeamsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetTeamsURL() string { - if r == nil || r.TeamsURL == nil { - return "" - } - return *r.TeamsURL -} - -// GetTreesURL returns the TreesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetTreesURL() string { - if r == nil || r.TreesURL == nil { - return "" - } - return *r.TreesURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (r *Repository) GetUpdatedAt() Timestamp { - if r == nil || r.UpdatedAt == nil { - return Timestamp{} - } - return *r.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *Repository) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetWatchersCount returns the WatchersCount field if it's non-nil, zero value otherwise. -func (r *Repository) GetWatchersCount() int { - if r == nil || r.WatchersCount == nil { - return 0 - } - return *r.WatchersCount -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetBody() string { - if r == nil || r.Body == nil { - return "" - } - return *r.Body -} - -// GetCommitID returns the CommitID field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetCommitID() string { - if r == nil || r.CommitID == nil { - return "" - } - return *r.CommitID -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetCreatedAt() time.Time { - if r == nil || r.CreatedAt == nil { - return time.Time{} - } - return *r.CreatedAt -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetID() int64 { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetPath() string { - if r == nil || r.Path == nil { - return "" - } - return *r.Path -} - -// GetPosition returns the Position field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetPosition() int { - if r == nil || r.Position == nil { - return 0 - } - return *r.Position -} - -// GetReactions returns the Reactions field. -func (r *RepositoryComment) GetReactions() *Reactions { - if r == nil { - return nil - } - return r.Reactions -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetUpdatedAt() time.Time { - if r == nil || r.UpdatedAt == nil { - return time.Time{} - } - return *r.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetUser returns the User field. -func (r *RepositoryComment) GetUser() *User { - if r == nil { - return nil - } - return r.User -} - -// GetAuthor returns the Author field. -func (r *RepositoryCommit) GetAuthor() *User { - if r == nil { - return nil - } - return r.Author -} - -// GetCommentsURL returns the CommentsURL field if it's non-nil, zero value otherwise. -func (r *RepositoryCommit) GetCommentsURL() string { - if r == nil || r.CommentsURL == nil { - return "" - } - return *r.CommentsURL -} - -// GetCommit returns the Commit field. -func (r *RepositoryCommit) GetCommit() *Commit { - if r == nil { - return nil - } - return r.Commit -} - -// GetCommitter returns the Committer field. -func (r *RepositoryCommit) GetCommitter() *User { - if r == nil { - return nil - } - return r.Committer -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *RepositoryCommit) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (r *RepositoryCommit) GetSHA() string { - if r == nil || r.SHA == nil { - return "" - } - return *r.SHA -} - -// GetStats returns the Stats field. -func (r *RepositoryCommit) GetStats() *CommitStats { - if r == nil { - return nil - } - return r.Stats -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepositoryCommit) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetDownloadURL returns the DownloadURL field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetDownloadURL() string { - if r == nil || r.DownloadURL == nil { - return "" - } - return *r.DownloadURL -} - -// GetEncoding returns the Encoding field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetEncoding() string { - if r == nil || r.Encoding == nil { - return "" - } - return *r.Encoding -} - -// GetGitURL returns the GitURL field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetGitURL() string { - if r == nil || r.GitURL == nil { - return "" - } - return *r.GitURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetName() string { - if r == nil || r.Name == nil { - return "" - } - return *r.Name -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetPath() string { - if r == nil || r.Path == nil { - return "" - } - return *r.Path -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetSHA() string { - if r == nil || r.SHA == nil { - return "" - } - return *r.SHA -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetSize() int { - if r == nil || r.Size == nil { - return 0 - } - return *r.Size -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetType() string { - if r == nil || r.Type == nil { - return "" - } - return *r.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetAuthor returns the Author field. -func (r *RepositoryContentFileOptions) GetAuthor() *CommitAuthor { - if r == nil { - return nil - } - return r.Author -} - -// GetBranch returns the Branch field if it's non-nil, zero value otherwise. -func (r *RepositoryContentFileOptions) GetBranch() string { - if r == nil || r.Branch == nil { - return "" - } - return *r.Branch -} - -// GetCommitter returns the Committer field. -func (r *RepositoryContentFileOptions) GetCommitter() *CommitAuthor { - if r == nil { - return nil - } - return r.Committer -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (r *RepositoryContentFileOptions) GetMessage() string { - if r == nil || r.Message == nil { - return "" - } - return *r.Message -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (r *RepositoryContentFileOptions) GetSHA() string { - if r == nil || r.SHA == nil { - return "" - } - return *r.SHA -} - -// GetContent returns the Content field. -func (r *RepositoryContentResponse) GetContent() *RepositoryContent { - if r == nil { - return nil - } - return r.Content -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (r *RepositoryEvent) GetAction() string { - if r == nil || r.Action == nil { - return "" - } - return *r.Action -} - -// GetInstallation returns the Installation field. -func (r *RepositoryEvent) GetInstallation() *Installation { - if r == nil { - return nil - } - return r.Installation -} - -// GetOrg returns the Org field. -func (r *RepositoryEvent) GetOrg() *Organization { - if r == nil { - return nil - } - return r.Org -} - -// GetRepo returns the Repo field. -func (r *RepositoryEvent) GetRepo() *Repository { - if r == nil { - return nil - } - return r.Repo -} - -// GetSender returns the Sender field. -func (r *RepositoryEvent) GetSender() *User { - if r == nil { - return nil - } - return r.Sender -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (r *RepositoryInvitation) GetCreatedAt() Timestamp { - if r == nil || r.CreatedAt == nil { - return Timestamp{} - } - return *r.CreatedAt -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *RepositoryInvitation) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *RepositoryInvitation) GetID() int64 { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetInvitee returns the Invitee field. -func (r *RepositoryInvitation) GetInvitee() *User { - if r == nil { - return nil - } - return r.Invitee -} - -// GetInviter returns the Inviter field. -func (r *RepositoryInvitation) GetInviter() *User { - if r == nil { - return nil - } - return r.Inviter -} - -// GetPermissions returns the Permissions field if it's non-nil, zero value otherwise. -func (r *RepositoryInvitation) GetPermissions() string { - if r == nil || r.Permissions == nil { - return "" - } - return *r.Permissions -} - -// GetRepo returns the Repo field. -func (r *RepositoryInvitation) GetRepo() *Repository { - if r == nil { - return nil - } - return r.Repo -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepositoryInvitation) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetContent returns the Content field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetContent() string { - if r == nil || r.Content == nil { - return "" - } - return *r.Content -} - -// GetDownloadURL returns the DownloadURL field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetDownloadURL() string { - if r == nil || r.DownloadURL == nil { - return "" - } - return *r.DownloadURL -} - -// GetEncoding returns the Encoding field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetEncoding() string { - if r == nil || r.Encoding == nil { - return "" - } - return *r.Encoding -} - -// GetGitURL returns the GitURL field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetGitURL() string { - if r == nil || r.GitURL == nil { - return "" - } - return *r.GitURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetLicense returns the License field. -func (r *RepositoryLicense) GetLicense() *License { - if r == nil { - return nil - } - return r.License -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetName() string { - if r == nil || r.Name == nil { - return "" - } - return *r.Name -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetPath() string { - if r == nil || r.Path == nil { - return "" - } - return *r.Path -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetSHA() string { - if r == nil || r.SHA == nil { - return "" - } - return *r.SHA -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetSize() int { - if r == nil || r.Size == nil { - return 0 - } - return *r.Size -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetType() string { - if r == nil || r.Type == nil { - return "" - } - return *r.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetBase returns the Base field if it's non-nil, zero value otherwise. -func (r *RepositoryMergeRequest) GetBase() string { - if r == nil || r.Base == nil { - return "" - } - return *r.Base -} - -// GetCommitMessage returns the CommitMessage field if it's non-nil, zero value otherwise. -func (r *RepositoryMergeRequest) GetCommitMessage() string { - if r == nil || r.CommitMessage == nil { - return "" - } - return *r.CommitMessage -} - -// GetHead returns the Head field if it's non-nil, zero value otherwise. -func (r *RepositoryMergeRequest) GetHead() string { - if r == nil || r.Head == nil { - return "" - } - return *r.Head -} - -// GetPermission returns the Permission field if it's non-nil, zero value otherwise. -func (r *RepositoryPermissionLevel) GetPermission() string { - if r == nil || r.Permission == nil { - return "" - } - return *r.Permission -} - -// GetUser returns the User field. -func (r *RepositoryPermissionLevel) GetUser() *User { - if r == nil { - return nil - } - return r.User -} - -// GetAssetsURL returns the AssetsURL field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetAssetsURL() string { - if r == nil || r.AssetsURL == nil { - return "" - } - return *r.AssetsURL -} - -// GetAuthor returns the Author field. -func (r *RepositoryRelease) GetAuthor() *User { - if r == nil { - return nil - } - return r.Author -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetBody() string { - if r == nil || r.Body == nil { - return "" - } - return *r.Body -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetCreatedAt() Timestamp { - if r == nil || r.CreatedAt == nil { - return Timestamp{} - } - return *r.CreatedAt -} - -// GetDraft returns the Draft field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetDraft() bool { - if r == nil || r.Draft == nil { - return false - } - return *r.Draft -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetID() int64 { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetName() string { - if r == nil || r.Name == nil { - return "" - } - return *r.Name -} - -// GetPrerelease returns the Prerelease field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetPrerelease() bool { - if r == nil || r.Prerelease == nil { - return false - } - return *r.Prerelease -} - -// GetPublishedAt returns the PublishedAt field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetPublishedAt() Timestamp { - if r == nil || r.PublishedAt == nil { - return Timestamp{} - } - return *r.PublishedAt -} - -// GetTagName returns the TagName field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetTagName() string { - if r == nil || r.TagName == nil { - return "" - } - return *r.TagName -} - -// GetTarballURL returns the TarballURL field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetTarballURL() string { - if r == nil || r.TarballURL == nil { - return "" - } - return *r.TarballURL -} - -// GetTargetCommitish returns the TargetCommitish field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetTargetCommitish() string { - if r == nil || r.TargetCommitish == nil { - return "" - } - return *r.TargetCommitish -} - -// GetUploadURL returns the UploadURL field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetUploadURL() string { - if r == nil || r.UploadURL == nil { - return "" - } - return *r.UploadURL -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetZipballURL returns the ZipballURL field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetZipballURL() string { - if r == nil || r.ZipballURL == nil { - return "" - } - return *r.ZipballURL -} - -// GetCommit returns the Commit field. -func (r *RepositoryTag) GetCommit() *Commit { - if r == nil { - return nil - } - return r.Commit -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (r *RepositoryTag) GetName() string { - if r == nil || r.Name == nil { - return "" - } - return *r.Name -} - -// GetTarballURL returns the TarballURL field if it's non-nil, zero value otherwise. -func (r *RepositoryTag) GetTarballURL() string { - if r == nil || r.TarballURL == nil { - return "" - } - return *r.TarballURL -} - -// GetZipballURL returns the ZipballURL field if it's non-nil, zero value otherwise. -func (r *RepositoryTag) GetZipballURL() string { - if r == nil || r.ZipballURL == nil { - return "" - } - return *r.ZipballURL -} - -// GetForkRepos returns the ForkRepos field if it's non-nil, zero value otherwise. -func (r *RepoStats) GetForkRepos() int { - if r == nil || r.ForkRepos == nil { - return 0 - } - return *r.ForkRepos -} - -// GetOrgRepos returns the OrgRepos field if it's non-nil, zero value otherwise. -func (r *RepoStats) GetOrgRepos() int { - if r == nil || r.OrgRepos == nil { - return 0 - } - return *r.OrgRepos -} - -// GetRootRepos returns the RootRepos field if it's non-nil, zero value otherwise. -func (r *RepoStats) GetRootRepos() int { - if r == nil || r.RootRepos == nil { - return 0 - } - return *r.RootRepos -} - -// GetTotalPushes returns the TotalPushes field if it's non-nil, zero value otherwise. -func (r *RepoStats) GetTotalPushes() int { - if r == nil || r.TotalPushes == nil { - return 0 - } - return *r.TotalPushes -} - -// GetTotalRepos returns the TotalRepos field if it's non-nil, zero value otherwise. -func (r *RepoStats) GetTotalRepos() int { - if r == nil || r.TotalRepos == nil { - return 0 - } - return *r.TotalRepos -} - -// GetTotalWikis returns the TotalWikis field if it's non-nil, zero value otherwise. -func (r *RepoStats) GetTotalWikis() int { - if r == nil || r.TotalWikis == nil { - return 0 - } - return *r.TotalWikis -} - -// GetContext returns the Context field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetContext() string { - if r == nil || r.Context == nil { - return "" - } - return *r.Context -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetCreatedAt() time.Time { - if r == nil || r.CreatedAt == nil { - return time.Time{} - } - return *r.CreatedAt -} - -// GetCreator returns the Creator field. -func (r *RepoStatus) GetCreator() *User { - if r == nil { - return nil - } - return r.Creator -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetDescription() string { - if r == nil || r.Description == nil { - return "" - } - return *r.Description -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetID() int64 { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetState() string { - if r == nil || r.State == nil { - return "" - } - return *r.State -} - -// GetTargetURL returns the TargetURL field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetTargetURL() string { - if r == nil || r.TargetURL == nil { - return "" - } - return *r.TargetURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetUpdatedAt() time.Time { - if r == nil || r.UpdatedAt == nil { - return time.Time{} - } - return *r.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (s *ServiceHook) GetName() string { - if s == nil || s.Name == nil { - return "" - } - return *s.Name -} - -// GetPayload returns the Payload field if it's non-nil, zero value otherwise. -func (s *SignatureVerification) GetPayload() string { - if s == nil || s.Payload == nil { - return "" - } - return *s.Payload -} - -// GetReason returns the Reason field if it's non-nil, zero value otherwise. -func (s *SignatureVerification) GetReason() string { - if s == nil || s.Reason == nil { - return "" - } - return *s.Reason -} - -// GetSignature returns the Signature field if it's non-nil, zero value otherwise. -func (s *SignatureVerification) GetSignature() string { - if s == nil || s.Signature == nil { - return "" - } - return *s.Signature -} - -// GetVerified returns the Verified field if it's non-nil, zero value otherwise. -func (s *SignatureVerification) GetVerified() bool { - if s == nil || s.Verified == nil { - return false - } - return *s.Verified -} - -// GetActor returns the Actor field. -func (s *Source) GetActor() *User { - if s == nil { - return nil - } - return s.Actor -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (s *Source) GetID() int64 { - if s == nil || s.ID == nil { - return 0 - } - return *s.ID -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (s *Source) GetURL() string { - if s == nil || s.URL == nil { - return "" - } - return *s.URL -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetEmail() string { - if s == nil || s.Email == nil { - return "" - } - return *s.Email -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetID() int64 { - if s == nil || s.ID == nil { - return 0 - } - return *s.ID -} - -// GetImportURL returns the ImportURL field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetImportURL() string { - if s == nil || s.ImportURL == nil { - return "" - } - return *s.ImportURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetName() string { - if s == nil || s.Name == nil { - return "" - } - return *s.Name -} - -// GetRemoteID returns the RemoteID field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetRemoteID() string { - if s == nil || s.RemoteID == nil { - return "" - } - return *s.RemoteID -} - -// GetRemoteName returns the RemoteName field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetRemoteName() string { - if s == nil || s.RemoteName == nil { - return "" - } - return *s.RemoteName -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetURL() string { - if s == nil || s.URL == nil { - return "" - } - return *s.URL -} - -// GetStarredAt returns the StarredAt field if it's non-nil, zero value otherwise. -func (s *Stargazer) GetStarredAt() Timestamp { - if s == nil || s.StarredAt == nil { - return Timestamp{} - } - return *s.StarredAt -} - -// GetUser returns the User field. -func (s *Stargazer) GetUser() *User { - if s == nil { - return nil - } - return s.User -} - -// GetRepository returns the Repository field. -func (s *StarredRepository) GetRepository() *Repository { - if s == nil { - return nil - } - return s.Repository -} - -// GetStarredAt returns the StarredAt field if it's non-nil, zero value otherwise. -func (s *StarredRepository) GetStarredAt() Timestamp { - if s == nil || s.StarredAt == nil { - return Timestamp{} - } - return *s.StarredAt -} - -// GetCommit returns the Commit field. -func (s *StatusEvent) GetCommit() *RepositoryCommit { - if s == nil { - return nil - } - return s.Commit -} - -// GetContext returns the Context field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetContext() string { - if s == nil || s.Context == nil { - return "" - } - return *s.Context -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetCreatedAt() Timestamp { - if s == nil || s.CreatedAt == nil { - return Timestamp{} - } - return *s.CreatedAt -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetDescription() string { - if s == nil || s.Description == nil { - return "" - } - return *s.Description -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetID() int64 { - if s == nil || s.ID == nil { - return 0 - } - return *s.ID -} - -// GetInstallation returns the Installation field. -func (s *StatusEvent) GetInstallation() *Installation { - if s == nil { - return nil - } - return s.Installation -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetName() string { - if s == nil || s.Name == nil { - return "" - } - return *s.Name -} - -// GetRepo returns the Repo field. -func (s *StatusEvent) GetRepo() *Repository { - if s == nil { - return nil - } - return s.Repo -} - -// GetSender returns the Sender field. -func (s *StatusEvent) GetSender() *User { - if s == nil { - return nil - } - return s.Sender -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetSHA() string { - if s == nil || s.SHA == nil { - return "" - } - return *s.SHA -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetState() string { - if s == nil || s.State == nil { - return "" - } - return *s.State -} - -// GetTargetURL returns the TargetURL field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetTargetURL() string { - if s == nil || s.TargetURL == nil { - return "" - } - return *s.TargetURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetUpdatedAt() Timestamp { - if s == nil || s.UpdatedAt == nil { - return Timestamp{} - } - return *s.UpdatedAt -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (s *Subscription) GetCreatedAt() Timestamp { - if s == nil || s.CreatedAt == nil { - return Timestamp{} - } - return *s.CreatedAt -} - -// GetIgnored returns the Ignored field if it's non-nil, zero value otherwise. -func (s *Subscription) GetIgnored() bool { - if s == nil || s.Ignored == nil { - return false - } - return *s.Ignored -} - -// GetReason returns the Reason field if it's non-nil, zero value otherwise. -func (s *Subscription) GetReason() string { - if s == nil || s.Reason == nil { - return "" - } - return *s.Reason -} - -// GetRepositoryURL returns the RepositoryURL field if it's non-nil, zero value otherwise. -func (s *Subscription) GetRepositoryURL() string { - if s == nil || s.RepositoryURL == nil { - return "" - } - return *s.RepositoryURL -} - -// GetSubscribed returns the Subscribed field if it's non-nil, zero value otherwise. -func (s *Subscription) GetSubscribed() bool { - if s == nil || s.Subscribed == nil { - return false - } - return *s.Subscribed -} - -// GetThreadURL returns the ThreadURL field if it's non-nil, zero value otherwise. -func (s *Subscription) GetThreadURL() string { - if s == nil || s.ThreadURL == nil { - return "" - } - return *s.ThreadURL -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (s *Subscription) GetURL() string { - if s == nil || s.URL == nil { - return "" - } - return *s.URL -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (t *Tag) GetMessage() string { - if t == nil || t.Message == nil { - return "" - } - return *t.Message -} - -// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. -func (t *Tag) GetNodeID() string { - if t == nil || t.NodeID == nil { - return "" - } - return *t.NodeID -} - -// GetObject returns the Object field. -func (t *Tag) GetObject() *GitObject { - if t == nil { - return nil - } - return t.Object -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (t *Tag) GetSHA() string { - if t == nil || t.SHA == nil { - return "" - } - return *t.SHA -} - -// GetTag returns the Tag field if it's non-nil, zero value otherwise. -func (t *Tag) GetTag() string { - if t == nil || t.Tag == nil { - return "" - } - return *t.Tag -} - -// GetTagger returns the Tagger field. -func (t *Tag) GetTagger() *CommitAuthor { - if t == nil { - return nil - } - return t.Tagger -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (t *Tag) GetURL() string { - if t == nil || t.URL == nil { - return "" - } - return *t.URL -} - -// GetVerification returns the Verification field. -func (t *Tag) GetVerification() *SignatureVerification { - if t == nil { - return nil - } - return t.Verification -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (t *Team) GetDescription() string { - if t == nil || t.Description == nil { - return "" - } - return *t.Description -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (t *Team) GetID() int64 { - if t == nil || t.ID == nil { - return 0 - } - return *t.ID -} - -// GetLDAPDN returns the LDAPDN field if it's non-nil, zero value otherwise. -func (t *Team) GetLDAPDN() string { - if t == nil || t.LDAPDN == nil { - return "" - } - return *t.LDAPDN -} - -// GetMembersCount returns the MembersCount field if it's non-nil, zero value otherwise. -func (t *Team) GetMembersCount() int { - if t == nil || t.MembersCount == nil { - return 0 - } - return *t.MembersCount -} - -// GetMembersURL returns the MembersURL field if it's non-nil, zero value otherwise. -func (t *Team) GetMembersURL() string { - if t == nil || t.MembersURL == nil { - return "" - } - return *t.MembersURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (t *Team) GetName() string { - if t == nil || t.Name == nil { - return "" - } - return *t.Name -} - -// GetOrganization returns the Organization field. -func (t *Team) GetOrganization() *Organization { - if t == nil { - return nil - } - return t.Organization -} - -// GetParent returns the Parent field. -func (t *Team) GetParent() *Team { - if t == nil { - return nil - } - return t.Parent -} - -// GetPermission returns the Permission field if it's non-nil, zero value otherwise. -func (t *Team) GetPermission() string { - if t == nil || t.Permission == nil { - return "" - } - return *t.Permission -} - -// GetPrivacy returns the Privacy field if it's non-nil, zero value otherwise. -func (t *Team) GetPrivacy() string { - if t == nil || t.Privacy == nil { - return "" - } - return *t.Privacy -} - -// GetReposCount returns the ReposCount field if it's non-nil, zero value otherwise. -func (t *Team) GetReposCount() int { - if t == nil || t.ReposCount == nil { - return 0 - } - return *t.ReposCount -} - -// GetRepositoriesURL returns the RepositoriesURL field if it's non-nil, zero value otherwise. -func (t *Team) GetRepositoriesURL() string { - if t == nil || t.RepositoriesURL == nil { - return "" - } - return *t.RepositoriesURL -} - -// GetSlug returns the Slug field if it's non-nil, zero value otherwise. -func (t *Team) GetSlug() string { - if t == nil || t.Slug == nil { - return "" - } - return *t.Slug -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (t *Team) GetURL() string { - if t == nil || t.URL == nil { - return "" - } - return *t.URL -} - -// GetInstallation returns the Installation field. -func (t *TeamAddEvent) GetInstallation() *Installation { - if t == nil { - return nil - } - return t.Installation -} - -// GetOrg returns the Org field. -func (t *TeamAddEvent) GetOrg() *Organization { - if t == nil { - return nil - } - return t.Org -} - -// GetRepo returns the Repo field. -func (t *TeamAddEvent) GetRepo() *Repository { - if t == nil { - return nil - } - return t.Repo -} - -// GetSender returns the Sender field. -func (t *TeamAddEvent) GetSender() *User { - if t == nil { - return nil - } - return t.Sender -} - -// GetTeam returns the Team field. -func (t *TeamAddEvent) GetTeam() *Team { - if t == nil { - return nil - } - return t.Team -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (t *TeamEvent) GetAction() string { - if t == nil || t.Action == nil { - return "" - } - return *t.Action -} - -// GetChanges returns the Changes field. -func (t *TeamEvent) GetChanges() *TeamChange { - if t == nil { - return nil - } - return t.Changes -} - -// GetInstallation returns the Installation field. -func (t *TeamEvent) GetInstallation() *Installation { - if t == nil { - return nil - } - return t.Installation -} - -// GetOrg returns the Org field. -func (t *TeamEvent) GetOrg() *Organization { - if t == nil { - return nil - } - return t.Org -} - -// GetRepo returns the Repo field. -func (t *TeamEvent) GetRepo() *Repository { - if t == nil { - return nil - } - return t.Repo -} - -// GetSender returns the Sender field. -func (t *TeamEvent) GetSender() *User { - if t == nil { - return nil - } - return t.Sender -} - -// GetTeam returns the Team field. -func (t *TeamEvent) GetTeam() *Team { - if t == nil { - return nil - } - return t.Team -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetDescription() string { - if t == nil || t.Description == nil { - return "" - } - return *t.Description -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetID() int64 { - if t == nil || t.ID == nil { - return 0 - } - return *t.ID -} - -// GetLDAPDN returns the LDAPDN field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetLDAPDN() string { - if t == nil || t.LDAPDN == nil { - return "" - } - return *t.LDAPDN -} - -// GetMembersURL returns the MembersURL field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetMembersURL() string { - if t == nil || t.MembersURL == nil { - return "" - } - return *t.MembersURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetName() string { - if t == nil || t.Name == nil { - return "" - } - return *t.Name -} - -// GetPermission returns the Permission field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetPermission() string { - if t == nil || t.Permission == nil { - return "" - } - return *t.Permission -} - -// GetPrivacy returns the Privacy field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetPrivacy() string { - if t == nil || t.Privacy == nil { - return "" - } - return *t.Privacy -} - -// GetRepositoriesURL returns the RepositoriesURL field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetRepositoriesURL() string { - if t == nil || t.RepositoriesURL == nil { - return "" - } - return *t.RepositoriesURL -} - -// GetSlug returns the Slug field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetSlug() string { - if t == nil || t.Slug == nil { - return "" - } - return *t.Slug -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetURL() string { - if t == nil || t.URL == nil { - return "" - } - return *t.URL -} - -// GetFragment returns the Fragment field if it's non-nil, zero value otherwise. -func (t *TextMatch) GetFragment() string { - if t == nil || t.Fragment == nil { - return "" - } - return *t.Fragment -} - -// GetObjectType returns the ObjectType field if it's non-nil, zero value otherwise. -func (t *TextMatch) GetObjectType() string { - if t == nil || t.ObjectType == nil { - return "" - } - return *t.ObjectType -} - -// GetObjectURL returns the ObjectURL field if it's non-nil, zero value otherwise. -func (t *TextMatch) GetObjectURL() string { - if t == nil || t.ObjectURL == nil { - return "" - } - return *t.ObjectURL -} - -// GetProperty returns the Property field if it's non-nil, zero value otherwise. -func (t *TextMatch) GetProperty() string { - if t == nil || t.Property == nil { - return "" - } - return *t.Property -} - -// GetActor returns the Actor field. -func (t *Timeline) GetActor() *User { - if t == nil { - return nil - } - return t.Actor -} - -// GetAssignee returns the Assignee field. -func (t *Timeline) GetAssignee() *User { - if t == nil { - return nil - } - return t.Assignee -} - -// GetCommitID returns the CommitID field if it's non-nil, zero value otherwise. -func (t *Timeline) GetCommitID() string { - if t == nil || t.CommitID == nil { - return "" - } - return *t.CommitID -} - -// GetCommitURL returns the CommitURL field if it's non-nil, zero value otherwise. -func (t *Timeline) GetCommitURL() string { - if t == nil || t.CommitURL == nil { - return "" - } - return *t.CommitURL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (t *Timeline) GetCreatedAt() time.Time { - if t == nil || t.CreatedAt == nil { - return time.Time{} - } - return *t.CreatedAt -} - -// GetEvent returns the Event field if it's non-nil, zero value otherwise. -func (t *Timeline) GetEvent() string { - if t == nil || t.Event == nil { - return "" - } - return *t.Event -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (t *Timeline) GetID() int64 { - if t == nil || t.ID == nil { - return 0 - } - return *t.ID -} - -// GetLabel returns the Label field. -func (t *Timeline) GetLabel() *Label { - if t == nil { - return nil - } - return t.Label -} - -// GetMilestone returns the Milestone field. -func (t *Timeline) GetMilestone() *Milestone { - if t == nil { - return nil - } - return t.Milestone -} - -// GetRename returns the Rename field. -func (t *Timeline) GetRename() *Rename { - if t == nil { - return nil - } - return t.Rename -} - -// GetSource returns the Source field. -func (t *Timeline) GetSource() *Source { - if t == nil { - return nil - } - return t.Source -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (t *Timeline) GetURL() string { - if t == nil || t.URL == nil { - return "" - } - return *t.URL -} - -// GetCount returns the Count field if it's non-nil, zero value otherwise. -func (t *TrafficClones) GetCount() int { - if t == nil || t.Count == nil { - return 0 - } - return *t.Count -} - -// GetUniques returns the Uniques field if it's non-nil, zero value otherwise. -func (t *TrafficClones) GetUniques() int { - if t == nil || t.Uniques == nil { - return 0 - } - return *t.Uniques -} - -// GetCount returns the Count field if it's non-nil, zero value otherwise. -func (t *TrafficData) GetCount() int { - if t == nil || t.Count == nil { - return 0 - } - return *t.Count -} - -// GetTimestamp returns the Timestamp field if it's non-nil, zero value otherwise. -func (t *TrafficData) GetTimestamp() Timestamp { - if t == nil || t.Timestamp == nil { - return Timestamp{} - } - return *t.Timestamp -} - -// GetUniques returns the Uniques field if it's non-nil, zero value otherwise. -func (t *TrafficData) GetUniques() int { - if t == nil || t.Uniques == nil { - return 0 - } - return *t.Uniques -} - -// GetCount returns the Count field if it's non-nil, zero value otherwise. -func (t *TrafficPath) GetCount() int { - if t == nil || t.Count == nil { - return 0 - } - return *t.Count -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (t *TrafficPath) GetPath() string { - if t == nil || t.Path == nil { - return "" - } - return *t.Path -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (t *TrafficPath) GetTitle() string { - if t == nil || t.Title == nil { - return "" - } - return *t.Title -} - -// GetUniques returns the Uniques field if it's non-nil, zero value otherwise. -func (t *TrafficPath) GetUniques() int { - if t == nil || t.Uniques == nil { - return 0 - } - return *t.Uniques -} - -// GetCount returns the Count field if it's non-nil, zero value otherwise. -func (t *TrafficReferrer) GetCount() int { - if t == nil || t.Count == nil { - return 0 - } - return *t.Count -} - -// GetReferrer returns the Referrer field if it's non-nil, zero value otherwise. -func (t *TrafficReferrer) GetReferrer() string { - if t == nil || t.Referrer == nil { - return "" - } - return *t.Referrer -} - -// GetUniques returns the Uniques field if it's non-nil, zero value otherwise. -func (t *TrafficReferrer) GetUniques() int { - if t == nil || t.Uniques == nil { - return 0 - } - return *t.Uniques -} - -// GetCount returns the Count field if it's non-nil, zero value otherwise. -func (t *TrafficViews) GetCount() int { - if t == nil || t.Count == nil { - return 0 - } - return *t.Count -} - -// GetUniques returns the Uniques field if it's non-nil, zero value otherwise. -func (t *TrafficViews) GetUniques() int { - if t == nil || t.Uniques == nil { - return 0 - } - return *t.Uniques -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (t *Tree) GetSHA() string { - if t == nil || t.SHA == nil { - return "" - } - return *t.SHA -} - -// GetContent returns the Content field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetContent() string { - if t == nil || t.Content == nil { - return "" - } - return *t.Content -} - -// GetMode returns the Mode field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetMode() string { - if t == nil || t.Mode == nil { - return "" - } - return *t.Mode -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetPath() string { - if t == nil || t.Path == nil { - return "" - } - return *t.Path -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetSHA() string { - if t == nil || t.SHA == nil { - return "" - } - return *t.SHA -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetSize() int { - if t == nil || t.Size == nil { - return 0 - } - return *t.Size -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetType() string { - if t == nil || t.Type == nil { - return "" - } - return *t.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetURL() string { - if t == nil || t.URL == nil { - return "" - } - return *t.URL -} - -// GetAvatarURL returns the AvatarURL field if it's non-nil, zero value otherwise. -func (u *User) GetAvatarURL() string { - if u == nil || u.AvatarURL == nil { - return "" - } - return *u.AvatarURL -} - -// GetBio returns the Bio field if it's non-nil, zero value otherwise. -func (u *User) GetBio() string { - if u == nil || u.Bio == nil { - return "" - } - return *u.Bio -} - -// GetBlog returns the Blog field if it's non-nil, zero value otherwise. -func (u *User) GetBlog() string { - if u == nil || u.Blog == nil { - return "" - } - return *u.Blog -} - -// GetCollaborators returns the Collaborators field if it's non-nil, zero value otherwise. -func (u *User) GetCollaborators() int { - if u == nil || u.Collaborators == nil { - return 0 - } - return *u.Collaborators -} - -// GetCompany returns the Company field if it's non-nil, zero value otherwise. -func (u *User) GetCompany() string { - if u == nil || u.Company == nil { - return "" - } - return *u.Company -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (u *User) GetCreatedAt() Timestamp { - if u == nil || u.CreatedAt == nil { - return Timestamp{} - } - return *u.CreatedAt -} - -// GetDiskUsage returns the DiskUsage field if it's non-nil, zero value otherwise. -func (u *User) GetDiskUsage() int { - if u == nil || u.DiskUsage == nil { - return 0 - } - return *u.DiskUsage -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (u *User) GetEmail() string { - if u == nil || u.Email == nil { - return "" - } - return *u.Email -} - -// GetEventsURL returns the EventsURL field if it's non-nil, zero value otherwise. -func (u *User) GetEventsURL() string { - if u == nil || u.EventsURL == nil { - return "" - } - return *u.EventsURL -} - -// GetFollowers returns the Followers field if it's non-nil, zero value otherwise. -func (u *User) GetFollowers() int { - if u == nil || u.Followers == nil { - return 0 - } - return *u.Followers -} - -// GetFollowersURL returns the FollowersURL field if it's non-nil, zero value otherwise. -func (u *User) GetFollowersURL() string { - if u == nil || u.FollowersURL == nil { - return "" - } - return *u.FollowersURL -} - -// GetFollowing returns the Following field if it's non-nil, zero value otherwise. -func (u *User) GetFollowing() int { - if u == nil || u.Following == nil { - return 0 - } - return *u.Following -} - -// GetFollowingURL returns the FollowingURL field if it's non-nil, zero value otherwise. -func (u *User) GetFollowingURL() string { - if u == nil || u.FollowingURL == nil { - return "" - } - return *u.FollowingURL -} - -// GetGistsURL returns the GistsURL field if it's non-nil, zero value otherwise. -func (u *User) GetGistsURL() string { - if u == nil || u.GistsURL == nil { - return "" - } - return *u.GistsURL -} - -// GetGravatarID returns the GravatarID field if it's non-nil, zero value otherwise. -func (u *User) GetGravatarID() string { - if u == nil || u.GravatarID == nil { - return "" - } - return *u.GravatarID -} - -// GetHireable returns the Hireable field if it's non-nil, zero value otherwise. -func (u *User) GetHireable() bool { - if u == nil || u.Hireable == nil { - return false - } - return *u.Hireable -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (u *User) GetHTMLURL() string { - if u == nil || u.HTMLURL == nil { - return "" - } - return *u.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (u *User) GetID() int64 { - if u == nil || u.ID == nil { - return 0 - } - return *u.ID -} - -// GetLocation returns the Location field if it's non-nil, zero value otherwise. -func (u *User) GetLocation() string { - if u == nil || u.Location == nil { - return "" - } - return *u.Location -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (u *User) GetLogin() string { - if u == nil || u.Login == nil { - return "" - } - return *u.Login -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (u *User) GetName() string { - if u == nil || u.Name == nil { - return "" - } - return *u.Name -} - -// GetOrganizationsURL returns the OrganizationsURL field if it's non-nil, zero value otherwise. -func (u *User) GetOrganizationsURL() string { - if u == nil || u.OrganizationsURL == nil { - return "" - } - return *u.OrganizationsURL -} - -// GetOwnedPrivateRepos returns the OwnedPrivateRepos field if it's non-nil, zero value otherwise. -func (u *User) GetOwnedPrivateRepos() int { - if u == nil || u.OwnedPrivateRepos == nil { - return 0 - } - return *u.OwnedPrivateRepos -} - -// GetPermissions returns the Permissions field if it's non-nil, zero value otherwise. -func (u *User) GetPermissions() map[string]bool { - if u == nil || u.Permissions == nil { - return map[string]bool{} - } - return *u.Permissions -} - -// GetPlan returns the Plan field. -func (u *User) GetPlan() *Plan { - if u == nil { - return nil - } - return u.Plan -} - -// GetPrivateGists returns the PrivateGists field if it's non-nil, zero value otherwise. -func (u *User) GetPrivateGists() int { - if u == nil || u.PrivateGists == nil { - return 0 - } - return *u.PrivateGists -} - -// GetPublicGists returns the PublicGists field if it's non-nil, zero value otherwise. -func (u *User) GetPublicGists() int { - if u == nil || u.PublicGists == nil { - return 0 - } - return *u.PublicGists -} - -// GetPublicRepos returns the PublicRepos field if it's non-nil, zero value otherwise. -func (u *User) GetPublicRepos() int { - if u == nil || u.PublicRepos == nil { - return 0 - } - return *u.PublicRepos -} - -// GetReceivedEventsURL returns the ReceivedEventsURL field if it's non-nil, zero value otherwise. -func (u *User) GetReceivedEventsURL() string { - if u == nil || u.ReceivedEventsURL == nil { - return "" - } - return *u.ReceivedEventsURL -} - -// GetReposURL returns the ReposURL field if it's non-nil, zero value otherwise. -func (u *User) GetReposURL() string { - if u == nil || u.ReposURL == nil { - return "" - } - return *u.ReposURL -} - -// GetSiteAdmin returns the SiteAdmin field if it's non-nil, zero value otherwise. -func (u *User) GetSiteAdmin() bool { - if u == nil || u.SiteAdmin == nil { - return false - } - return *u.SiteAdmin -} - -// GetStarredURL returns the StarredURL field if it's non-nil, zero value otherwise. -func (u *User) GetStarredURL() string { - if u == nil || u.StarredURL == nil { - return "" - } - return *u.StarredURL -} - -// GetSubscriptionsURL returns the SubscriptionsURL field if it's non-nil, zero value otherwise. -func (u *User) GetSubscriptionsURL() string { - if u == nil || u.SubscriptionsURL == nil { - return "" - } - return *u.SubscriptionsURL -} - -// GetSuspendedAt returns the SuspendedAt field if it's non-nil, zero value otherwise. -func (u *User) GetSuspendedAt() Timestamp { - if u == nil || u.SuspendedAt == nil { - return Timestamp{} - } - return *u.SuspendedAt -} - -// GetTotalPrivateRepos returns the TotalPrivateRepos field if it's non-nil, zero value otherwise. -func (u *User) GetTotalPrivateRepos() int { - if u == nil || u.TotalPrivateRepos == nil { - return 0 - } - return *u.TotalPrivateRepos -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (u *User) GetType() string { - if u == nil || u.Type == nil { - return "" - } - return *u.Type -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (u *User) GetUpdatedAt() Timestamp { - if u == nil || u.UpdatedAt == nil { - return Timestamp{} - } - return *u.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (u *User) GetURL() string { - if u == nil || u.URL == nil { - return "" - } - return *u.URL -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (u *UserEmail) GetEmail() string { - if u == nil || u.Email == nil { - return "" - } - return *u.Email -} - -// GetPrimary returns the Primary field if it's non-nil, zero value otherwise. -func (u *UserEmail) GetPrimary() bool { - if u == nil || u.Primary == nil { - return false - } - return *u.Primary -} - -// GetVerified returns the Verified field if it's non-nil, zero value otherwise. -func (u *UserEmail) GetVerified() bool { - if u == nil || u.Verified == nil { - return false - } - return *u.Verified -} - -// GetAvatarURL returns the AvatarURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetAvatarURL() string { - if u == nil || u.AvatarURL == nil { - return "" - } - return *u.AvatarURL -} - -// GetEventsURL returns the EventsURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetEventsURL() string { - if u == nil || u.EventsURL == nil { - return "" - } - return *u.EventsURL -} - -// GetFollowersURL returns the FollowersURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetFollowersURL() string { - if u == nil || u.FollowersURL == nil { - return "" - } - return *u.FollowersURL -} - -// GetFollowingURL returns the FollowingURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetFollowingURL() string { - if u == nil || u.FollowingURL == nil { - return "" - } - return *u.FollowingURL -} - -// GetGistsURL returns the GistsURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetGistsURL() string { - if u == nil || u.GistsURL == nil { - return "" - } - return *u.GistsURL -} - -// GetGravatarID returns the GravatarID field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetGravatarID() string { - if u == nil || u.GravatarID == nil { - return "" - } - return *u.GravatarID -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetID() int64 { - if u == nil || u.ID == nil { - return 0 - } - return *u.ID -} - -// GetLDAPDN returns the LDAPDN field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetLDAPDN() string { - if u == nil || u.LDAPDN == nil { - return "" - } - return *u.LDAPDN -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetLogin() string { - if u == nil || u.Login == nil { - return "" - } - return *u.Login -} - -// GetOrganizationsURL returns the OrganizationsURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetOrganizationsURL() string { - if u == nil || u.OrganizationsURL == nil { - return "" - } - return *u.OrganizationsURL -} - -// GetReceivedEventsURL returns the ReceivedEventsURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetReceivedEventsURL() string { - if u == nil || u.ReceivedEventsURL == nil { - return "" - } - return *u.ReceivedEventsURL -} - -// GetReposURL returns the ReposURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetReposURL() string { - if u == nil || u.ReposURL == nil { - return "" - } - return *u.ReposURL -} - -// GetSiteAdmin returns the SiteAdmin field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetSiteAdmin() bool { - if u == nil || u.SiteAdmin == nil { - return false - } - return *u.SiteAdmin -} - -// GetStarredURL returns the StarredURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetStarredURL() string { - if u == nil || u.StarredURL == nil { - return "" - } - return *u.StarredURL -} - -// GetSubscriptionsURL returns the SubscriptionsURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetSubscriptionsURL() string { - if u == nil || u.SubscriptionsURL == nil { - return "" - } - return *u.SubscriptionsURL -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetType() string { - if u == nil || u.Type == nil { - return "" - } - return *u.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetURL() string { - if u == nil || u.URL == nil { - return "" - } - return *u.URL -} - -// GetIncompleteResults returns the IncompleteResults field if it's non-nil, zero value otherwise. -func (u *UsersSearchResult) GetIncompleteResults() bool { - if u == nil || u.IncompleteResults == nil { - return false - } - return *u.IncompleteResults -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (u *UsersSearchResult) GetTotal() int { - if u == nil || u.Total == nil { - return 0 - } - return *u.Total -} - -// GetAdminUsers returns the AdminUsers field if it's non-nil, zero value otherwise. -func (u *UserStats) GetAdminUsers() int { - if u == nil || u.AdminUsers == nil { - return 0 - } - return *u.AdminUsers -} - -// GetSuspendedUsers returns the SuspendedUsers field if it's non-nil, zero value otherwise. -func (u *UserStats) GetSuspendedUsers() int { - if u == nil || u.SuspendedUsers == nil { - return 0 - } - return *u.SuspendedUsers -} - -// GetTotalUsers returns the TotalUsers field if it's non-nil, zero value otherwise. -func (u *UserStats) GetTotalUsers() int { - if u == nil || u.TotalUsers == nil { - return 0 - } - return *u.TotalUsers -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (w *WatchEvent) GetAction() string { - if w == nil || w.Action == nil { - return "" - } - return *w.Action -} - -// GetInstallation returns the Installation field. -func (w *WatchEvent) GetInstallation() *Installation { - if w == nil { - return nil - } - return w.Installation -} - -// GetRepo returns the Repo field. -func (w *WatchEvent) GetRepo() *Repository { - if w == nil { - return nil - } - return w.Repo -} - -// GetSender returns the Sender field. -func (w *WatchEvent) GetSender() *User { - if w == nil { - return nil - } - return w.Sender -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (w *WebHookAuthor) GetEmail() string { - if w == nil || w.Email == nil { - return "" - } - return *w.Email -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (w *WebHookAuthor) GetName() string { - if w == nil || w.Name == nil { - return "" - } - return *w.Name -} - -// GetUsername returns the Username field if it's non-nil, zero value otherwise. -func (w *WebHookAuthor) GetUsername() string { - if w == nil || w.Username == nil { - return "" - } - return *w.Username -} - -// GetAuthor returns the Author field. -func (w *WebHookCommit) GetAuthor() *WebHookAuthor { - if w == nil { - return nil - } - return w.Author -} - -// GetCommitter returns the Committer field. -func (w *WebHookCommit) GetCommitter() *WebHookAuthor { - if w == nil { - return nil - } - return w.Committer -} - -// GetDistinct returns the Distinct field if it's non-nil, zero value otherwise. -func (w *WebHookCommit) GetDistinct() bool { - if w == nil || w.Distinct == nil { - return false - } - return *w.Distinct -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (w *WebHookCommit) GetID() string { - if w == nil || w.ID == nil { - return "" - } - return *w.ID -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (w *WebHookCommit) GetMessage() string { - if w == nil || w.Message == nil { - return "" - } - return *w.Message -} - -// GetTimestamp returns the Timestamp field if it's non-nil, zero value otherwise. -func (w *WebHookCommit) GetTimestamp() time.Time { - if w == nil || w.Timestamp == nil { - return time.Time{} - } - return *w.Timestamp -} - -// GetAfter returns the After field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetAfter() string { - if w == nil || w.After == nil { - return "" - } - return *w.After -} - -// GetBefore returns the Before field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetBefore() string { - if w == nil || w.Before == nil { - return "" - } - return *w.Before -} - -// GetCompare returns the Compare field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetCompare() string { - if w == nil || w.Compare == nil { - return "" - } - return *w.Compare -} - -// GetCreated returns the Created field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetCreated() bool { - if w == nil || w.Created == nil { - return false - } - return *w.Created -} - -// GetDeleted returns the Deleted field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetDeleted() bool { - if w == nil || w.Deleted == nil { - return false - } - return *w.Deleted -} - -// GetForced returns the Forced field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetForced() bool { - if w == nil || w.Forced == nil { - return false - } - return *w.Forced -} - -// GetHeadCommit returns the HeadCommit field. -func (w *WebHookPayload) GetHeadCommit() *WebHookCommit { - if w == nil { - return nil - } - return w.HeadCommit -} - -// GetPusher returns the Pusher field. -func (w *WebHookPayload) GetPusher() *User { - if w == nil { - return nil - } - return w.Pusher -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetRef() string { - if w == nil || w.Ref == nil { - return "" - } - return *w.Ref -} - -// GetRepo returns the Repo field. -func (w *WebHookPayload) GetRepo() *Repository { - if w == nil { - return nil - } - return w.Repo -} - -// GetSender returns the Sender field. -func (w *WebHookPayload) GetSender() *User { - if w == nil { - return nil - } - return w.Sender -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (w *WeeklyCommitActivity) GetTotal() int { - if w == nil || w.Total == nil { - return 0 - } - return *w.Total -} - -// GetWeek returns the Week field if it's non-nil, zero value otherwise. -func (w *WeeklyCommitActivity) GetWeek() Timestamp { - if w == nil || w.Week == nil { - return Timestamp{} - } - return *w.Week -} - -// GetAdditions returns the Additions field if it's non-nil, zero value otherwise. -func (w *WeeklyStats) GetAdditions() int { - if w == nil || w.Additions == nil { - return 0 - } - return *w.Additions -} - -// GetCommits returns the Commits field if it's non-nil, zero value otherwise. -func (w *WeeklyStats) GetCommits() int { - if w == nil || w.Commits == nil { - return 0 - } - return *w.Commits -} - -// GetDeletions returns the Deletions field if it's non-nil, zero value otherwise. -func (w *WeeklyStats) GetDeletions() int { - if w == nil || w.Deletions == nil { - return 0 - } - return *w.Deletions -} - -// GetWeek returns the Week field if it's non-nil, zero value otherwise. -func (w *WeeklyStats) GetWeek() Timestamp { - if w == nil || w.Week == nil { - return Timestamp{} - } - return *w.Week -} diff --git a/vendor/github.com/google/go-github/github/github.go b/vendor/github.com/google/go-github/github/github.go deleted file mode 100644 index 082472260b1..00000000000 --- a/vendor/github.com/google/go-github/github/github.go +++ /dev/null @@ -1,980 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:generate go run gen-accessors.go - -package github - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "strconv" - "strings" - "sync" - "time" - - "github.com/google/go-querystring/query" -) - -const ( - libraryVersion = "15" - defaultBaseURL = "https://api.github.com/" - uploadBaseURL = "https://uploads.github.com/" - userAgent = "go-github/" + libraryVersion - - headerRateLimit = "X-RateLimit-Limit" - headerRateRemaining = "X-RateLimit-Remaining" - headerRateReset = "X-RateLimit-Reset" - headerOTP = "X-GitHub-OTP" - - mediaTypeV3 = "application/vnd.github.v3+json" - defaultMediaType = "application/octet-stream" - mediaTypeV3SHA = "application/vnd.github.v3.sha" - mediaTypeV3Diff = "application/vnd.github.v3.diff" - mediaTypeV3Patch = "application/vnd.github.v3.patch" - mediaTypeOrgPermissionRepo = "application/vnd.github.v3.repository+json" - - // Media Type values to access preview APIs - - // https://developer.github.com/changes/2015-03-09-licenses-api/ - mediaTypeLicensesPreview = "application/vnd.github.drax-preview+json" - - // https://developer.github.com/changes/2014-12-09-new-attributes-for-stars-api/ - mediaTypeStarringPreview = "application/vnd.github.v3.star+json" - - // https://developer.github.com/changes/2015-11-11-protected-branches-api/ - mediaTypeProtectedBranchesPreview = "application/vnd.github.loki-preview+json" - - // https://help.github.com/enterprise/2.4/admin/guides/migrations/exporting-the-github-com-organization-s-repositories/ - mediaTypeMigrationsPreview = "application/vnd.github.wyandotte-preview+json" - - // https://developer.github.com/changes/2016-04-06-deployment-and-deployment-status-enhancements/ - mediaTypeDeploymentStatusPreview = "application/vnd.github.ant-man-preview+json" - - // https://developer.github.com/changes/2016-02-19-source-import-preview-api/ - mediaTypeImportPreview = "application/vnd.github.barred-rock-preview" - - // https://developer.github.com/changes/2016-05-12-reactions-api-preview/ - mediaTypeReactionsPreview = "application/vnd.github.squirrel-girl-preview" - - // https://developer.github.com/changes/2016-04-04-git-signing-api-preview/ - mediaTypeGitSigningPreview = "application/vnd.github.cryptographer-preview+json" - - // https://developer.github.com/changes/2016-05-23-timeline-preview-api/ - mediaTypeTimelinePreview = "application/vnd.github.mockingbird-preview+json" - - // https://developer.github.com/changes/2016-06-14-repository-invitations/ - mediaTypeRepositoryInvitationsPreview = "application/vnd.github.swamp-thing-preview+json" - - // https://developer.github.com/changes/2016-07-06-github-pages-preiew-api/ - mediaTypePagesPreview = "application/vnd.github.mister-fantastic-preview+json" - - // https://developer.github.com/changes/2016-09-14-projects-api/ - mediaTypeProjectsPreview = "application/vnd.github.inertia-preview+json" - - // https://developer.github.com/changes/2016-09-14-Integrations-Early-Access/ - mediaTypeIntegrationPreview = "application/vnd.github.machine-man-preview+json" - - // https://developer.github.com/changes/2017-01-05-commit-search-api/ - mediaTypeCommitSearchPreview = "application/vnd.github.cloak-preview+json" - - // https://developer.github.com/changes/2017-02-28-user-blocking-apis-and-webhook/ - mediaTypeBlockUsersPreview = "application/vnd.github.giant-sentry-fist-preview+json" - - // https://developer.github.com/changes/2017-02-09-community-health/ - mediaTypeRepositoryCommunityHealthMetricsPreview = "application/vnd.github.black-panther-preview+json" - - // https://developer.github.com/changes/2017-05-23-coc-api/ - mediaTypeCodesOfConductPreview = "application/vnd.github.scarlet-witch-preview+json" - - // https://developer.github.com/changes/2017-07-17-update-topics-on-repositories/ - mediaTypeTopicsPreview = "application/vnd.github.mercy-preview+json" - - // https://developer.github.com/changes/2017-07-26-team-review-request-thor-preview/ - mediaTypeTeamReviewPreview = "application/vnd.github.thor-preview+json" - - // https://developer.github.com/v3/apps/marketplace/ - mediaTypeMarketplacePreview = "application/vnd.github.valkyrie-preview+json" - - // https://developer.github.com/changes/2017-08-30-preview-nested-teams/ - mediaTypeNestedTeamsPreview = "application/vnd.github.hellcat-preview+json" - - // https://developer.github.com/changes/2017-11-09-repository-transfer-api-preview/ - mediaTypeRepositoryTransferPreview = "application/vnd.github.nightshade-preview+json" - - // https://developer.github.com/changes/2017-12-19-graphql-node-id/ - mediaTypeGraphQLNodeIDPreview = "application/vnd.github.jean-grey-preview+json" -) - -// A Client manages communication with the GitHub API. -type Client struct { - clientMu sync.Mutex // clientMu protects the client during calls that modify the CheckRedirect func. - client *http.Client // HTTP client used to communicate with the API. - - // Base URL for API requests. Defaults to the public GitHub API, but can be - // set to a domain endpoint to use with GitHub Enterprise. BaseURL should - // always be specified with a trailing slash. - BaseURL *url.URL - - // Base URL for uploading files. - UploadURL *url.URL - - // User agent used when communicating with the GitHub API. - UserAgent string - - rateMu sync.Mutex - rateLimits [categories]Rate // Rate limits for the client as determined by the most recent API calls. - - common service // Reuse a single struct instead of allocating one for each service on the heap. - - // Services used for talking to different parts of the GitHub API. - Activity *ActivityService - Admin *AdminService - Apps *AppsService - Authorizations *AuthorizationsService - Gists *GistsService - Git *GitService - Gitignores *GitignoresService - Issues *IssuesService - Licenses *LicensesService - Marketplace *MarketplaceService - Migrations *MigrationService - Organizations *OrganizationsService - Projects *ProjectsService - PullRequests *PullRequestsService - Reactions *ReactionsService - Repositories *RepositoriesService - Search *SearchService - Users *UsersService -} - -type service struct { - client *Client -} - -// ListOptions specifies the optional parameters to various List methods that -// support pagination. -type ListOptions struct { - // For paginated result sets, page of results to retrieve. - Page int `url:"page,omitempty"` - - // For paginated result sets, the number of results to include per page. - PerPage int `url:"per_page,omitempty"` -} - -// UploadOptions specifies the parameters to methods that support uploads. -type UploadOptions struct { - Name string `url:"name,omitempty"` -} - -// RawType represents type of raw format of a request instead of JSON. -type RawType uint8 - -const ( - // Diff format. - Diff RawType = 1 + iota - // Patch format. - Patch -) - -// RawOptions specifies parameters when user wants to get raw format of -// a response instead of JSON. -type RawOptions struct { - Type RawType -} - -// addOptions adds the parameters in opt as URL query parameters to s. opt -// must be a struct whose fields may contain "url" tags. -func addOptions(s string, opt interface{}) (string, error) { - v := reflect.ValueOf(opt) - if v.Kind() == reflect.Ptr && v.IsNil() { - return s, nil - } - - u, err := url.Parse(s) - if err != nil { - return s, err - } - - qs, err := query.Values(opt) - if err != nil { - return s, err - } - - u.RawQuery = qs.Encode() - return u.String(), nil -} - -// NewClient returns a new GitHub API client. If a nil httpClient is -// provided, http.DefaultClient will be used. To use API methods which require -// authentication, provide an http.Client that will perform the authentication -// for you (such as that provided by the golang.org/x/oauth2 library). -func NewClient(httpClient *http.Client) *Client { - if httpClient == nil { - httpClient = http.DefaultClient - } - baseURL, _ := url.Parse(defaultBaseURL) - uploadURL, _ := url.Parse(uploadBaseURL) - - c := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent, UploadURL: uploadURL} - c.common.client = c - c.Activity = (*ActivityService)(&c.common) - c.Admin = (*AdminService)(&c.common) - c.Apps = (*AppsService)(&c.common) - c.Authorizations = (*AuthorizationsService)(&c.common) - c.Gists = (*GistsService)(&c.common) - c.Git = (*GitService)(&c.common) - c.Gitignores = (*GitignoresService)(&c.common) - c.Issues = (*IssuesService)(&c.common) - c.Licenses = (*LicensesService)(&c.common) - c.Marketplace = &MarketplaceService{client: c} - c.Migrations = (*MigrationService)(&c.common) - c.Organizations = (*OrganizationsService)(&c.common) - c.Projects = (*ProjectsService)(&c.common) - c.PullRequests = (*PullRequestsService)(&c.common) - c.Reactions = (*ReactionsService)(&c.common) - c.Repositories = (*RepositoriesService)(&c.common) - c.Search = (*SearchService)(&c.common) - c.Users = (*UsersService)(&c.common) - return c -} - -// NewEnterpriseClient returns a new GitHub API client with provided -// base URL and upload URL (often the same URL). -// If either URL does not have a trailing slash, one is added automatically. -// If a nil httpClient is provided, http.DefaultClient will be used. -// -// Note that NewEnterpriseClient is a convenience helper only; -// its behavior is equivalent to using NewClient, followed by setting -// the BaseURL and UploadURL fields. -func NewEnterpriseClient(baseURL, uploadURL string, httpClient *http.Client) (*Client, error) { - baseEndpoint, err := url.Parse(baseURL) - if err != nil { - return nil, err - } - if !strings.HasSuffix(baseEndpoint.Path, "/") { - baseEndpoint.Path += "/" - } - - uploadEndpoint, err := url.Parse(uploadURL) - if err != nil { - return nil, err - } - if !strings.HasSuffix(uploadEndpoint.Path, "/") { - uploadEndpoint.Path += "/" - } - - c := NewClient(httpClient) - c.BaseURL = baseEndpoint - c.UploadURL = uploadEndpoint - return c, nil -} - -// NewRequest creates an API request. A relative URL can be provided in urlStr, -// in which case it is resolved relative to the BaseURL of the Client. -// Relative URLs should always be specified without a preceding slash. If -// specified, the value pointed to by body is JSON encoded and included as the -// request body. -func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) { - if !strings.HasSuffix(c.BaseURL.Path, "/") { - return nil, fmt.Errorf("BaseURL must have a trailing slash, but %q does not", c.BaseURL) - } - u, err := c.BaseURL.Parse(urlStr) - if err != nil { - return nil, err - } - - var buf io.ReadWriter - if body != nil { - buf = new(bytes.Buffer) - enc := json.NewEncoder(buf) - enc.SetEscapeHTML(false) - err := enc.Encode(body) - if err != nil { - return nil, err - } - } - - req, err := http.NewRequest(method, u.String(), buf) - if err != nil { - return nil, err - } - - if body != nil { - req.Header.Set("Content-Type", "application/json") - } - req.Header.Set("Accept", mediaTypeV3) - if c.UserAgent != "" { - req.Header.Set("User-Agent", c.UserAgent) - } - return req, nil -} - -// NewUploadRequest creates an upload request. A relative URL can be provided in -// urlStr, in which case it is resolved relative to the UploadURL of the Client. -// Relative URLs should always be specified without a preceding slash. -func (c *Client) NewUploadRequest(urlStr string, reader io.Reader, size int64, mediaType string) (*http.Request, error) { - if !strings.HasSuffix(c.UploadURL.Path, "/") { - return nil, fmt.Errorf("UploadURL must have a trailing slash, but %q does not", c.UploadURL) - } - u, err := c.UploadURL.Parse(urlStr) - if err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", u.String(), reader) - if err != nil { - return nil, err - } - req.ContentLength = size - - if mediaType == "" { - mediaType = defaultMediaType - } - req.Header.Set("Content-Type", mediaType) - req.Header.Set("Accept", mediaTypeV3) - req.Header.Set("User-Agent", c.UserAgent) - return req, nil -} - -// Response is a GitHub API response. This wraps the standard http.Response -// returned from GitHub and provides convenient access to things like -// pagination links. -type Response struct { - *http.Response - - // These fields provide the page values for paginating through a set of - // results. Any or all of these may be set to the zero value for - // responses that are not part of a paginated set, or for which there - // are no additional pages. - - NextPage int - PrevPage int - FirstPage int - LastPage int - - Rate -} - -// newResponse creates a new Response for the provided http.Response. -// r must not be nil. -func newResponse(r *http.Response) *Response { - response := &Response{Response: r} - response.populatePageValues() - response.Rate = parseRate(r) - return response -} - -// populatePageValues parses the HTTP Link response headers and populates the -// various pagination link values in the Response. -func (r *Response) populatePageValues() { - if links, ok := r.Response.Header["Link"]; ok && len(links) > 0 { - for _, link := range strings.Split(links[0], ",") { - segments := strings.Split(strings.TrimSpace(link), ";") - - // link must at least have href and rel - if len(segments) < 2 { - continue - } - - // ensure href is properly formatted - if !strings.HasPrefix(segments[0], "<") || !strings.HasSuffix(segments[0], ">") { - continue - } - - // try to pull out page parameter - url, err := url.Parse(segments[0][1 : len(segments[0])-1]) - if err != nil { - continue - } - page := url.Query().Get("page") - if page == "" { - continue - } - - for _, segment := range segments[1:] { - switch strings.TrimSpace(segment) { - case `rel="next"`: - r.NextPage, _ = strconv.Atoi(page) - case `rel="prev"`: - r.PrevPage, _ = strconv.Atoi(page) - case `rel="first"`: - r.FirstPage, _ = strconv.Atoi(page) - case `rel="last"`: - r.LastPage, _ = strconv.Atoi(page) - } - - } - } - } -} - -// parseRate parses the rate related headers. -func parseRate(r *http.Response) Rate { - var rate Rate - if limit := r.Header.Get(headerRateLimit); limit != "" { - rate.Limit, _ = strconv.Atoi(limit) - } - if remaining := r.Header.Get(headerRateRemaining); remaining != "" { - rate.Remaining, _ = strconv.Atoi(remaining) - } - if reset := r.Header.Get(headerRateReset); reset != "" { - if v, _ := strconv.ParseInt(reset, 10, 64); v != 0 { - rate.Reset = Timestamp{time.Unix(v, 0)} - } - } - return rate -} - -// Do sends an API request and returns the API response. The API response is -// JSON decoded and stored in the value pointed to by v, or returned as an -// error if an API error has occurred. If v implements the io.Writer -// interface, the raw response body will be written to v, without attempting to -// first decode it. If rate limit is exceeded and reset time is in the future, -// Do returns *RateLimitError immediately without making a network API call. -// -// The provided ctx must be non-nil. If it is canceled or times out, -// ctx.Err() will be returned. -func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*Response, error) { - req = withContext(ctx, req) - - rateLimitCategory := category(req.URL.Path) - - // If we've hit rate limit, don't make further requests before Reset time. - if err := c.checkRateLimitBeforeDo(req, rateLimitCategory); err != nil { - return &Response{ - Response: err.Response, - Rate: err.Rate, - }, err - } - - resp, err := c.client.Do(req) - if err != nil { - // If we got an error, and the context has been canceled, - // the context's error is probably more useful. - select { - case <-ctx.Done(): - return nil, ctx.Err() - default: - } - - // If the error type is *url.Error, sanitize its URL before returning. - if e, ok := err.(*url.Error); ok { - if url, err := url.Parse(e.URL); err == nil { - e.URL = sanitizeURL(url).String() - return nil, e - } - } - - return nil, err - } - - defer func() { - // Drain up to 512 bytes and close the body to let the Transport reuse the connection - io.CopyN(ioutil.Discard, resp.Body, 512) - resp.Body.Close() - }() - - response := newResponse(resp) - - c.rateMu.Lock() - c.rateLimits[rateLimitCategory] = response.Rate - c.rateMu.Unlock() - - err = CheckResponse(resp) - if err != nil { - // even though there was an error, we still return the response - // in case the caller wants to inspect it further - return response, err - } - - if v != nil { - if w, ok := v.(io.Writer); ok { - io.Copy(w, resp.Body) - } else { - err = json.NewDecoder(resp.Body).Decode(v) - if err == io.EOF { - err = nil // ignore EOF errors caused by empty response body - } - } - } - - return response, err -} - -// checkRateLimitBeforeDo does not make any network calls, but uses existing knowledge from -// current client state in order to quickly check if *RateLimitError can be immediately returned -// from Client.Do, and if so, returns it so that Client.Do can skip making a network API call unnecessarily. -// Otherwise it returns nil, and Client.Do should proceed normally. -func (c *Client) checkRateLimitBeforeDo(req *http.Request, rateLimitCategory rateLimitCategory) *RateLimitError { - c.rateMu.Lock() - rate := c.rateLimits[rateLimitCategory] - c.rateMu.Unlock() - if !rate.Reset.Time.IsZero() && rate.Remaining == 0 && time.Now().Before(rate.Reset.Time) { - // Create a fake response. - resp := &http.Response{ - Status: http.StatusText(http.StatusForbidden), - StatusCode: http.StatusForbidden, - Request: req, - Header: make(http.Header), - Body: ioutil.NopCloser(strings.NewReader("")), - } - return &RateLimitError{ - Rate: rate, - Response: resp, - Message: fmt.Sprintf("API rate limit of %v still exceeded until %v, not making remote request.", rate.Limit, rate.Reset.Time), - } - } - - return nil -} - -/* -An ErrorResponse reports one or more errors caused by an API request. - -GitHub API docs: https://developer.github.com/v3/#client-errors -*/ -type ErrorResponse struct { - Response *http.Response // HTTP response that caused this error - Message string `json:"message"` // error message - Errors []Error `json:"errors"` // more detail on individual errors - // Block is only populated on certain types of errors such as code 451. - // See https://developer.github.com/changes/2016-03-17-the-451-status-code-is-now-supported/ - // for more information. - Block *struct { - Reason string `json:"reason,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - } `json:"block,omitempty"` - // Most errors will also include a documentation_url field pointing - // to some content that might help you resolve the error, see - // https://developer.github.com/v3/#client-errors - DocumentationURL string `json:"documentation_url,omitempty"` -} - -func (r *ErrorResponse) Error() string { - return fmt.Sprintf("%v %v: %d %v %+v", - r.Response.Request.Method, sanitizeURL(r.Response.Request.URL), - r.Response.StatusCode, r.Message, r.Errors) -} - -// TwoFactorAuthError occurs when using HTTP Basic Authentication for a user -// that has two-factor authentication enabled. The request can be reattempted -// by providing a one-time password in the request. -type TwoFactorAuthError ErrorResponse - -func (r *TwoFactorAuthError) Error() string { return (*ErrorResponse)(r).Error() } - -// RateLimitError occurs when GitHub returns 403 Forbidden response with a rate limit -// remaining value of 0, and error message starts with "API rate limit exceeded for ". -type RateLimitError struct { - Rate Rate // Rate specifies last known rate limit for the client - Response *http.Response // HTTP response that caused this error - Message string `json:"message"` // error message -} - -func (r *RateLimitError) Error() string { - return fmt.Sprintf("%v %v: %d %v %v", - r.Response.Request.Method, sanitizeURL(r.Response.Request.URL), - r.Response.StatusCode, r.Message, formatRateReset(r.Rate.Reset.Time.Sub(time.Now()))) -} - -// AcceptedError occurs when GitHub returns 202 Accepted response with an -// empty body, which means a job was scheduled on the GitHub side to process -// the information needed and cache it. -// Technically, 202 Accepted is not a real error, it's just used to -// indicate that results are not ready yet, but should be available soon. -// The request can be repeated after some time. -type AcceptedError struct{} - -func (*AcceptedError) Error() string { - return "job scheduled on GitHub side; try again later" -} - -// AbuseRateLimitError occurs when GitHub returns 403 Forbidden response with the -// "documentation_url" field value equal to "https://developer.github.com/v3/#abuse-rate-limits". -type AbuseRateLimitError struct { - Response *http.Response // HTTP response that caused this error - Message string `json:"message"` // error message - - // RetryAfter is provided with some abuse rate limit errors. If present, - // it is the amount of time that the client should wait before retrying. - // Otherwise, the client should try again later (after an unspecified amount of time). - RetryAfter *time.Duration -} - -func (r *AbuseRateLimitError) Error() string { - return fmt.Sprintf("%v %v: %d %v", - r.Response.Request.Method, sanitizeURL(r.Response.Request.URL), - r.Response.StatusCode, r.Message) -} - -// sanitizeURL redacts the client_secret parameter from the URL which may be -// exposed to the user. -func sanitizeURL(uri *url.URL) *url.URL { - if uri == nil { - return nil - } - params := uri.Query() - if len(params.Get("client_secret")) > 0 { - params.Set("client_secret", "REDACTED") - uri.RawQuery = params.Encode() - } - return uri -} - -/* -An Error reports more details on an individual error in an ErrorResponse. -These are the possible validation error codes: - - missing: - resource does not exist - missing_field: - a required field on a resource has not been set - invalid: - the formatting of a field is invalid - already_exists: - another resource has the same valid as this field - custom: - some resources return this (e.g. github.User.CreateKey()), additional - information is set in the Message field of the Error - -GitHub API docs: https://developer.github.com/v3/#client-errors -*/ -type Error struct { - Resource string `json:"resource"` // resource on which the error occurred - Field string `json:"field"` // field on which the error occurred - Code string `json:"code"` // validation error code - Message string `json:"message"` // Message describing the error. Errors with Code == "custom" will always have this set. -} - -func (e *Error) Error() string { - return fmt.Sprintf("%v error caused by %v field on %v resource", - e.Code, e.Field, e.Resource) -} - -// CheckResponse checks the API response for errors, and returns them if -// present. A response is considered an error if it has a status code outside -// the 200 range or equal to 202 Accepted. -// API error responses are expected to have either no response -// body, or a JSON response body that maps to ErrorResponse. Any other -// response body will be silently ignored. -// -// The error type will be *RateLimitError for rate limit exceeded errors, -// *AcceptedError for 202 Accepted status codes, -// and *TwoFactorAuthError for two-factor authentication errors. -func CheckResponse(r *http.Response) error { - if r.StatusCode == http.StatusAccepted { - return &AcceptedError{} - } - if c := r.StatusCode; 200 <= c && c <= 299 { - return nil - } - errorResponse := &ErrorResponse{Response: r} - data, err := ioutil.ReadAll(r.Body) - if err == nil && data != nil { - json.Unmarshal(data, errorResponse) - } - switch { - case r.StatusCode == http.StatusUnauthorized && strings.HasPrefix(r.Header.Get(headerOTP), "required"): - return (*TwoFactorAuthError)(errorResponse) - case r.StatusCode == http.StatusForbidden && r.Header.Get(headerRateRemaining) == "0" && strings.HasPrefix(errorResponse.Message, "API rate limit exceeded for "): - return &RateLimitError{ - Rate: parseRate(r), - Response: errorResponse.Response, - Message: errorResponse.Message, - } - case r.StatusCode == http.StatusForbidden && errorResponse.DocumentationURL == "https://developer.github.com/v3/#abuse-rate-limits": - abuseRateLimitError := &AbuseRateLimitError{ - Response: errorResponse.Response, - Message: errorResponse.Message, - } - if v := r.Header["Retry-After"]; len(v) > 0 { - // According to GitHub support, the "Retry-After" header value will be - // an integer which represents the number of seconds that one should - // wait before resuming making requests. - retryAfterSeconds, _ := strconv.ParseInt(v[0], 10, 64) // Error handling is noop. - retryAfter := time.Duration(retryAfterSeconds) * time.Second - abuseRateLimitError.RetryAfter = &retryAfter - } - return abuseRateLimitError - default: - return errorResponse - } -} - -// parseBoolResponse determines the boolean result from a GitHub API response. -// Several GitHub API methods return boolean responses indicated by the HTTP -// status code in the response (true indicated by a 204, false indicated by a -// 404). This helper function will determine that result and hide the 404 -// error if present. Any other error will be returned through as-is. -func parseBoolResponse(err error) (bool, error) { - if err == nil { - return true, nil - } - - if err, ok := err.(*ErrorResponse); ok && err.Response.StatusCode == http.StatusNotFound { - // Simply false. In this one case, we do not pass the error through. - return false, nil - } - - // some other real error occurred - return false, err -} - -// Rate represents the rate limit for the current client. -type Rate struct { - // The number of requests per hour the client is currently limited to. - Limit int `json:"limit"` - - // The number of remaining requests the client can make this hour. - Remaining int `json:"remaining"` - - // The time at which the current rate limit will reset. - Reset Timestamp `json:"reset"` -} - -func (r Rate) String() string { - return Stringify(r) -} - -// RateLimits represents the rate limits for the current client. -type RateLimits struct { - // The rate limit for non-search API requests. Unauthenticated - // requests are limited to 60 per hour. Authenticated requests are - // limited to 5,000 per hour. - // - // GitHub API docs: https://developer.github.com/v3/#rate-limiting - Core *Rate `json:"core"` - - // The rate limit for search API requests. Unauthenticated requests - // are limited to 10 requests per minutes. Authenticated requests are - // limited to 30 per minute. - // - // GitHub API docs: https://developer.github.com/v3/search/#rate-limit - Search *Rate `json:"search"` -} - -func (r RateLimits) String() string { - return Stringify(r) -} - -type rateLimitCategory uint8 - -const ( - coreCategory rateLimitCategory = iota - searchCategory - - categories // An array of this length will be able to contain all rate limit categories. -) - -// category returns the rate limit category of the endpoint, determined by Request.URL.Path. -func category(path string) rateLimitCategory { - switch { - default: - return coreCategory - case strings.HasPrefix(path, "/search/"): - return searchCategory - } -} - -// RateLimits returns the rate limits for the current client. -func (c *Client) RateLimits(ctx context.Context) (*RateLimits, *Response, error) { - req, err := c.NewRequest("GET", "rate_limit", nil) - if err != nil { - return nil, nil, err - } - - response := new(struct { - Resources *RateLimits `json:"resources"` - }) - resp, err := c.Do(ctx, req, response) - if err != nil { - return nil, nil, err - } - - if response.Resources != nil { - c.rateMu.Lock() - if response.Resources.Core != nil { - c.rateLimits[coreCategory] = *response.Resources.Core - } - if response.Resources.Search != nil { - c.rateLimits[searchCategory] = *response.Resources.Search - } - c.rateMu.Unlock() - } - - return response.Resources, resp, nil -} - -/* -UnauthenticatedRateLimitedTransport allows you to make unauthenticated calls -that need to use a higher rate limit associated with your OAuth application. - - t := &github.UnauthenticatedRateLimitedTransport{ - ClientID: "your app's client ID", - ClientSecret: "your app's client secret", - } - client := github.NewClient(t.Client()) - -This will append the querystring params client_id=xxx&client_secret=yyy to all -requests. - -See https://developer.github.com/v3/#unauthenticated-rate-limited-requests for -more information. -*/ -type UnauthenticatedRateLimitedTransport struct { - // ClientID is the GitHub OAuth client ID of the current application, which - // can be found by selecting its entry in the list at - // https://github.com/settings/applications. - ClientID string - - // ClientSecret is the GitHub OAuth client secret of the current - // application. - ClientSecret string - - // Transport is the underlying HTTP transport to use when making requests. - // It will default to http.DefaultTransport if nil. - Transport http.RoundTripper -} - -// RoundTrip implements the RoundTripper interface. -func (t *UnauthenticatedRateLimitedTransport) RoundTrip(req *http.Request) (*http.Response, error) { - if t.ClientID == "" { - return nil, errors.New("t.ClientID is empty") - } - if t.ClientSecret == "" { - return nil, errors.New("t.ClientSecret is empty") - } - - // To set extra querystring params, we must make a copy of the Request so - // that we don't modify the Request we were given. This is required by the - // specification of http.RoundTripper. - // - // Since we are going to modify only req.URL here, we only need a deep copy - // of req.URL. - req2 := new(http.Request) - *req2 = *req - req2.URL = new(url.URL) - *req2.URL = *req.URL - - q := req2.URL.Query() - q.Set("client_id", t.ClientID) - q.Set("client_secret", t.ClientSecret) - req2.URL.RawQuery = q.Encode() - - // Make the HTTP request. - return t.transport().RoundTrip(req2) -} - -// Client returns an *http.Client that makes requests which are subject to the -// rate limit of your OAuth application. -func (t *UnauthenticatedRateLimitedTransport) Client() *http.Client { - return &http.Client{Transport: t} -} - -func (t *UnauthenticatedRateLimitedTransport) transport() http.RoundTripper { - if t.Transport != nil { - return t.Transport - } - return http.DefaultTransport -} - -// BasicAuthTransport is an http.RoundTripper that authenticates all requests -// using HTTP Basic Authentication with the provided username and password. It -// additionally supports users who have two-factor authentication enabled on -// their GitHub account. -type BasicAuthTransport struct { - Username string // GitHub username - Password string // GitHub password - OTP string // one-time password for users with two-factor auth enabled - - // Transport is the underlying HTTP transport to use when making requests. - // It will default to http.DefaultTransport if nil. - Transport http.RoundTripper -} - -// RoundTrip implements the RoundTripper interface. -func (t *BasicAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) { - // To set extra headers, we must make a copy of the Request so - // that we don't modify the Request we were given. This is required by the - // specification of http.RoundTripper. - // - // Since we are going to modify only req.Header here, we only need a deep copy - // of req.Header. - req2 := new(http.Request) - *req2 = *req - req2.Header = make(http.Header, len(req.Header)) - for k, s := range req.Header { - req2.Header[k] = append([]string(nil), s...) - } - - req2.SetBasicAuth(t.Username, t.Password) - if t.OTP != "" { - req2.Header.Set(headerOTP, t.OTP) - } - return t.transport().RoundTrip(req2) -} - -// Client returns an *http.Client that makes requests that are authenticated -// using HTTP Basic Authentication. -func (t *BasicAuthTransport) Client() *http.Client { - return &http.Client{Transport: t} -} - -func (t *BasicAuthTransport) transport() http.RoundTripper { - if t.Transport != nil { - return t.Transport - } - return http.DefaultTransport -} - -// formatRateReset formats d to look like "[rate reset in 2s]" or -// "[rate reset in 87m02s]" for the positive durations. And like "[rate limit was reset 87m02s ago]" -// for the negative cases. -func formatRateReset(d time.Duration) string { - isNegative := d < 0 - if isNegative { - d *= -1 - } - secondsTotal := int(0.5 + d.Seconds()) - minutes := secondsTotal / 60 - seconds := secondsTotal - minutes*60 - - var timeString string - if minutes > 0 { - timeString = fmt.Sprintf("%dm%02ds", minutes, seconds) - } else { - timeString = fmt.Sprintf("%ds", seconds) - } - - if isNegative { - return fmt.Sprintf("[rate limit was reset %v ago]", timeString) - } - return fmt.Sprintf("[rate reset in %v]", timeString) -} - -// Bool is a helper routine that allocates a new bool value -// to store v and returns a pointer to it. -func Bool(v bool) *bool { return &v } - -// Int is a helper routine that allocates a new int value -// to store v and returns a pointer to it. -func Int(v int) *int { return &v } - -// Int64 is a helper routine that allocates a new int64 value -// to store v and returns a pointer to it. -func Int64(v int64) *int64 { return &v } - -// String is a helper routine that allocates a new string value -// to store v and returns a pointer to it. -func String(v string) *string { return &v } diff --git a/vendor/github.com/google/go-github/github/gitignore.go b/vendor/github.com/google/go-github/github/gitignore.go deleted file mode 100644 index 2f691bc323e..00000000000 --- a/vendor/github.com/google/go-github/github/gitignore.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// GitignoresService provides access to the gitignore related functions in the -// GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/gitignore/ -type GitignoresService service - -// Gitignore represents a .gitignore file as returned by the GitHub API. -type Gitignore struct { - Name *string `json:"name,omitempty"` - Source *string `json:"source,omitempty"` -} - -func (g Gitignore) String() string { - return Stringify(g) -} - -// List all available Gitignore templates. -// -// GitHub API docs: https://developer.github.com/v3/gitignore/#listing-available-templates -func (s GitignoresService) List(ctx context.Context) ([]string, *Response, error) { - req, err := s.client.NewRequest("GET", "gitignore/templates", nil) - if err != nil { - return nil, nil, err - } - - var availableTemplates []string - resp, err := s.client.Do(ctx, req, &availableTemplates) - if err != nil { - return nil, resp, err - } - - return availableTemplates, resp, nil -} - -// Get a Gitignore by name. -// -// GitHub API docs: https://developer.github.com/v3/gitignore/#get-a-single-template -func (s GitignoresService) Get(ctx context.Context, name string) (*Gitignore, *Response, error) { - u := fmt.Sprintf("gitignore/templates/%v", name) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - gitignore := new(Gitignore) - resp, err := s.client.Do(ctx, req, gitignore) - if err != nil { - return nil, resp, err - } - - return gitignore, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/issues.go b/vendor/github.com/google/go-github/github/issues.go deleted file mode 100644 index f865ea20e87..00000000000 --- a/vendor/github.com/google/go-github/github/issues.go +++ /dev/null @@ -1,330 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "strings" - "time" -) - -// IssuesService handles communication with the issue related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/issues/ -type IssuesService service - -// Issue represents a GitHub issue on a repository. -// -// Note: As far as the GitHub API is concerned, every pull request is an issue, -// but not every issue is a pull request. Some endpoints, events, and webhooks -// may also return pull requests via this struct. If PullRequestLinks is nil, -// this is an issue, and if PullRequestLinks is not nil, this is a pull request. -// The IsPullRequest helper method can be used to check that. -type Issue struct { - ID *int64 `json:"id,omitempty"` - Number *int `json:"number,omitempty"` - State *string `json:"state,omitempty"` - Locked *bool `json:"locked,omitempty"` - Title *string `json:"title,omitempty"` - Body *string `json:"body,omitempty"` - User *User `json:"user,omitempty"` - Labels []Label `json:"labels,omitempty"` - Assignee *User `json:"assignee,omitempty"` - Comments *int `json:"comments,omitempty"` - ClosedAt *time.Time `json:"closed_at,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - ClosedBy *User `json:"closed_by,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - CommentsURL *string `json:"comments_url,omitempty"` - EventsURL *string `json:"events_url,omitempty"` - LabelsURL *string `json:"labels_url,omitempty"` - RepositoryURL *string `json:"repository_url,omitempty"` - Milestone *Milestone `json:"milestone,omitempty"` - PullRequestLinks *PullRequestLinks `json:"pull_request,omitempty"` - Repository *Repository `json:"repository,omitempty"` - Reactions *Reactions `json:"reactions,omitempty"` - Assignees []*User `json:"assignees,omitempty"` - NodeID *string `json:"node_id,omitempty"` - - // TextMatches is only populated from search results that request text matches - // See: search.go and https://developer.github.com/v3/search/#text-match-metadata - TextMatches []TextMatch `json:"text_matches,omitempty"` -} - -func (i Issue) String() string { - return Stringify(i) -} - -// IsPullRequest reports whether the issue is also a pull request. It uses the -// method recommended by GitHub's API documentation, which is to check whether -// PullRequestLinks is non-nil. -func (i Issue) IsPullRequest() bool { - return i.PullRequestLinks != nil -} - -// IssueRequest represents a request to create/edit an issue. -// It is separate from Issue above because otherwise Labels -// and Assignee fail to serialize to the correct JSON. -type IssueRequest struct { - Title *string `json:"title,omitempty"` - Body *string `json:"body,omitempty"` - Labels *[]string `json:"labels,omitempty"` - Assignee *string `json:"assignee,omitempty"` - State *string `json:"state,omitempty"` - Milestone *int `json:"milestone,omitempty"` - Assignees *[]string `json:"assignees,omitempty"` -} - -// IssueListOptions specifies the optional parameters to the IssuesService.List -// and IssuesService.ListByOrg methods. -type IssueListOptions struct { - // Filter specifies which issues to list. Possible values are: assigned, - // created, mentioned, subscribed, all. Default is "assigned". - Filter string `url:"filter,omitempty"` - - // State filters issues based on their state. Possible values are: open, - // closed, all. Default is "open". - State string `url:"state,omitempty"` - - // Labels filters issues based on their label. - Labels []string `url:"labels,comma,omitempty"` - - // Sort specifies how to sort issues. Possible values are: created, updated, - // and comments. Default value is "created". - Sort string `url:"sort,omitempty"` - - // Direction in which to sort issues. Possible values are: asc, desc. - // Default is "desc". - Direction string `url:"direction,omitempty"` - - // Since filters issues by time. - Since time.Time `url:"since,omitempty"` - - ListOptions -} - -// PullRequestLinks object is added to the Issue object when it's an issue included -// in the IssueCommentEvent webhook payload, if the webhook is fired by a comment on a PR. -type PullRequestLinks struct { - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - DiffURL *string `json:"diff_url,omitempty"` - PatchURL *string `json:"patch_url,omitempty"` -} - -// List the issues for the authenticated user. If all is true, list issues -// across all the user's visible repositories including owned, member, and -// organization repositories; if false, list only owned and member -// repositories. -// -// GitHub API docs: https://developer.github.com/v3/issues/#list-issues -func (s *IssuesService) List(ctx context.Context, all bool, opt *IssueListOptions) ([]*Issue, *Response, error) { - var u string - if all { - u = "issues" - } else { - u = "user/issues" - } - return s.listIssues(ctx, u, opt) -} - -// ListByOrg fetches the issues in the specified organization for the -// authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/issues/#list-issues -func (s *IssuesService) ListByOrg(ctx context.Context, org string, opt *IssueListOptions) ([]*Issue, *Response, error) { - u := fmt.Sprintf("orgs/%v/issues", org) - return s.listIssues(ctx, u, opt) -} - -func (s *IssuesService) listIssues(ctx context.Context, u string, opt *IssueListOptions) ([]*Issue, *Response, error) { - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - acceptHeaders := []string{mediaTypeReactionsPreview, mediaTypeGraphQLNodeIDPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - var issues []*Issue - resp, err := s.client.Do(ctx, req, &issues) - if err != nil { - return nil, resp, err - } - - return issues, resp, nil -} - -// IssueListByRepoOptions specifies the optional parameters to the -// IssuesService.ListByRepo method. -type IssueListByRepoOptions struct { - // Milestone limits issues for the specified milestone. Possible values are - // a milestone number, "none" for issues with no milestone, "*" for issues - // with any milestone. - Milestone string `url:"milestone,omitempty"` - - // State filters issues based on their state. Possible values are: open, - // closed, all. Default is "open". - State string `url:"state,omitempty"` - - // Assignee filters issues based on their assignee. Possible values are a - // user name, "none" for issues that are not assigned, "*" for issues with - // any assigned user. - Assignee string `url:"assignee,omitempty"` - - // Creator filters issues based on their creator. - Creator string `url:"creator,omitempty"` - - // Mentioned filters issues to those mentioned a specific user. - Mentioned string `url:"mentioned,omitempty"` - - // Labels filters issues based on their label. - Labels []string `url:"labels,omitempty,comma"` - - // Sort specifies how to sort issues. Possible values are: created, updated, - // and comments. Default value is "created". - Sort string `url:"sort,omitempty"` - - // Direction in which to sort issues. Possible values are: asc, desc. - // Default is "desc". - Direction string `url:"direction,omitempty"` - - // Since filters issues by time. - Since time.Time `url:"since,omitempty"` - - ListOptions -} - -// ListByRepo lists the issues for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/#list-issues-for-a-repository -func (s *IssuesService) ListByRepo(ctx context.Context, owner string, repo string, opt *IssueListByRepoOptions) ([]*Issue, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - acceptHeaders := []string{mediaTypeReactionsPreview, mediaTypeGraphQLNodeIDPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - var issues []*Issue - resp, err := s.client.Do(ctx, req, &issues) - if err != nil { - return nil, resp, err - } - - return issues, resp, nil -} - -// Get a single issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/#get-a-single-issue -func (s *IssuesService) Get(ctx context.Context, owner string, repo string, number int) (*Issue, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d", owner, repo, number) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - acceptHeaders := []string{mediaTypeReactionsPreview, mediaTypeGraphQLNodeIDPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - issue := new(Issue) - resp, err := s.client.Do(ctx, req, issue) - if err != nil { - return nil, resp, err - } - - return issue, resp, nil -} - -// Create a new issue on the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/#create-an-issue -func (s *IssuesService) Create(ctx context.Context, owner string, repo string, issue *IssueRequest) (*Issue, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues", owner, repo) - req, err := s.client.NewRequest("POST", u, issue) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - i := new(Issue) - resp, err := s.client.Do(ctx, req, i) - if err != nil { - return nil, resp, err - } - - return i, resp, nil -} - -// Edit an issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/#edit-an-issue -func (s *IssuesService) Edit(ctx context.Context, owner string, repo string, number int, issue *IssueRequest) (*Issue, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d", owner, repo, number) - req, err := s.client.NewRequest("PATCH", u, issue) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - i := new(Issue) - resp, err := s.client.Do(ctx, req, i) - if err != nil { - return nil, resp, err - } - - return i, resp, nil -} - -// Lock an issue's conversation. -// -// GitHub API docs: https://developer.github.com/v3/issues/#lock-an-issue -func (s *IssuesService) Lock(ctx context.Context, owner string, repo string, number int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/lock", owner, repo, number) - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// Unlock an issue's conversation. -// -// GitHub API docs: https://developer.github.com/v3/issues/#unlock-an-issue -func (s *IssuesService) Unlock(ctx context.Context, owner string, repo string, number int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/lock", owner, repo, number) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/issues_assignees.go b/vendor/github.com/google/go-github/github/issues_assignees.go deleted file mode 100644 index 9cb366f50a3..00000000000 --- a/vendor/github.com/google/go-github/github/issues_assignees.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ListAssignees fetches all available assignees (owners and collaborators) to -// which issues may be assigned. -// -// GitHub API docs: https://developer.github.com/v3/issues/assignees/#list-assignees -func (s *IssuesService) ListAssignees(ctx context.Context, owner, repo string, opt *ListOptions) ([]*User, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/assignees", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - var assignees []*User - resp, err := s.client.Do(ctx, req, &assignees) - if err != nil { - return nil, resp, err - } - - return assignees, resp, nil -} - -// IsAssignee checks if a user is an assignee for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/assignees/#check-assignee -func (s *IssuesService) IsAssignee(ctx context.Context, owner, repo, user string) (bool, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/assignees/%v", owner, repo, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - resp, err := s.client.Do(ctx, req, nil) - assignee, err := parseBoolResponse(err) - return assignee, resp, err -} - -// AddAssignees adds the provided GitHub users as assignees to the issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/assignees/#add-assignees-to-an-issue -func (s *IssuesService) AddAssignees(ctx context.Context, owner, repo string, number int, assignees []string) (*Issue, *Response, error) { - users := &struct { - Assignees []string `json:"assignees,omitempty"` - }{Assignees: assignees} - u := fmt.Sprintf("repos/%v/%v/issues/%v/assignees", owner, repo, number) - req, err := s.client.NewRequest("POST", u, users) - if err != nil { - return nil, nil, err - } - - issue := &Issue{} - resp, err := s.client.Do(ctx, req, issue) - return issue, resp, err -} - -// RemoveAssignees removes the provided GitHub users as assignees from the issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/assignees/#remove-assignees-from-an-issue -func (s *IssuesService) RemoveAssignees(ctx context.Context, owner, repo string, number int, assignees []string) (*Issue, *Response, error) { - users := &struct { - Assignees []string `json:"assignees,omitempty"` - }{Assignees: assignees} - u := fmt.Sprintf("repos/%v/%v/issues/%v/assignees", owner, repo, number) - req, err := s.client.NewRequest("DELETE", u, users) - if err != nil { - return nil, nil, err - } - - issue := &Issue{} - resp, err := s.client.Do(ctx, req, issue) - return issue, resp, err -} diff --git a/vendor/github.com/google/go-github/github/issues_comments.go b/vendor/github.com/google/go-github/github/issues_comments.go deleted file mode 100644 index 70047453add..00000000000 --- a/vendor/github.com/google/go-github/github/issues_comments.go +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// IssueComment represents a comment left on an issue. -type IssueComment struct { - ID *int64 `json:"id,omitempty"` - Body *string `json:"body,omitempty"` - User *User `json:"user,omitempty"` - Reactions *Reactions `json:"reactions,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - IssueURL *string `json:"issue_url,omitempty"` -} - -func (i IssueComment) String() string { - return Stringify(i) -} - -// IssueListCommentsOptions specifies the optional parameters to the -// IssuesService.ListComments method. -type IssueListCommentsOptions struct { - // Sort specifies how to sort comments. Possible values are: created, updated. - Sort string `url:"sort,omitempty"` - - // Direction in which to sort comments. Possible values are: asc, desc. - Direction string `url:"direction,omitempty"` - - // Since filters comments by time. - Since time.Time `url:"since,omitempty"` - - ListOptions -} - -// ListComments lists all comments on the specified issue. Specifying an issue -// number of 0 will return all comments on all issues for the repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/comments/#list-comments-on-an-issue -func (s *IssuesService) ListComments(ctx context.Context, owner string, repo string, number int, opt *IssueListCommentsOptions) ([]*IssueComment, *Response, error) { - var u string - if number == 0 { - u = fmt.Sprintf("repos/%v/%v/issues/comments", owner, repo) - } else { - u = fmt.Sprintf("repos/%v/%v/issues/%d/comments", owner, repo, number) - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var comments []*IssueComment - resp, err := s.client.Do(ctx, req, &comments) - if err != nil { - return nil, resp, err - } - - return comments, resp, nil -} - -// GetComment fetches the specified issue comment. -// -// GitHub API docs: https://developer.github.com/v3/issues/comments/#get-a-single-comment -func (s *IssuesService) GetComment(ctx context.Context, owner string, repo string, id int) (*IssueComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/comments/%d", owner, repo, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - comment := new(IssueComment) - resp, err := s.client.Do(ctx, req, comment) - if err != nil { - return nil, resp, err - } - - return comment, resp, nil -} - -// CreateComment creates a new comment on the specified issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/comments/#create-a-comment -func (s *IssuesService) CreateComment(ctx context.Context, owner string, repo string, number int, comment *IssueComment) (*IssueComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/comments", owner, repo, number) - req, err := s.client.NewRequest("POST", u, comment) - if err != nil { - return nil, nil, err - } - c := new(IssueComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// EditComment updates an issue comment. -// -// GitHub API docs: https://developer.github.com/v3/issues/comments/#edit-a-comment -func (s *IssuesService) EditComment(ctx context.Context, owner string, repo string, id int, comment *IssueComment) (*IssueComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/comments/%d", owner, repo, id) - req, err := s.client.NewRequest("PATCH", u, comment) - if err != nil { - return nil, nil, err - } - c := new(IssueComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// DeleteComment deletes an issue comment. -// -// GitHub API docs: https://developer.github.com/v3/issues/comments/#delete-a-comment -func (s *IssuesService) DeleteComment(ctx context.Context, owner string, repo string, id int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/comments/%d", owner, repo, id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/issues_events.go b/vendor/github.com/google/go-github/github/issues_events.go deleted file mode 100644 index 55e6d431b30..00000000000 --- a/vendor/github.com/google/go-github/github/issues_events.go +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// IssueEvent represents an event that occurred around an Issue or Pull Request. -type IssueEvent struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - - // The User that generated this event. - Actor *User `json:"actor,omitempty"` - - // Event identifies the actual type of Event that occurred. Possible - // values are: - // - // closed - // The Actor closed the issue. - // If the issue was closed by commit message, CommitID holds the SHA1 hash of the commit. - // - // merged - // The Actor merged into master a branch containing a commit mentioning the issue. - // CommitID holds the SHA1 of the merge commit. - // - // referenced - // The Actor committed to master a commit mentioning the issue in its commit message. - // CommitID holds the SHA1 of the commit. - // - // reopened, locked, unlocked - // The Actor did that to the issue. - // - // renamed - // The Actor changed the issue title from Rename.From to Rename.To. - // - // mentioned - // Someone unspecified @mentioned the Actor [sic] in an issue comment body. - // - // assigned, unassigned - // The Assigner assigned the issue to or removed the assignment from the Assignee. - // - // labeled, unlabeled - // The Actor added or removed the Label from the issue. - // - // milestoned, demilestoned - // The Actor added or removed the issue from the Milestone. - // - // subscribed, unsubscribed - // The Actor subscribed to or unsubscribed from notifications for an issue. - // - // head_ref_deleted, head_ref_restored - // The pull request’s branch was deleted or restored. - // - Event *string `json:"event,omitempty"` - - CreatedAt *time.Time `json:"created_at,omitempty"` - Issue *Issue `json:"issue,omitempty"` - - // Only present on certain events; see above. - Assignee *User `json:"assignee,omitempty"` - Assigner *User `json:"assigner,omitempty"` - CommitID *string `json:"commit_id,omitempty"` - Milestone *Milestone `json:"milestone,omitempty"` - Label *Label `json:"label,omitempty"` - Rename *Rename `json:"rename,omitempty"` -} - -// ListIssueEvents lists events for the specified issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/events/#list-events-for-an-issue -func (s *IssuesService) ListIssueEvents(ctx context.Context, owner, repo string, number int, opt *ListOptions) ([]*IssueEvent, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%v/events", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*IssueEvent - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListRepositoryEvents lists events for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/events/#list-events-for-a-repository -func (s *IssuesService) ListRepositoryEvents(ctx context.Context, owner, repo string, opt *ListOptions) ([]*IssueEvent, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/events", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*IssueEvent - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// GetEvent returns the specified issue event. -// -// GitHub API docs: https://developer.github.com/v3/issues/events/#get-a-single-event -func (s *IssuesService) GetEvent(ctx context.Context, owner, repo string, id int64) (*IssueEvent, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/events/%v", owner, repo, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - event := new(IssueEvent) - resp, err := s.client.Do(ctx, req, event) - if err != nil { - return nil, resp, err - } - - return event, resp, nil -} - -// Rename contains details for 'renamed' events. -type Rename struct { - From *string `json:"from,omitempty"` - To *string `json:"to,omitempty"` -} - -func (r Rename) String() string { - return Stringify(r) -} diff --git a/vendor/github.com/google/go-github/github/issues_labels.go b/vendor/github.com/google/go-github/github/issues_labels.go deleted file mode 100644 index aacf7d7c21c..00000000000 --- a/vendor/github.com/google/go-github/github/issues_labels.go +++ /dev/null @@ -1,251 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// Label represents a GitHub label on an Issue -type Label struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - Name *string `json:"name,omitempty"` - Color *string `json:"color,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -func (l Label) String() string { - return Stringify(l) -} - -// ListLabels lists all labels for a repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#list-all-labels-for-this-repository -func (s *IssuesService) ListLabels(ctx context.Context, owner string, repo string, opt *ListOptions) ([]*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/labels", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - var labels []*Label - resp, err := s.client.Do(ctx, req, &labels) - if err != nil { - return nil, resp, err - } - - return labels, resp, nil -} - -// GetLabel gets a single label. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#get-a-single-label -func (s *IssuesService) GetLabel(ctx context.Context, owner string, repo string, name string) (*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/labels/%v", owner, repo, name) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - label := new(Label) - resp, err := s.client.Do(ctx, req, label) - if err != nil { - return nil, resp, err - } - - return label, resp, nil -} - -// CreateLabel creates a new label on the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#create-a-label -func (s *IssuesService) CreateLabel(ctx context.Context, owner string, repo string, label *Label) (*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/labels", owner, repo) - req, err := s.client.NewRequest("POST", u, label) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - l := new(Label) - resp, err := s.client.Do(ctx, req, l) - if err != nil { - return nil, resp, err - } - - return l, resp, nil -} - -// EditLabel edits a label. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#update-a-label -func (s *IssuesService) EditLabel(ctx context.Context, owner string, repo string, name string, label *Label) (*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/labels/%v", owner, repo, name) - req, err := s.client.NewRequest("PATCH", u, label) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - l := new(Label) - resp, err := s.client.Do(ctx, req, l) - if err != nil { - return nil, resp, err - } - - return l, resp, nil -} - -// DeleteLabel deletes a label. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#delete-a-label -func (s *IssuesService) DeleteLabel(ctx context.Context, owner string, repo string, name string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/labels/%v", owner, repo, name) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// ListLabelsByIssue lists all labels for an issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#list-labels-on-an-issue -func (s *IssuesService) ListLabelsByIssue(ctx context.Context, owner string, repo string, number int, opt *ListOptions) ([]*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/labels", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - var labels []*Label - resp, err := s.client.Do(ctx, req, &labels) - if err != nil { - return nil, resp, err - } - - return labels, resp, nil -} - -// AddLabelsToIssue adds labels to an issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#add-labels-to-an-issue -func (s *IssuesService) AddLabelsToIssue(ctx context.Context, owner string, repo string, number int, labels []string) ([]*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/labels", owner, repo, number) - req, err := s.client.NewRequest("POST", u, labels) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - var l []*Label - resp, err := s.client.Do(ctx, req, &l) - if err != nil { - return nil, resp, err - } - - return l, resp, nil -} - -// RemoveLabelForIssue removes a label for an issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#remove-a-label-from-an-issue -func (s *IssuesService) RemoveLabelForIssue(ctx context.Context, owner string, repo string, number int, label string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/labels/%v", owner, repo, number, label) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// ReplaceLabelsForIssue replaces all labels for an issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#replace-all-labels-for-an-issue -func (s *IssuesService) ReplaceLabelsForIssue(ctx context.Context, owner string, repo string, number int, labels []string) ([]*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/labels", owner, repo, number) - req, err := s.client.NewRequest("PUT", u, labels) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - var l []*Label - resp, err := s.client.Do(ctx, req, &l) - if err != nil { - return nil, resp, err - } - - return l, resp, nil -} - -// RemoveLabelsForIssue removes all labels for an issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#remove-all-labels-from-an-issue -func (s *IssuesService) RemoveLabelsForIssue(ctx context.Context, owner string, repo string, number int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/labels", owner, repo, number) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// ListLabelsForMilestone lists labels for every issue in a milestone. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#get-labels-for-every-issue-in-a-milestone -func (s *IssuesService) ListLabelsForMilestone(ctx context.Context, owner string, repo string, number int, opt *ListOptions) ([]*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/milestones/%d/labels", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - var labels []*Label - resp, err := s.client.Do(ctx, req, &labels) - if err != nil { - return nil, resp, err - } - - return labels, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/issues_milestones.go b/vendor/github.com/google/go-github/github/issues_milestones.go deleted file mode 100644 index 6af1cc03c4a..00000000000 --- a/vendor/github.com/google/go-github/github/issues_milestones.go +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// Milestone represents a GitHub repository milestone. -type Milestone struct { - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - LabelsURL *string `json:"labels_url,omitempty"` - ID *int64 `json:"id,omitempty"` - Number *int `json:"number,omitempty"` - State *string `json:"state,omitempty"` - Title *string `json:"title,omitempty"` - Description *string `json:"description,omitempty"` - Creator *User `json:"creator,omitempty"` - OpenIssues *int `json:"open_issues,omitempty"` - ClosedIssues *int `json:"closed_issues,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - ClosedAt *time.Time `json:"closed_at,omitempty"` - DueOn *time.Time `json:"due_on,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -func (m Milestone) String() string { - return Stringify(m) -} - -// MilestoneListOptions specifies the optional parameters to the -// IssuesService.ListMilestones method. -type MilestoneListOptions struct { - // State filters milestones based on their state. Possible values are: - // open, closed, all. Default is "open". - State string `url:"state,omitempty"` - - // Sort specifies how to sort milestones. Possible values are: due_on, completeness. - // Default value is "due_on". - Sort string `url:"sort,omitempty"` - - // Direction in which to sort milestones. Possible values are: asc, desc. - // Default is "asc". - Direction string `url:"direction,omitempty"` - - ListOptions -} - -// ListMilestones lists all milestones for a repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/milestones/#list-milestones-for-a-repository -func (s *IssuesService) ListMilestones(ctx context.Context, owner string, repo string, opt *MilestoneListOptions) ([]*Milestone, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/milestones", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - var milestones []*Milestone - resp, err := s.client.Do(ctx, req, &milestones) - if err != nil { - return nil, resp, err - } - - return milestones, resp, nil -} - -// GetMilestone gets a single milestone. -// -// GitHub API docs: https://developer.github.com/v3/issues/milestones/#get-a-single-milestone -func (s *IssuesService) GetMilestone(ctx context.Context, owner string, repo string, number int) (*Milestone, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/milestones/%d", owner, repo, number) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - milestone := new(Milestone) - resp, err := s.client.Do(ctx, req, milestone) - if err != nil { - return nil, resp, err - } - - return milestone, resp, nil -} - -// CreateMilestone creates a new milestone on the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/milestones/#create-a-milestone -func (s *IssuesService) CreateMilestone(ctx context.Context, owner string, repo string, milestone *Milestone) (*Milestone, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/milestones", owner, repo) - req, err := s.client.NewRequest("POST", u, milestone) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - m := new(Milestone) - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// EditMilestone edits a milestone. -// -// GitHub API docs: https://developer.github.com/v3/issues/milestones/#update-a-milestone -func (s *IssuesService) EditMilestone(ctx context.Context, owner string, repo string, number int, milestone *Milestone) (*Milestone, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/milestones/%d", owner, repo, number) - req, err := s.client.NewRequest("PATCH", u, milestone) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - m := new(Milestone) - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// DeleteMilestone deletes a milestone. -// -// GitHub API docs: https://developer.github.com/v3/issues/milestones/#delete-a-milestone -func (s *IssuesService) DeleteMilestone(ctx context.Context, owner string, repo string, number int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/milestones/%d", owner, repo, number) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/issues_timeline.go b/vendor/github.com/google/go-github/github/issues_timeline.go deleted file mode 100644 index 9cfda832026..00000000000 --- a/vendor/github.com/google/go-github/github/issues_timeline.go +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// Timeline represents an event that occurred around an Issue or Pull Request. -// -// It is similar to an IssueEvent but may contain more information. -// GitHub API docs: https://developer.github.com/v3/issues/timeline/ -type Timeline struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - CommitURL *string `json:"commit_url,omitempty"` - - // The User object that generated the event. - Actor *User `json:"actor,omitempty"` - - // Event identifies the actual type of Event that occurred. Possible values - // are: - // - // assigned - // The issue was assigned to the assignee. - // - // closed - // The issue was closed by the actor. When the commit_id is present, it - // identifies the commit that closed the issue using "closes / fixes #NN" - // syntax. - // - // commented - // A comment was added to the issue. - // - // committed - // A commit was added to the pull request's 'HEAD' branch. Only provided - // for pull requests. - // - // cross-referenced - // The issue was referenced from another issue. The 'source' attribute - // contains the 'id', 'actor', and 'url' of the reference's source. - // - // demilestoned - // The issue was removed from a milestone. - // - // head_ref_deleted - // The pull request's branch was deleted. - // - // head_ref_restored - // The pull request's branch was restored. - // - // labeled - // A label was added to the issue. - // - // locked - // The issue was locked by the actor. - // - // mentioned - // The actor was @mentioned in an issue body. - // - // merged - // The issue was merged by the actor. The 'commit_id' attribute is the - // SHA1 of the HEAD commit that was merged. - // - // milestoned - // The issue was added to a milestone. - // - // referenced - // The issue was referenced from a commit message. The 'commit_id' - // attribute is the commit SHA1 of where that happened. - // - // renamed - // The issue title was changed. - // - // reopened - // The issue was reopened by the actor. - // - // subscribed - // The actor subscribed to receive notifications for an issue. - // - // unassigned - // The assignee was unassigned from the issue. - // - // unlabeled - // A label was removed from the issue. - // - // unlocked - // The issue was unlocked by the actor. - // - // unsubscribed - // The actor unsubscribed to stop receiving notifications for an issue. - // - Event *string `json:"event,omitempty"` - - // The string SHA of a commit that referenced this Issue or Pull Request. - CommitID *string `json:"commit_id,omitempty"` - // The timestamp indicating when the event occurred. - CreatedAt *time.Time `json:"created_at,omitempty"` - // The Label object including `name` and `color` attributes. Only provided for - // 'labeled' and 'unlabeled' events. - Label *Label `json:"label,omitempty"` - // The User object which was assigned to (or unassigned from) this Issue or - // Pull Request. Only provided for 'assigned' and 'unassigned' events. - Assignee *User `json:"assignee,omitempty"` - // The Milestone object including a 'title' attribute. - // Only provided for 'milestoned' and 'demilestoned' events. - Milestone *Milestone `json:"milestone,omitempty"` - // The 'id', 'actor', and 'url' for the source of a reference from another issue. - // Only provided for 'cross-referenced' events. - Source *Source `json:"source,omitempty"` - // An object containing rename details including 'from' and 'to' attributes. - // Only provided for 'renamed' events. - Rename *Rename `json:"rename,omitempty"` -} - -// Source represents a reference's source. -type Source struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - Actor *User `json:"actor,omitempty"` -} - -// ListIssueTimeline lists events for the specified issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/timeline/#list-events-for-an-issue -func (s *IssuesService) ListIssueTimeline(ctx context.Context, owner, repo string, number int, opt *ListOptions) ([]*Timeline, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%v/timeline", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTimelinePreview) - - var events []*Timeline - resp, err := s.client.Do(ctx, req, &events) - return events, resp, err -} diff --git a/vendor/github.com/google/go-github/github/licenses.go b/vendor/github.com/google/go-github/github/licenses.go deleted file mode 100644 index e9cd1777afb..00000000000 --- a/vendor/github.com/google/go-github/github/licenses.go +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// LicensesService handles communication with the license related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/licenses/ -type LicensesService service - -// RepositoryLicense represents the license for a repository. -type RepositoryLicense struct { - Name *string `json:"name,omitempty"` - Path *string `json:"path,omitempty"` - - SHA *string `json:"sha,omitempty"` - Size *int `json:"size,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - GitURL *string `json:"git_url,omitempty"` - DownloadURL *string `json:"download_url,omitempty"` - Type *string `json:"type,omitempty"` - Content *string `json:"content,omitempty"` - Encoding *string `json:"encoding,omitempty"` - License *License `json:"license,omitempty"` -} - -func (l RepositoryLicense) String() string { - return Stringify(l) -} - -// License represents an open source license. -type License struct { - Key *string `json:"key,omitempty"` - Name *string `json:"name,omitempty"` - URL *string `json:"url,omitempty"` - - SPDXID *string `json:"spdx_id,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - Featured *bool `json:"featured,omitempty"` - Description *string `json:"description,omitempty"` - Implementation *string `json:"implementation,omitempty"` - Permissions *[]string `json:"permissions,omitempty"` - Conditions *[]string `json:"conditions,omitempty"` - Limitations *[]string `json:"limitations,omitempty"` - Body *string `json:"body,omitempty"` -} - -func (l License) String() string { - return Stringify(l) -} - -// List popular open source licenses. -// -// GitHub API docs: https://developer.github.com/v3/licenses/#list-all-licenses -func (s *LicensesService) List(ctx context.Context) ([]*License, *Response, error) { - req, err := s.client.NewRequest("GET", "licenses", nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeLicensesPreview) - - var licenses []*License - resp, err := s.client.Do(ctx, req, &licenses) - if err != nil { - return nil, resp, err - } - - return licenses, resp, nil -} - -// Get extended metadata for one license. -// -// GitHub API docs: https://developer.github.com/v3/licenses/#get-an-individual-license -func (s *LicensesService) Get(ctx context.Context, licenseName string) (*License, *Response, error) { - u := fmt.Sprintf("licenses/%s", licenseName) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeLicensesPreview) - - license := new(License) - resp, err := s.client.Do(ctx, req, license) - if err != nil { - return nil, resp, err - } - - return license, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/messages.go b/vendor/github.com/google/go-github/github/messages.go deleted file mode 100644 index 2396fd4314e..00000000000 --- a/vendor/github.com/google/go-github/github/messages.go +++ /dev/null @@ -1,245 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file provides functions for validating payloads from GitHub Webhooks. -// GitHub API docs: https://developer.github.com/webhooks/securing/#validating-payloads-from-github - -package github - -import ( - "crypto/hmac" - "crypto/sha1" - "crypto/sha256" - "crypto/sha512" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "hash" - "io/ioutil" - "net/http" - "net/url" - "strings" -) - -const ( - // sha1Prefix is the prefix used by GitHub before the HMAC hexdigest. - sha1Prefix = "sha1" - // sha256Prefix and sha512Prefix are provided for future compatibility. - sha256Prefix = "sha256" - sha512Prefix = "sha512" - // signatureHeader is the GitHub header key used to pass the HMAC hexdigest. - signatureHeader = "X-Hub-Signature" - // eventTypeHeader is the GitHub header key used to pass the event type. - eventTypeHeader = "X-Github-Event" - // deliveryIDHeader is the GitHub header key used to pass the unique ID for the webhook event. - deliveryIDHeader = "X-Github-Delivery" -) - -var ( - // eventTypeMapping maps webhooks types to their corresponding go-github struct types. - eventTypeMapping = map[string]string{ - "commit_comment": "CommitCommentEvent", - "create": "CreateEvent", - "delete": "DeleteEvent", - "deployment": "DeploymentEvent", - "deployment_status": "DeploymentStatusEvent", - "fork": "ForkEvent", - "gollum": "GollumEvent", - "installation": "InstallationEvent", - "installation_repositories": "InstallationRepositoriesEvent", - "issue_comment": "IssueCommentEvent", - "issues": "IssuesEvent", - "label": "LabelEvent", - "marketplace_purchase": "MarketplacePurchaseEvent", - "member": "MemberEvent", - "membership": "MembershipEvent", - "milestone": "MilestoneEvent", - "organization": "OrganizationEvent", - "org_block": "OrgBlockEvent", - "page_build": "PageBuildEvent", - "ping": "PingEvent", - "project": "ProjectEvent", - "project_card": "ProjectCardEvent", - "project_column": "ProjectColumnEvent", - "public": "PublicEvent", - "pull_request_review": "PullRequestReviewEvent", - "pull_request_review_comment": "PullRequestReviewCommentEvent", - "pull_request": "PullRequestEvent", - "push": "PushEvent", - "repository": "RepositoryEvent", - "release": "ReleaseEvent", - "status": "StatusEvent", - "team": "TeamEvent", - "team_add": "TeamAddEvent", - "watch": "WatchEvent", - } -) - -// genMAC generates the HMAC signature for a message provided the secret key -// and hashFunc. -func genMAC(message, key []byte, hashFunc func() hash.Hash) []byte { - mac := hmac.New(hashFunc, key) - mac.Write(message) - return mac.Sum(nil) -} - -// checkMAC reports whether messageMAC is a valid HMAC tag for message. -func checkMAC(message, messageMAC, key []byte, hashFunc func() hash.Hash) bool { - expectedMAC := genMAC(message, key, hashFunc) - return hmac.Equal(messageMAC, expectedMAC) -} - -// messageMAC returns the hex-decoded HMAC tag from the signature and its -// corresponding hash function. -func messageMAC(signature string) ([]byte, func() hash.Hash, error) { - if signature == "" { - return nil, nil, errors.New("missing signature") - } - sigParts := strings.SplitN(signature, "=", 2) - if len(sigParts) != 2 { - return nil, nil, fmt.Errorf("error parsing signature %q", signature) - } - - var hashFunc func() hash.Hash - switch sigParts[0] { - case sha1Prefix: - hashFunc = sha1.New - case sha256Prefix: - hashFunc = sha256.New - case sha512Prefix: - hashFunc = sha512.New - default: - return nil, nil, fmt.Errorf("unknown hash type prefix: %q", sigParts[0]) - } - - buf, err := hex.DecodeString(sigParts[1]) - if err != nil { - return nil, nil, fmt.Errorf("error decoding signature %q: %v", signature, err) - } - return buf, hashFunc, nil -} - -// ValidatePayload validates an incoming GitHub Webhook event request -// and returns the (JSON) payload. -// The Content-Type header of the payload can be "application/json" or "application/x-www-form-urlencoded". -// If the Content-Type is neither then an error is returned. -// secretKey is the GitHub Webhook secret message. -// -// Example usage: -// -// func (s *GitHubEventMonitor) ServeHTTP(w http.ResponseWriter, r *http.Request) { -// payload, err := github.ValidatePayload(r, s.webhookSecretKey) -// if err != nil { ... } -// // Process payload... -// } -// -func ValidatePayload(r *http.Request, secretKey []byte) (payload []byte, err error) { - var body []byte // Raw body that GitHub uses to calculate the signature. - - switch ct := r.Header.Get("Content-Type"); ct { - case "application/json": - var err error - if body, err = ioutil.ReadAll(r.Body); err != nil { - return nil, err - } - - // If the content type is application/json, - // the JSON payload is just the original body. - payload = body - - case "application/x-www-form-urlencoded": - // payloadFormParam is the name of the form parameter that the JSON payload - // will be in if a webhook has its content type set to application/x-www-form-urlencoded. - const payloadFormParam = "payload" - - var err error - if body, err = ioutil.ReadAll(r.Body); err != nil { - return nil, err - } - - // If the content type is application/x-www-form-urlencoded, - // the JSON payload will be under the "payload" form param. - form, err := url.ParseQuery(string(body)) - if err != nil { - return nil, err - } - payload = []byte(form.Get(payloadFormParam)) - - default: - return nil, fmt.Errorf("Webhook request has unsupported Content-Type %q", ct) - } - - sig := r.Header.Get(signatureHeader) - if err := validateSignature(sig, body, secretKey); err != nil { - return nil, err - } - return payload, nil -} - -// validateSignature validates the signature for the given payload. -// signature is the GitHub hash signature delivered in the X-Hub-Signature header. -// payload is the JSON payload sent by GitHub Webhooks. -// secretKey is the GitHub Webhook secret message. -// -// GitHub API docs: https://developer.github.com/webhooks/securing/#validating-payloads-from-github -func validateSignature(signature string, payload, secretKey []byte) error { - messageMAC, hashFunc, err := messageMAC(signature) - if err != nil { - return err - } - if !checkMAC(payload, messageMAC, secretKey, hashFunc) { - return errors.New("payload signature check failed") - } - return nil -} - -// WebHookType returns the event type of webhook request r. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#webhook-headers -func WebHookType(r *http.Request) string { - return r.Header.Get(eventTypeHeader) -} - -// DeliveryID returns the unique delivery ID of webhook request r. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#webhook-headers -func DeliveryID(r *http.Request) string { - return r.Header.Get(deliveryIDHeader) -} - -// ParseWebHook parses the event payload. For recognized event types, a -// value of the corresponding struct type will be returned (as returned -// by Event.ParsePayload()). An error will be returned for unrecognized event -// types. -// -// Example usage: -// -// func (s *GitHubEventMonitor) ServeHTTP(w http.ResponseWriter, r *http.Request) { -// payload, err := github.ValidatePayload(r, s.webhookSecretKey) -// if err != nil { ... } -// event, err := github.ParseWebHook(github.WebHookType(r), payload) -// if err != nil { ... } -// switch event := event.(type) { -// case *github.CommitCommentEvent: -// processCommitCommentEvent(event) -// case *github.CreateEvent: -// processCreateEvent(event) -// ... -// } -// } -// -func ParseWebHook(messageType string, payload []byte) (interface{}, error) { - eventType, ok := eventTypeMapping[messageType] - if !ok { - return nil, fmt.Errorf("unknown X-Github-Event in message: %v", messageType) - } - - event := Event{ - Type: &eventType, - RawPayload: (*json.RawMessage)(&payload), - } - return event.ParsePayload() -} diff --git a/vendor/github.com/google/go-github/github/migrations.go b/vendor/github.com/google/go-github/github/migrations.go deleted file mode 100644 index 90cc1fae85f..00000000000 --- a/vendor/github.com/google/go-github/github/migrations.go +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "errors" - "fmt" - "net/http" - "strings" -) - -// MigrationService provides access to the migration related functions -// in the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/migration/ -type MigrationService service - -// Migration represents a GitHub migration (archival). -type Migration struct { - ID *int64 `json:"id,omitempty"` - GUID *string `json:"guid,omitempty"` - // State is the current state of a migration. - // Possible values are: - // "pending" which means the migration hasn't started yet, - // "exporting" which means the migration is in progress, - // "exported" which means the migration finished successfully, or - // "failed" which means the migration failed. - State *string `json:"state,omitempty"` - // LockRepositories indicates whether repositories are locked (to prevent - // manipulation) while migrating data. - LockRepositories *bool `json:"lock_repositories,omitempty"` - // ExcludeAttachments indicates whether attachments should be excluded from - // the migration (to reduce migration archive file size). - ExcludeAttachments *bool `json:"exclude_attachments,omitempty"` - URL *string `json:"url,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` - Repositories []*Repository `json:"repositories,omitempty"` -} - -func (m Migration) String() string { - return Stringify(m) -} - -// MigrationOptions specifies the optional parameters to Migration methods. -type MigrationOptions struct { - // LockRepositories indicates whether repositories should be locked (to prevent - // manipulation) while migrating data. - LockRepositories bool - - // ExcludeAttachments indicates whether attachments should be excluded from - // the migration (to reduce migration archive file size). - ExcludeAttachments bool -} - -// startMigration represents the body of a StartMigration request. -type startMigration struct { - // Repositories is a slice of repository names to migrate. - Repositories []string `json:"repositories,omitempty"` - - // LockRepositories indicates whether repositories should be locked (to prevent - // manipulation) while migrating data. - LockRepositories *bool `json:"lock_repositories,omitempty"` - - // ExcludeAttachments indicates whether attachments should be excluded from - // the migration (to reduce migration archive file size). - ExcludeAttachments *bool `json:"exclude_attachments,omitempty"` -} - -// StartMigration starts the generation of a migration archive. -// repos is a slice of repository names to migrate. -// -// GitHub API docs: https://developer.github.com/v3/migration/migrations/#start-a-migration -func (s *MigrationService) StartMigration(ctx context.Context, org string, repos []string, opt *MigrationOptions) (*Migration, *Response, error) { - u := fmt.Sprintf("orgs/%v/migrations", org) - - body := &startMigration{Repositories: repos} - if opt != nil { - body.LockRepositories = Bool(opt.LockRepositories) - body.ExcludeAttachments = Bool(opt.ExcludeAttachments) - } - - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - m := &Migration{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// ListMigrations lists the most recent migrations. -// -// GitHub API docs: https://developer.github.com/v3/migration/migrations/#get-a-list-of-migrations -func (s *MigrationService) ListMigrations(ctx context.Context, org string) ([]*Migration, *Response, error) { - u := fmt.Sprintf("orgs/%v/migrations", org) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - var m []*Migration - resp, err := s.client.Do(ctx, req, &m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// MigrationStatus gets the status of a specific migration archive. -// id is the migration ID. -// -// GitHub API docs: https://developer.github.com/v3/migration/migrations/#get-the-status-of-a-migration -func (s *MigrationService) MigrationStatus(ctx context.Context, org string, id int64) (*Migration, *Response, error) { - u := fmt.Sprintf("orgs/%v/migrations/%v", org, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - m := &Migration{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// MigrationArchiveURL fetches a migration archive URL. -// id is the migration ID. -// -// GitHub API docs: https://developer.github.com/v3/migration/migrations/#download-a-migration-archive -func (s *MigrationService) MigrationArchiveURL(ctx context.Context, org string, id int64) (url string, err error) { - u := fmt.Sprintf("orgs/%v/migrations/%v/archive", org, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return "", err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - s.client.clientMu.Lock() - defer s.client.clientMu.Unlock() - - // Disable the redirect mechanism because AWS fails if the GitHub auth token is provided. - var loc string - saveRedirect := s.client.client.CheckRedirect - s.client.client.CheckRedirect = func(req *http.Request, via []*http.Request) error { - loc = req.URL.String() - return errors.New("disable redirect") - } - defer func() { s.client.client.CheckRedirect = saveRedirect }() - - _, err = s.client.Do(ctx, req, nil) // expect error from disable redirect - if err == nil { - return "", errors.New("expected redirect, none provided") - } - if !strings.Contains(err.Error(), "disable redirect") { - return "", err - } - return loc, nil -} - -// DeleteMigration deletes a previous migration archive. -// id is the migration ID. -// -// GitHub API docs: https://developer.github.com/v3/migration/migrations/#delete-a-migration-archive -func (s *MigrationService) DeleteMigration(ctx context.Context, org string, id int64) (*Response, error) { - u := fmt.Sprintf("orgs/%v/migrations/%v/archive", org, id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - return s.client.Do(ctx, req, nil) -} - -// UnlockRepo unlocks a repository that was locked for migration. -// id is the migration ID. -// You should unlock each migrated repository and delete them when the migration -// is complete and you no longer need the source data. -// -// GitHub API docs: https://developer.github.com/v3/migration/migrations/#unlock-a-repository -func (s *MigrationService) UnlockRepo(ctx context.Context, org string, id int64, repo string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/migrations/%v/repos/%v/lock", org, id, repo) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/migrations_source_import.go b/vendor/github.com/google/go-github/github/migrations_source_import.go deleted file mode 100644 index fd45e780065..00000000000 --- a/vendor/github.com/google/go-github/github/migrations_source_import.go +++ /dev/null @@ -1,329 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// Import represents a repository import request. -type Import struct { - // The URL of the originating repository. - VCSURL *string `json:"vcs_url,omitempty"` - // The originating VCS type. Can be one of 'subversion', 'git', - // 'mercurial', or 'tfvc'. Without this parameter, the import job will - // take additional time to detect the VCS type before beginning the - // import. This detection step will be reflected in the response. - VCS *string `json:"vcs,omitempty"` - // VCSUsername and VCSPassword are only used for StartImport calls that - // are importing a password-protected repository. - VCSUsername *string `json:"vcs_username,omitempty"` - VCSPassword *string `json:"vcs_password,omitempty"` - // For a tfvc import, the name of the project that is being imported. - TFVCProject *string `json:"tfvc_project,omitempty"` - - // LFS related fields that may be preset in the Import Progress response - - // Describes whether the import has been opted in or out of using Git - // LFS. The value can be 'opt_in', 'opt_out', or 'undecided' if no - // action has been taken. - UseLFS *string `json:"use_lfs,omitempty"` - // Describes whether files larger than 100MB were found during the - // importing step. - HasLargeFiles *bool `json:"has_large_files,omitempty"` - // The total size in gigabytes of files larger than 100MB found in the - // originating repository. - LargeFilesSize *int `json:"large_files_size,omitempty"` - // The total number of files larger than 100MB found in the originating - // repository. To see a list of these files, call LargeFiles. - LargeFilesCount *int `json:"large_files_count,omitempty"` - - // Identifies the current status of an import. An import that does not - // have errors will progress through these steps: - // - // detecting - the "detection" step of the import is in progress - // because the request did not include a VCS parameter. The - // import is identifying the type of source control present at - // the URL. - // importing - the "raw" step of the import is in progress. This is - // where commit data is fetched from the original repository. - // The import progress response will include CommitCount (the - // total number of raw commits that will be imported) and - // Percent (0 - 100, the current progress through the import). - // mapping - the "rewrite" step of the import is in progress. This - // is where SVN branches are converted to Git branches, and - // where author updates are applied. The import progress - // response does not include progress information. - // pushing - the "push" step of the import is in progress. This is - // where the importer updates the repository on GitHub. The - // import progress response will include PushPercent, which is - // the percent value reported by git push when it is "Writing - // objects". - // complete - the import is complete, and the repository is ready - // on GitHub. - // - // If there are problems, you will see one of these in the status field: - // - // auth_failed - the import requires authentication in order to - // connect to the original repository. Make an UpdateImport - // request, and include VCSUsername and VCSPassword. - // error - the import encountered an error. The import progress - // response will include the FailedStep and an error message. - // Contact GitHub support for more information. - // detection_needs_auth - the importer requires authentication for - // the originating repository to continue detection. Make an - // UpdatImport request, and include VCSUsername and - // VCSPassword. - // detection_found_nothing - the importer didn't recognize any - // source control at the URL. - // detection_found_multiple - the importer found several projects - // or repositories at the provided URL. When this is the case, - // the Import Progress response will also include a - // ProjectChoices field with the possible project choices as - // values. Make an UpdateImport request, and include VCS and - // (if applicable) TFVCProject. - Status *string `json:"status,omitempty"` - CommitCount *int `json:"commit_count,omitempty"` - StatusText *string `json:"status_text,omitempty"` - AuthorsCount *int `json:"authors_count,omitempty"` - Percent *int `json:"percent,omitempty"` - PushPercent *int `json:"push_percent,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - AuthorsURL *string `json:"authors_url,omitempty"` - RepositoryURL *string `json:"repository_url,omitempty"` - Message *string `json:"message,omitempty"` - FailedStep *string `json:"failed_step,omitempty"` - - // Human readable display name, provided when the Import appears as - // part of ProjectChoices. - HumanName *string `json:"human_name,omitempty"` - - // When the importer finds several projects or repositories at the - // provided URLs, this will identify the available choices. Call - // UpdateImport with the selected Import value. - ProjectChoices []Import `json:"project_choices,omitempty"` -} - -func (i Import) String() string { - return Stringify(i) -} - -// SourceImportAuthor identifies an author imported from a source repository. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-commit-authors -type SourceImportAuthor struct { - ID *int64 `json:"id,omitempty"` - RemoteID *string `json:"remote_id,omitempty"` - RemoteName *string `json:"remote_name,omitempty"` - Email *string `json:"email,omitempty"` - Name *string `json:"name,omitempty"` - URL *string `json:"url,omitempty"` - ImportURL *string `json:"import_url,omitempty"` -} - -func (a SourceImportAuthor) String() string { - return Stringify(a) -} - -// LargeFile identifies a file larger than 100MB found during a repository import. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-large-files -type LargeFile struct { - RefName *string `json:"ref_name,omitempty"` - Path *string `json:"path,omitempty"` - OID *string `json:"oid,omitempty"` - Size *int `json:"size,omitempty"` -} - -func (f LargeFile) String() string { - return Stringify(f) -} - -// StartImport initiates a repository import. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#start-an-import -func (s *MigrationService) StartImport(ctx context.Context, owner, repo string, in *Import) (*Import, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import", owner, repo) - req, err := s.client.NewRequest("PUT", u, in) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - out := new(Import) - resp, err := s.client.Do(ctx, req, out) - if err != nil { - return nil, resp, err - } - - return out, resp, nil -} - -// ImportProgress queries for the status and progress of an ongoing repository import. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-import-progress -func (s *MigrationService) ImportProgress(ctx context.Context, owner, repo string) (*Import, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - out := new(Import) - resp, err := s.client.Do(ctx, req, out) - if err != nil { - return nil, resp, err - } - - return out, resp, nil -} - -// UpdateImport initiates a repository import. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#update-existing-import -func (s *MigrationService) UpdateImport(ctx context.Context, owner, repo string, in *Import) (*Import, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import", owner, repo) - req, err := s.client.NewRequest("PATCH", u, in) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - out := new(Import) - resp, err := s.client.Do(ctx, req, out) - if err != nil { - return nil, resp, err - } - - return out, resp, nil -} - -// CommitAuthors gets the authors mapped from the original repository. -// -// Each type of source control system represents authors in a different way. -// For example, a Git commit author has a display name and an email address, -// but a Subversion commit author just has a username. The GitHub Importer will -// make the author information valid, but the author might not be correct. For -// example, it will change the bare Subversion username "hubot" into something -// like "hubot ". -// -// This method and MapCommitAuthor allow you to provide correct Git author -// information. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-commit-authors -func (s *MigrationService) CommitAuthors(ctx context.Context, owner, repo string) ([]*SourceImportAuthor, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import/authors", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - var authors []*SourceImportAuthor - resp, err := s.client.Do(ctx, req, &authors) - if err != nil { - return nil, resp, err - } - - return authors, resp, nil -} - -// MapCommitAuthor updates an author's identity for the import. Your -// application can continue updating authors any time before you push new -// commits to the repository. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#map-a-commit-author -func (s *MigrationService) MapCommitAuthor(ctx context.Context, owner, repo string, id int64, author *SourceImportAuthor) (*SourceImportAuthor, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import/authors/%v", owner, repo, id) - req, err := s.client.NewRequest("PATCH", u, author) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - out := new(SourceImportAuthor) - resp, err := s.client.Do(ctx, req, out) - if err != nil { - return nil, resp, err - } - - return out, resp, nil -} - -// SetLFSPreference sets whether imported repositories should use Git LFS for -// files larger than 100MB. Only the UseLFS field on the provided Import is -// used. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#set-git-lfs-preference -func (s *MigrationService) SetLFSPreference(ctx context.Context, owner, repo string, in *Import) (*Import, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import/lfs", owner, repo) - req, err := s.client.NewRequest("PATCH", u, in) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - out := new(Import) - resp, err := s.client.Do(ctx, req, out) - if err != nil { - return nil, resp, err - } - - return out, resp, nil -} - -// LargeFiles lists files larger than 100MB found during the import. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-large-files -func (s *MigrationService) LargeFiles(ctx context.Context, owner, repo string) ([]*LargeFile, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import/large_files", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - var files []*LargeFile - resp, err := s.client.Do(ctx, req, &files) - if err != nil { - return nil, resp, err - } - - return files, resp, nil -} - -// CancelImport stops an import for a repository. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#cancel-an-import -func (s *MigrationService) CancelImport(ctx context.Context, owner, repo string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/import", owner, repo) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/misc.go b/vendor/github.com/google/go-github/github/misc.go deleted file mode 100644 index 5b8082d3ce5..00000000000 --- a/vendor/github.com/google/go-github/github/misc.go +++ /dev/null @@ -1,253 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "bytes" - "context" - "fmt" - "net/url" -) - -// MarkdownOptions specifies optional parameters to the Markdown method. -type MarkdownOptions struct { - // Mode identifies the rendering mode. Possible values are: - // markdown - render a document as plain Markdown, just like - // README files are rendered. - // - // gfm - to render a document as user-content, e.g. like user - // comments or issues are rendered. In GFM mode, hard line breaks are - // always taken into account, and issue and user mentions are linked - // accordingly. - // - // Default is "markdown". - Mode string - - // Context identifies the repository context. Only taken into account - // when rendering as "gfm". - Context string -} - -type markdownRequest struct { - Text *string `json:"text,omitempty"` - Mode *string `json:"mode,omitempty"` - Context *string `json:"context,omitempty"` -} - -// Markdown renders an arbitrary Markdown document. -// -// GitHub API docs: https://developer.github.com/v3/markdown/ -func (c *Client) Markdown(ctx context.Context, text string, opt *MarkdownOptions) (string, *Response, error) { - request := &markdownRequest{Text: String(text)} - if opt != nil { - if opt.Mode != "" { - request.Mode = String(opt.Mode) - } - if opt.Context != "" { - request.Context = String(opt.Context) - } - } - - req, err := c.NewRequest("POST", "markdown", request) - if err != nil { - return "", nil, err - } - - buf := new(bytes.Buffer) - resp, err := c.Do(ctx, req, buf) - if err != nil { - return "", resp, err - } - - return buf.String(), resp, nil -} - -// ListEmojis returns the emojis available to use on GitHub. -// -// GitHub API docs: https://developer.github.com/v3/emojis/ -func (c *Client) ListEmojis(ctx context.Context) (map[string]string, *Response, error) { - req, err := c.NewRequest("GET", "emojis", nil) - if err != nil { - return nil, nil, err - } - - var emoji map[string]string - resp, err := c.Do(ctx, req, &emoji) - if err != nil { - return nil, resp, err - } - - return emoji, resp, nil -} - -// CodeOfConduct represents a code of conduct. -type CodeOfConduct struct { - Name *string `json:"name,omitempty"` - Key *string `json:"key,omitempty"` - URL *string `json:"url,omitempty"` - Body *string `json:"body,omitempty"` -} - -func (c *CodeOfConduct) String() string { - return Stringify(c) -} - -// ListCodesOfConduct returns all codes of conduct. -// -// GitHub API docs: https://developer.github.com/v3/codes_of_conduct/#list-all-codes-of-conduct -func (c *Client) ListCodesOfConduct(ctx context.Context) ([]*CodeOfConduct, *Response, error) { - req, err := c.NewRequest("GET", "codes_of_conduct", nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeCodesOfConductPreview) - - var cs []*CodeOfConduct - resp, err := c.Do(ctx, req, &cs) - if err != nil { - return nil, resp, err - } - - return cs, resp, nil -} - -// GetCodeOfConduct returns an individual code of conduct. -// -// https://developer.github.com/v3/codes_of_conduct/#get-an-individual-code-of-conduct -func (c *Client) GetCodeOfConduct(ctx context.Context, key string) (*CodeOfConduct, *Response, error) { - u := fmt.Sprintf("codes_of_conduct/%s", key) - req, err := c.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeCodesOfConductPreview) - - coc := new(CodeOfConduct) - resp, err := c.Do(ctx, req, coc) - if err != nil { - return nil, resp, err - } - - return coc, resp, nil -} - -// APIMeta represents metadata about the GitHub API. -type APIMeta struct { - // An Array of IP addresses in CIDR format specifying the addresses - // that incoming service hooks will originate from on GitHub.com. - Hooks []string `json:"hooks,omitempty"` - - // An Array of IP addresses in CIDR format specifying the Git servers - // for GitHub.com. - Git []string `json:"git,omitempty"` - - // Whether authentication with username and password is supported. - // (GitHub Enterprise instances using CAS or OAuth for authentication - // will return false. Features like Basic Authentication with a - // username and password, sudo mode, and two-factor authentication are - // not supported on these servers.) - VerifiablePasswordAuthentication *bool `json:"verifiable_password_authentication,omitempty"` - - // An array of IP addresses in CIDR format specifying the addresses - // which serve GitHub Pages websites. - Pages []string `json:"pages,omitempty"` -} - -// APIMeta returns information about GitHub.com, the service. Or, if you access -// this endpoint on your organization’s GitHub Enterprise installation, this -// endpoint provides information about that installation. -// -// GitHub API docs: https://developer.github.com/v3/meta/ -func (c *Client) APIMeta(ctx context.Context) (*APIMeta, *Response, error) { - req, err := c.NewRequest("GET", "meta", nil) - if err != nil { - return nil, nil, err - } - - meta := new(APIMeta) - resp, err := c.Do(ctx, req, meta) - if err != nil { - return nil, resp, err - } - - return meta, resp, nil -} - -// Octocat returns an ASCII art octocat with the specified message in a speech -// bubble. If message is empty, a random zen phrase is used. -func (c *Client) Octocat(ctx context.Context, message string) (string, *Response, error) { - u := "octocat" - if message != "" { - u = fmt.Sprintf("%s?s=%s", u, url.QueryEscape(message)) - } - - req, err := c.NewRequest("GET", u, nil) - if err != nil { - return "", nil, err - } - - buf := new(bytes.Buffer) - resp, err := c.Do(ctx, req, buf) - if err != nil { - return "", resp, err - } - - return buf.String(), resp, nil -} - -// Zen returns a random line from The Zen of GitHub. -// -// see also: http://warpspire.com/posts/taste/ -func (c *Client) Zen(ctx context.Context) (string, *Response, error) { - req, err := c.NewRequest("GET", "zen", nil) - if err != nil { - return "", nil, err - } - - buf := new(bytes.Buffer) - resp, err := c.Do(ctx, req, buf) - if err != nil { - return "", resp, err - } - - return buf.String(), resp, nil -} - -// ServiceHook represents a hook that has configuration settings, a list of -// available events, and default events. -type ServiceHook struct { - Name *string `json:"name,omitempty"` - Events []string `json:"events,omitempty"` - SupportedEvents []string `json:"supported_events,omitempty"` - Schema [][]string `json:"schema,omitempty"` -} - -func (s *ServiceHook) String() string { - return Stringify(s) -} - -// ListServiceHooks lists all of the available service hooks. -// -// GitHub API docs: https://developer.github.com/webhooks/#services -func (c *Client) ListServiceHooks(ctx context.Context) ([]*ServiceHook, *Response, error) { - u := "hooks" - req, err := c.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var hooks []*ServiceHook - resp, err := c.Do(ctx, req, &hooks) - if err != nil { - return nil, resp, err - } - - return hooks, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/orgs.go b/vendor/github.com/google/go-github/github/orgs.go deleted file mode 100644 index 976a5fca2f4..00000000000 --- a/vendor/github.com/google/go-github/github/orgs.go +++ /dev/null @@ -1,209 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// OrganizationsService provides access to the organization related functions -// in the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/orgs/ -type OrganizationsService service - -// Organization represents a GitHub organization account. -type Organization struct { - Login *string `json:"login,omitempty"` - ID *int64 `json:"id,omitempty"` - AvatarURL *string `json:"avatar_url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - Name *string `json:"name,omitempty"` - Company *string `json:"company,omitempty"` - Blog *string `json:"blog,omitempty"` - Location *string `json:"location,omitempty"` - Email *string `json:"email,omitempty"` - Description *string `json:"description,omitempty"` - PublicRepos *int `json:"public_repos,omitempty"` - PublicGists *int `json:"public_gists,omitempty"` - Followers *int `json:"followers,omitempty"` - Following *int `json:"following,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - TotalPrivateRepos *int `json:"total_private_repos,omitempty"` - OwnedPrivateRepos *int `json:"owned_private_repos,omitempty"` - PrivateGists *int `json:"private_gists,omitempty"` - DiskUsage *int `json:"disk_usage,omitempty"` - Collaborators *int `json:"collaborators,omitempty"` - BillingEmail *string `json:"billing_email,omitempty"` - Type *string `json:"type,omitempty"` - Plan *Plan `json:"plan,omitempty"` - NodeID *string `json:"node_id,omitempty"` - - // API URLs - URL *string `json:"url,omitempty"` - EventsURL *string `json:"events_url,omitempty"` - HooksURL *string `json:"hooks_url,omitempty"` - IssuesURL *string `json:"issues_url,omitempty"` - MembersURL *string `json:"members_url,omitempty"` - PublicMembersURL *string `json:"public_members_url,omitempty"` - ReposURL *string `json:"repos_url,omitempty"` -} - -func (o Organization) String() string { - return Stringify(o) -} - -// Plan represents the payment plan for an account. See plans at https://github.com/plans. -type Plan struct { - Name *string `json:"name,omitempty"` - Space *int `json:"space,omitempty"` - Collaborators *int `json:"collaborators,omitempty"` - PrivateRepos *int `json:"private_repos,omitempty"` -} - -func (p Plan) String() string { - return Stringify(p) -} - -// OrganizationsListOptions specifies the optional parameters to the -// OrganizationsService.ListAll method. -type OrganizationsListOptions struct { - // Since filters Organizations by ID. - Since int `url:"since,omitempty"` - - ListOptions -} - -// ListAll lists all organizations, in the order that they were created on GitHub. -// -// Note: Pagination is powered exclusively by the since parameter. To continue -// listing the next set of organizations, use the ID of the last-returned organization -// as the opts.Since parameter for the next call. -// -// GitHub API docs: https://developer.github.com/v3/orgs/#list-all-organizations -func (s *OrganizationsService) ListAll(ctx context.Context, opt *OrganizationsListOptions) ([]*Organization, *Response, error) { - u, err := addOptions("organizations", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - orgs := []*Organization{} - resp, err := s.client.Do(ctx, req, &orgs) - if err != nil { - return nil, resp, err - } - return orgs, resp, nil -} - -// List the organizations for a user. Passing the empty string will list -// organizations for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/orgs/#list-user-organizations -func (s *OrganizationsService) List(ctx context.Context, user string, opt *ListOptions) ([]*Organization, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/orgs", user) - } else { - u = "user/orgs" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - var orgs []*Organization - resp, err := s.client.Do(ctx, req, &orgs) - if err != nil { - return nil, resp, err - } - - return orgs, resp, nil -} - -// Get fetches an organization by name. -// -// GitHub API docs: https://developer.github.com/v3/orgs/#get-an-organization -func (s *OrganizationsService) Get(ctx context.Context, org string) (*Organization, *Response, error) { - u := fmt.Sprintf("orgs/%v", org) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - organization := new(Organization) - resp, err := s.client.Do(ctx, req, organization) - if err != nil { - return nil, resp, err - } - - return organization, resp, nil -} - -// GetByID fetches an organization. -// -// Note: GetByID uses the undocumented GitHub API endpoint /organizations/:id. -func (s *OrganizationsService) GetByID(ctx context.Context, id int64) (*Organization, *Response, error) { - u := fmt.Sprintf("organizations/%d", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - organization := new(Organization) - resp, err := s.client.Do(ctx, req, organization) - if err != nil { - return nil, resp, err - } - - return organization, resp, nil -} - -// Edit an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/#edit-an-organization -func (s *OrganizationsService) Edit(ctx context.Context, name string, org *Organization) (*Organization, *Response, error) { - u := fmt.Sprintf("orgs/%v", name) - req, err := s.client.NewRequest("PATCH", u, org) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - o := new(Organization) - resp, err := s.client.Do(ctx, req, o) - if err != nil { - return nil, resp, err - } - - return o, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/orgs_hooks.go b/vendor/github.com/google/go-github/github/orgs_hooks.go deleted file mode 100644 index 4fc692e0f63..00000000000 --- a/vendor/github.com/google/go-github/github/orgs_hooks.go +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2015 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ListHooks lists all Hooks for the specified organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#list-hooks -func (s *OrganizationsService) ListHooks(ctx context.Context, org string, opt *ListOptions) ([]*Hook, *Response, error) { - u := fmt.Sprintf("orgs/%v/hooks", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var hooks []*Hook - resp, err := s.client.Do(ctx, req, &hooks) - if err != nil { - return nil, resp, err - } - - return hooks, resp, nil -} - -// GetHook returns a single specified Hook. -// -// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#get-single-hook -func (s *OrganizationsService) GetHook(ctx context.Context, org string, id int) (*Hook, *Response, error) { - u := fmt.Sprintf("orgs/%v/hooks/%d", org, id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - hook := new(Hook) - resp, err := s.client.Do(ctx, req, hook) - return hook, resp, err -} - -// CreateHook creates a Hook for the specified org. -// Name and Config are required fields. -// -// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#create-a-hook -func (s *OrganizationsService) CreateHook(ctx context.Context, org string, hook *Hook) (*Hook, *Response, error) { - u := fmt.Sprintf("orgs/%v/hooks", org) - req, err := s.client.NewRequest("POST", u, hook) - if err != nil { - return nil, nil, err - } - - h := new(Hook) - resp, err := s.client.Do(ctx, req, h) - if err != nil { - return nil, resp, err - } - - return h, resp, nil -} - -// EditHook updates a specified Hook. -// -// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#edit-a-hook -func (s *OrganizationsService) EditHook(ctx context.Context, org string, id int, hook *Hook) (*Hook, *Response, error) { - u := fmt.Sprintf("orgs/%v/hooks/%d", org, id) - req, err := s.client.NewRequest("PATCH", u, hook) - if err != nil { - return nil, nil, err - } - h := new(Hook) - resp, err := s.client.Do(ctx, req, h) - return h, resp, err -} - -// PingHook triggers a 'ping' event to be sent to the Hook. -// -// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#ping-a-hook -func (s *OrganizationsService) PingHook(ctx context.Context, org string, id int) (*Response, error) { - u := fmt.Sprintf("orgs/%v/hooks/%d/pings", org, id) - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// DeleteHook deletes a specified Hook. -// -// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#delete-a-hook -func (s *OrganizationsService) DeleteHook(ctx context.Context, org string, id int) (*Response, error) { - u := fmt.Sprintf("orgs/%v/hooks/%d", org, id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/orgs_members.go b/vendor/github.com/google/go-github/github/orgs_members.go deleted file mode 100644 index d0ea6a985e1..00000000000 --- a/vendor/github.com/google/go-github/github/orgs_members.go +++ /dev/null @@ -1,299 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// Membership represents the status of a user's membership in an organization or team. -type Membership struct { - URL *string `json:"url,omitempty"` - - // State is the user's status within the organization or team. - // Possible values are: "active", "pending" - State *string `json:"state,omitempty"` - - // Role identifies the user's role within the organization or team. - // Possible values for organization membership: - // member - non-owner organization member - // admin - organization owner - // - // Possible values for team membership are: - // member - a normal member of the team - // maintainer - a team maintainer. Able to add/remove other team - // members, promote other team members to team - // maintainer, and edit the team’s name and description - Role *string `json:"role,omitempty"` - - // For organization membership, the API URL of the organization. - OrganizationURL *string `json:"organization_url,omitempty"` - - // For organization membership, the organization the membership is for. - Organization *Organization `json:"organization,omitempty"` - - // For organization membership, the user the membership is for. - User *User `json:"user,omitempty"` -} - -func (m Membership) String() string { - return Stringify(m) -} - -// ListMembersOptions specifies optional parameters to the -// OrganizationsService.ListMembers method. -type ListMembersOptions struct { - // If true (or if the authenticated user is not an owner of the - // organization), list only publicly visible members. - PublicOnly bool `url:"-"` - - // Filter members returned in the list. Possible values are: - // 2fa_disabled, all. Default is "all". - Filter string `url:"filter,omitempty"` - - // Role filters members returned by their role in the organization. - // Possible values are: - // all - all members of the organization, regardless of role - // admin - organization owners - // member - non-organization members - // - // Default is "all". - Role string `url:"role,omitempty"` - - ListOptions -} - -// ListMembers lists the members for an organization. If the authenticated -// user is an owner of the organization, this will return both concealed and -// public members, otherwise it will only return public members. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#members-list -func (s *OrganizationsService) ListMembers(ctx context.Context, org string, opt *ListMembersOptions) ([]*User, *Response, error) { - var u string - if opt != nil && opt.PublicOnly { - u = fmt.Sprintf("orgs/%v/public_members", org) - } else { - u = fmt.Sprintf("orgs/%v/members", org) - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var members []*User - resp, err := s.client.Do(ctx, req, &members) - if err != nil { - return nil, resp, err - } - - return members, resp, nil -} - -// IsMember checks if a user is a member of an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#check-membership -func (s *OrganizationsService) IsMember(ctx context.Context, org, user string) (bool, *Response, error) { - u := fmt.Sprintf("orgs/%v/members/%v", org, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - resp, err := s.client.Do(ctx, req, nil) - member, err := parseBoolResponse(err) - return member, resp, err -} - -// IsPublicMember checks if a user is a public member of an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#check-public-membership -func (s *OrganizationsService) IsPublicMember(ctx context.Context, org, user string) (bool, *Response, error) { - u := fmt.Sprintf("orgs/%v/public_members/%v", org, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - resp, err := s.client.Do(ctx, req, nil) - member, err := parseBoolResponse(err) - return member, resp, err -} - -// RemoveMember removes a user from all teams of an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#remove-a-member -func (s *OrganizationsService) RemoveMember(ctx context.Context, org, user string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/members/%v", org, user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// PublicizeMembership publicizes a user's membership in an organization. (A -// user cannot publicize the membership for another user.) -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#publicize-a-users-membership -func (s *OrganizationsService) PublicizeMembership(ctx context.Context, org, user string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/public_members/%v", org, user) - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ConcealMembership conceals a user's membership in an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#conceal-a-users-membership -func (s *OrganizationsService) ConcealMembership(ctx context.Context, org, user string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/public_members/%v", org, user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ListOrgMembershipsOptions specifies optional parameters to the -// OrganizationsService.ListOrgMemberships method. -type ListOrgMembershipsOptions struct { - // Filter memberships to include only those with the specified state. - // Possible values are: "active", "pending". - State string `url:"state,omitempty"` - - ListOptions -} - -// ListOrgMemberships lists the organization memberships for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#list-your-organization-memberships -func (s *OrganizationsService) ListOrgMemberships(ctx context.Context, opt *ListOrgMembershipsOptions) ([]*Membership, *Response, error) { - u := "user/memberships/orgs" - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var memberships []*Membership - resp, err := s.client.Do(ctx, req, &memberships) - if err != nil { - return nil, resp, err - } - - return memberships, resp, nil -} - -// GetOrgMembership gets the membership for a user in a specified organization. -// Passing an empty string for user will get the membership for the -// authenticated user. -// -// GitHub API docs: -// https://developer.github.com/v3/orgs/members/#get-organization-membership -// https://developer.github.com/v3/orgs/members/#get-your-organization-membership -func (s *OrganizationsService) GetOrgMembership(ctx context.Context, user, org string) (*Membership, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("orgs/%v/memberships/%v", org, user) - } else { - u = fmt.Sprintf("user/memberships/orgs/%v", org) - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - membership := new(Membership) - resp, err := s.client.Do(ctx, req, membership) - if err != nil { - return nil, resp, err - } - - return membership, resp, nil -} - -// EditOrgMembership edits the membership for user in specified organization. -// Passing an empty string for user will edit the membership for the -// authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#add-or-update-organization-membership -// GitHub API docs: https://developer.github.com/v3/orgs/members/#edit-your-organization-membership -func (s *OrganizationsService) EditOrgMembership(ctx context.Context, user, org string, membership *Membership) (*Membership, *Response, error) { - var u, method string - if user != "" { - u = fmt.Sprintf("orgs/%v/memberships/%v", org, user) - method = "PUT" - } else { - u = fmt.Sprintf("user/memberships/orgs/%v", org) - method = "PATCH" - } - - req, err := s.client.NewRequest(method, u, membership) - if err != nil { - return nil, nil, err - } - - m := new(Membership) - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// RemoveOrgMembership removes user from the specified organization. If the -// user has been invited to the organization, this will cancel their invitation. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#remove-organization-membership -func (s *OrganizationsService) RemoveOrgMembership(ctx context.Context, user, org string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/memberships/%v", org, user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ListPendingOrgInvitations returns a list of pending invitations. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#list-pending-organization-invitations -func (s *OrganizationsService) ListPendingOrgInvitations(ctx context.Context, org string, opt *ListOptions) ([]*Invitation, *Response, error) { - u := fmt.Sprintf("orgs/%v/invitations", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var pendingInvitations []*Invitation - resp, err := s.client.Do(ctx, req, &pendingInvitations) - if err != nil { - return nil, resp, err - } - return pendingInvitations, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/orgs_outside_collaborators.go b/vendor/github.com/google/go-github/github/orgs_outside_collaborators.go deleted file mode 100644 index 85ffd05f61a..00000000000 --- a/vendor/github.com/google/go-github/github/orgs_outside_collaborators.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ListOutsideCollaboratorsOptions specifies optional parameters to the -// OrganizationsService.ListOutsideCollaborators method. -type ListOutsideCollaboratorsOptions struct { - // Filter outside collaborators returned in the list. Possible values are: - // 2fa_disabled, all. Default is "all". - Filter string `url:"filter,omitempty"` - - ListOptions -} - -// ListOutsideCollaborators lists outside collaborators of organization's repositories. -// This will only work if the authenticated -// user is an owner of the organization. -// -// Warning: The API may change without advance notice during the preview period. -// Preview features are not supported for production use. -// -// GitHub API docs: https://developer.github.com/v3/orgs/outside_collaborators/#list-outside-collaborators -func (s *OrganizationsService) ListOutsideCollaborators(ctx context.Context, org string, opt *ListOutsideCollaboratorsOptions) ([]*User, *Response, error) { - u := fmt.Sprintf("orgs/%v/outside_collaborators", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var members []*User - resp, err := s.client.Do(ctx, req, &members) - if err != nil { - return nil, resp, err - } - - return members, resp, nil -} - -// RemoveOutsideCollaborator removes a user from the list of outside collaborators; -// consequently, removing them from all the organization's repositories. -// -// GitHub API docs: https://developer.github.com/v3/orgs/outside_collaborators/#remove-outside-collaborator -func (s *OrganizationsService) RemoveOutsideCollaborator(ctx context.Context, org string, user string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/outside_collaborators/%v", org, user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ConvertMemberToOutsideCollaborator reduces the permission level of a member of the -// organization to that of an outside collaborator. Therefore, they will only -// have access to the repositories that their current team membership allows. -// Responses for converting a non-member or the last owner to an outside collaborator -// are listed in GitHub API docs. -// -// GitHub API docs: https://developer.github.com/v3/orgs/outside_collaborators/#convert-member-to-outside-collaborator -func (s *OrganizationsService) ConvertMemberToOutsideCollaborator(ctx context.Context, org string, user string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/outside_collaborators/%v", org, user) - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/orgs_projects.go b/vendor/github.com/google/go-github/github/orgs_projects.go deleted file mode 100644 index e57cba97829..00000000000 --- a/vendor/github.com/google/go-github/github/orgs_projects.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ListProjects lists the projects for an organization. -// -// GitHub API docs: https://developer.github.com/v3/projects/#list-organization-projects -func (s *OrganizationsService) ListProjects(ctx context.Context, org string, opt *ProjectListOptions) ([]*Project, *Response, error) { - u := fmt.Sprintf("orgs/%v/projects", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - var projects []*Project - resp, err := s.client.Do(ctx, req, &projects) - if err != nil { - return nil, resp, err - } - - return projects, resp, nil -} - -// CreateProject creates a GitHub Project for the specified organization. -// -// GitHub API docs: https://developer.github.com/v3/projects/#create-an-organization-project -func (s *OrganizationsService) CreateProject(ctx context.Context, org string, opt *ProjectOptions) (*Project, *Response, error) { - u := fmt.Sprintf("orgs/%v/projects", org) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - project := &Project{} - resp, err := s.client.Do(ctx, req, project) - if err != nil { - return nil, resp, err - } - - return project, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/orgs_teams.go b/vendor/github.com/google/go-github/github/orgs_teams.go deleted file mode 100644 index c145710881a..00000000000 --- a/vendor/github.com/google/go-github/github/orgs_teams.go +++ /dev/null @@ -1,512 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "strings" - "time" -) - -// Team represents a team within a GitHub organization. Teams are used to -// manage access to an organization's repositories. -type Team struct { - ID *int64 `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Description *string `json:"description,omitempty"` - URL *string `json:"url,omitempty"` - Slug *string `json:"slug,omitempty"` - - // Permission specifies the default permission for repositories owned by the team. - Permission *string `json:"permission,omitempty"` - - // Privacy identifies the level of privacy this team should have. - // Possible values are: - // secret - only visible to organization owners and members of this team - // closed - visible to all members of this organization - // Default is "secret". - Privacy *string `json:"privacy,omitempty"` - - MembersCount *int `json:"members_count,omitempty"` - ReposCount *int `json:"repos_count,omitempty"` - Organization *Organization `json:"organization,omitempty"` - MembersURL *string `json:"members_url,omitempty"` - RepositoriesURL *string `json:"repositories_url,omitempty"` - Parent *Team `json:"parent,omitempty"` - - // LDAPDN is only available in GitHub Enterprise and when the team - // membership is synchronized with LDAP. - LDAPDN *string `json:"ldap_dn,omitempty"` -} - -func (t Team) String() string { - return Stringify(t) -} - -// Invitation represents a team member's invitation status. -type Invitation struct { - ID *int64 `json:"id,omitempty"` - Login *string `json:"login,omitempty"` - Email *string `json:"email,omitempty"` - // Role can be one of the values - 'direct_member', 'admin', 'billing_manager', 'hiring_manager', or 'reinstate'. - Role *string `json:"role,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - Inviter *User `json:"inviter,omitempty"` -} - -func (i Invitation) String() string { - return Stringify(i) -} - -// ListTeams lists all of the teams for an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#list-teams -func (s *OrganizationsService) ListTeams(ctx context.Context, org string, opt *ListOptions) ([]*Team, *Response, error) { - u := fmt.Sprintf("orgs/%v/teams", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - var teams []*Team - resp, err := s.client.Do(ctx, req, &teams) - if err != nil { - return nil, resp, err - } - - return teams, resp, nil -} - -// GetTeam fetches a team by ID. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#get-team -func (s *OrganizationsService) GetTeam(ctx context.Context, team int64) (*Team, *Response, error) { - u := fmt.Sprintf("teams/%v", team) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - t := new(Team) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} - -// NewTeam represents a team to be created or modified. -type NewTeam struct { - Name string `json:"name"` // Name of the team. (Required.) - Description *string `json:"description,omitempty"` - Maintainers []string `json:"maintainers,omitempty"` - RepoNames []string `json:"repo_names,omitempty"` - ParentTeamID *int64 `json:"parent_team_id,omitempty"` - - // Deprecated: Permission is deprecated when creating or editing a team in an org - // using the new GitHub permission model. It no longer identifies the - // permission a team has on its repos, but only specifies the default - // permission a repo is initially added with. Avoid confusion by - // specifying a permission value when calling AddTeamRepo. - Permission *string `json:"permission,omitempty"` - - // Privacy identifies the level of privacy this team should have. - // Possible values are: - // secret - only visible to organization owners and members of this team - // closed - visible to all members of this organization - // Default is "secret". - Privacy *string `json:"privacy,omitempty"` - - // LDAPDN may be used in GitHub Enterprise when the team membership - // is synchronized with LDAP. - LDAPDN *string `json:"ldap_dn,omitempty"` -} - -func (s NewTeam) String() string { - return Stringify(s) -} - -// CreateTeam creates a new team within an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#create-team -func (s *OrganizationsService) CreateTeam(ctx context.Context, org string, team *NewTeam) (*Team, *Response, error) { - u := fmt.Sprintf("orgs/%v/teams", org) - req, err := s.client.NewRequest("POST", u, team) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - t := new(Team) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} - -// EditTeam edits a team. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#edit-team -func (s *OrganizationsService) EditTeam(ctx context.Context, id int64, team *NewTeam) (*Team, *Response, error) { - u := fmt.Sprintf("teams/%v", id) - req, err := s.client.NewRequest("PATCH", u, team) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - t := new(Team) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} - -// DeleteTeam deletes a team. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#delete-team -func (s *OrganizationsService) DeleteTeam(ctx context.Context, team int64) (*Response, error) { - u := fmt.Sprintf("teams/%v", team) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - return s.client.Do(ctx, req, nil) -} - -// OrganizationListTeamMembersOptions specifies the optional parameters to the -// OrganizationsService.ListTeamMembers method. -type OrganizationListTeamMembersOptions struct { - // Role filters members returned by their role in the team. Possible - // values are "all", "member", "maintainer". Default is "all". - Role string `url:"role,omitempty"` - - ListOptions -} - -// ListChildTeams lists child teams for a team. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#list-child-teams -func (s *OrganizationsService) ListChildTeams(ctx context.Context, teamID int64, opt *ListOptions) ([]*Team, *Response, error) { - u := fmt.Sprintf("teams/%v/teams", teamID) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - var teams []*Team - resp, err := s.client.Do(ctx, req, &teams) - if err != nil { - return nil, resp, err - } - - return teams, resp, nil -} - -// ListTeamMembers lists all of the users who are members of the specified -// team. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#list-team-members -func (s *OrganizationsService) ListTeamMembers(ctx context.Context, team int64, opt *OrganizationListTeamMembersOptions) ([]*User, *Response, error) { - u := fmt.Sprintf("teams/%v/members", team) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - var members []*User - resp, err := s.client.Do(ctx, req, &members) - if err != nil { - return nil, resp, err - } - - return members, resp, nil -} - -// IsTeamMember checks if a user is a member of the specified team. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#get-team-member -// -// Deprecated: This API has been marked as deprecated in the Github API docs, -// OrganizationsService.GetTeamMembership method should be used instead. -func (s *OrganizationsService) IsTeamMember(ctx context.Context, team int64, user string) (bool, *Response, error) { - u := fmt.Sprintf("teams/%v/members/%v", team, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - resp, err := s.client.Do(ctx, req, nil) - member, err := parseBoolResponse(err) - return member, resp, err -} - -// ListTeamRepos lists the repositories that the specified team has access to. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#list-team-repos -func (s *OrganizationsService) ListTeamRepos(ctx context.Context, team int64, opt *ListOptions) ([]*Repository, *Response, error) { - u := fmt.Sprintf("teams/%v/repos", team) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when topics API fully launches. - headers := []string{mediaTypeTopicsPreview, mediaTypeNestedTeamsPreview} - req.Header.Set("Accept", strings.Join(headers, ", ")) - - var repos []*Repository - resp, err := s.client.Do(ctx, req, &repos) - if err != nil { - return nil, resp, err - } - - return repos, resp, nil -} - -// IsTeamRepo checks if a team manages the specified repository. If the -// repository is managed by team, a Repository is returned which includes the -// permissions team has for that repo. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#check-if-a-team-manages-a-repository -func (s *OrganizationsService) IsTeamRepo(ctx context.Context, team int64, owner string, repo string) (*Repository, *Response, error) { - u := fmt.Sprintf("teams/%v/repos/%v/%v", team, owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - headers := []string{mediaTypeOrgPermissionRepo, mediaTypeNestedTeamsPreview} - req.Header.Set("Accept", strings.Join(headers, ", ")) - - repository := new(Repository) - resp, err := s.client.Do(ctx, req, repository) - if err != nil { - return nil, resp, err - } - - return repository, resp, nil -} - -// OrganizationAddTeamRepoOptions specifies the optional parameters to the -// OrganizationsService.AddTeamRepo method. -type OrganizationAddTeamRepoOptions struct { - // Permission specifies the permission to grant the team on this repository. - // Possible values are: - // pull - team members can pull, but not push to or administer this repository - // push - team members can pull and push, but not administer this repository - // admin - team members can pull, push and administer this repository - // - // If not specified, the team's permission attribute will be used. - Permission string `json:"permission,omitempty"` -} - -// AddTeamRepo adds a repository to be managed by the specified team. The -// specified repository must be owned by the organization to which the team -// belongs, or a direct fork of a repository owned by the organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#add-team-repo -func (s *OrganizationsService) AddTeamRepo(ctx context.Context, team int64, owner string, repo string, opt *OrganizationAddTeamRepoOptions) (*Response, error) { - u := fmt.Sprintf("teams/%v/repos/%v/%v", team, owner, repo) - req, err := s.client.NewRequest("PUT", u, opt) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// RemoveTeamRepo removes a repository from being managed by the specified -// team. Note that this does not delete the repository, it just removes it -// from the team. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#remove-team-repo -func (s *OrganizationsService) RemoveTeamRepo(ctx context.Context, team int64, owner string, repo string) (*Response, error) { - u := fmt.Sprintf("teams/%v/repos/%v/%v", team, owner, repo) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ListUserTeams lists a user's teams -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#list-user-teams -func (s *OrganizationsService) ListUserTeams(ctx context.Context, opt *ListOptions) ([]*Team, *Response, error) { - u := "user/teams" - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - var teams []*Team - resp, err := s.client.Do(ctx, req, &teams) - if err != nil { - return nil, resp, err - } - - return teams, resp, nil -} - -// GetTeamMembership returns the membership status for a user in a team. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#get-team-membership -func (s *OrganizationsService) GetTeamMembership(ctx context.Context, team int64, user string) (*Membership, *Response, error) { - u := fmt.Sprintf("teams/%v/memberships/%v", team, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - t := new(Membership) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} - -// OrganizationAddTeamMembershipOptions does stuff specifies the optional -// parameters to the OrganizationsService.AddTeamMembership method. -type OrganizationAddTeamMembershipOptions struct { - // Role specifies the role the user should have in the team. Possible - // values are: - // member - a normal member of the team - // maintainer - a team maintainer. Able to add/remove other team - // members, promote other team members to team - // maintainer, and edit the team’s name and description - // - // Default value is "member". - Role string `json:"role,omitempty"` -} - -// AddTeamMembership adds or invites a user to a team. -// -// In order to add a membership between a user and a team, the authenticated -// user must have 'admin' permissions to the team or be an owner of the -// organization that the team is associated with. -// -// If the user is already a part of the team's organization (meaning they're on -// at least one other team in the organization), this endpoint will add the -// user to the team. -// -// If the user is completely unaffiliated with the team's organization (meaning -// they're on none of the organization's teams), this endpoint will send an -// invitation to the user via email. This newly-created membership will be in -// the "pending" state until the user accepts the invitation, at which point -// the membership will transition to the "active" state and the user will be -// added as a member of the team. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#add-team-membership -func (s *OrganizationsService) AddTeamMembership(ctx context.Context, team int64, user string, opt *OrganizationAddTeamMembershipOptions) (*Membership, *Response, error) { - u := fmt.Sprintf("teams/%v/memberships/%v", team, user) - req, err := s.client.NewRequest("PUT", u, opt) - if err != nil { - return nil, nil, err - } - - t := new(Membership) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} - -// RemoveTeamMembership removes a user from a team. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#remove-team-membership -func (s *OrganizationsService) RemoveTeamMembership(ctx context.Context, team int64, user string) (*Response, error) { - u := fmt.Sprintf("teams/%v/memberships/%v", team, user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ListPendingTeamInvitations get pending invitaion list in team. -// Warning: The API may change without advance notice during the preview period. -// Preview features are not supported for production use. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#list-pending-team-invitations -func (s *OrganizationsService) ListPendingTeamInvitations(ctx context.Context, team int64, opt *ListOptions) ([]*Invitation, *Response, error) { - u := fmt.Sprintf("teams/%v/invitations", team) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var pendingInvitations []*Invitation - resp, err := s.client.Do(ctx, req, &pendingInvitations) - if err != nil { - return nil, resp, err - } - - return pendingInvitations, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/orgs_users_blocking.go b/vendor/github.com/google/go-github/github/orgs_users_blocking.go deleted file mode 100644 index b1aecf44532..00000000000 --- a/vendor/github.com/google/go-github/github/orgs_users_blocking.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ListBlockedUsers lists all the users blocked by an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/blocking/#list-blocked-users -func (s *OrganizationsService) ListBlockedUsers(ctx context.Context, org string, opt *ListOptions) ([]*User, *Response, error) { - u := fmt.Sprintf("orgs/%v/blocks", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - var blockedUsers []*User - resp, err := s.client.Do(ctx, req, &blockedUsers) - if err != nil { - return nil, resp, err - } - - return blockedUsers, resp, nil -} - -// IsBlocked reports whether specified user is blocked from an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/blocking/#check-whether-a-user-is-blocked-from-an-organization -func (s *OrganizationsService) IsBlocked(ctx context.Context, org string, user string) (bool, *Response, error) { - u := fmt.Sprintf("orgs/%v/blocks/%v", org, user) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - resp, err := s.client.Do(ctx, req, nil) - isBlocked, err := parseBoolResponse(err) - return isBlocked, resp, err -} - -// BlockUser blocks specified user from an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/blocking/#block-a-user -func (s *OrganizationsService) BlockUser(ctx context.Context, org string, user string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/blocks/%v", org, user) - - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - return s.client.Do(ctx, req, nil) -} - -// UnblockUser unblocks specified user from an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/blocking/#unblock-a-user -func (s *OrganizationsService) UnblockUser(ctx context.Context, org string, user string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/blocks/%v", org, user) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/projects.go b/vendor/github.com/google/go-github/github/projects.go deleted file mode 100644 index 22061363291..00000000000 --- a/vendor/github.com/google/go-github/github/projects.go +++ /dev/null @@ -1,431 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ProjectsService provides access to the projects functions in the -// GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/projects/ -type ProjectsService service - -// Project represents a GitHub Project. -type Project struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - OwnerURL *string `json:"owner_url,omitempty"` - Name *string `json:"name,omitempty"` - Body *string `json:"body,omitempty"` - Number *int `json:"number,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - - // The User object that generated the project. - Creator *User `json:"creator,omitempty"` -} - -func (p Project) String() string { - return Stringify(p) -} - -// GetProject gets a GitHub Project for a repo. -// -// GitHub API docs: https://developer.github.com/v3/projects/#get-a-project -func (s *ProjectsService) GetProject(ctx context.Context, id int64) (*Project, *Response, error) { - u := fmt.Sprintf("projects/%v", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - project := &Project{} - resp, err := s.client.Do(ctx, req, project) - if err != nil { - return nil, resp, err - } - - return project, resp, nil -} - -// ProjectOptions specifies the parameters to the -// RepositoriesService.CreateProject and -// ProjectsService.UpdateProject methods. -type ProjectOptions struct { - // The name of the project. (Required for creation; optional for update.) - Name string `json:"name,omitempty"` - // The body of the project. (Optional.) - Body string `json:"body,omitempty"` - - // The following field(s) are only applicable for update. - // They should be left with zero values for creation. - - // State of the project. Either "open" or "closed". (Optional.) - State string `json:"state,omitempty"` -} - -// UpdateProject updates a repository project. -// -// GitHub API docs: https://developer.github.com/v3/projects/#update-a-project -func (s *ProjectsService) UpdateProject(ctx context.Context, id int64, opt *ProjectOptions) (*Project, *Response, error) { - u := fmt.Sprintf("projects/%v", id) - req, err := s.client.NewRequest("PATCH", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - project := &Project{} - resp, err := s.client.Do(ctx, req, project) - if err != nil { - return nil, resp, err - } - - return project, resp, nil -} - -// DeleteProject deletes a GitHub Project from a repository. -// -// GitHub API docs: https://developer.github.com/v3/projects/#delete-a-project -func (s *ProjectsService) DeleteProject(ctx context.Context, id int64) (*Response, error) { - u := fmt.Sprintf("projects/%v", id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - return s.client.Do(ctx, req, nil) -} - -// ProjectColumn represents a column of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/repos/projects/ -type ProjectColumn struct { - ID *int64 `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - ProjectURL *string `json:"project_url,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` -} - -// ListProjectColumns lists the columns of a GitHub Project for a repo. -// -// GitHub API docs: https://developer.github.com/v3/projects/columns/#list-project-columns -func (s *ProjectsService) ListProjectColumns(ctx context.Context, projectID int64, opt *ListOptions) ([]*ProjectColumn, *Response, error) { - u := fmt.Sprintf("projects/%v/columns", projectID) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - columns := []*ProjectColumn{} - resp, err := s.client.Do(ctx, req, &columns) - if err != nil { - return nil, resp, err - } - - return columns, resp, nil -} - -// GetProjectColumn gets a column of a GitHub Project for a repo. -// -// GitHub API docs: https://developer.github.com/v3/projects/columns/#get-a-project-column -func (s *ProjectsService) GetProjectColumn(ctx context.Context, id int64) (*ProjectColumn, *Response, error) { - u := fmt.Sprintf("projects/columns/%v", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - column := &ProjectColumn{} - resp, err := s.client.Do(ctx, req, column) - if err != nil { - return nil, resp, err - } - - return column, resp, nil -} - -// ProjectColumnOptions specifies the parameters to the -// ProjectsService.CreateProjectColumn and -// ProjectsService.UpdateProjectColumn methods. -type ProjectColumnOptions struct { - // The name of the project column. (Required for creation and update.) - Name string `json:"name"` -} - -// CreateProjectColumn creates a column for the specified (by number) project. -// -// GitHub API docs: https://developer.github.com/v3/projects/columns/#create-a-project-column -func (s *ProjectsService) CreateProjectColumn(ctx context.Context, projectID int64, opt *ProjectColumnOptions) (*ProjectColumn, *Response, error) { - u := fmt.Sprintf("projects/%v/columns", projectID) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - column := &ProjectColumn{} - resp, err := s.client.Do(ctx, req, column) - if err != nil { - return nil, resp, err - } - - return column, resp, nil -} - -// UpdateProjectColumn updates a column of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/columns/#update-a-project-column -func (s *ProjectsService) UpdateProjectColumn(ctx context.Context, columnID int64, opt *ProjectColumnOptions) (*ProjectColumn, *Response, error) { - u := fmt.Sprintf("projects/columns/%v", columnID) - req, err := s.client.NewRequest("PATCH", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - column := &ProjectColumn{} - resp, err := s.client.Do(ctx, req, column) - if err != nil { - return nil, resp, err - } - - return column, resp, nil -} - -// DeleteProjectColumn deletes a column from a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/columns/#delete-a-project-column -func (s *ProjectsService) DeleteProjectColumn(ctx context.Context, columnID int64) (*Response, error) { - u := fmt.Sprintf("projects/columns/%v", columnID) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - return s.client.Do(ctx, req, nil) -} - -// ProjectColumnMoveOptions specifies the parameters to the -// ProjectsService.MoveProjectColumn method. -type ProjectColumnMoveOptions struct { - // Position can be one of "first", "last", or "after:", where - // is the ID of a column in the same project. (Required.) - Position string `json:"position"` -} - -// MoveProjectColumn moves a column within a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/columns/#move-a-project-column -func (s *ProjectsService) MoveProjectColumn(ctx context.Context, columnID int64, opt *ProjectColumnMoveOptions) (*Response, error) { - u := fmt.Sprintf("projects/columns/%v/moves", columnID) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - return s.client.Do(ctx, req, nil) -} - -// ProjectCard represents a card in a column of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#get-a-project-card -type ProjectCard struct { - URL *string `json:"url,omitempty"` - ColumnURL *string `json:"column_url,omitempty"` - ContentURL *string `json:"content_url,omitempty"` - ID *int64 `json:"id,omitempty"` - Note *string `json:"note,omitempty"` - Creator *User `json:"creator,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - - // The following fields are only populated by Webhook events. - ColumnID *int64 `json:"column_id,omitempty"` -} - -// ListProjectCards lists the cards in a column of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#list-project-cards -func (s *ProjectsService) ListProjectCards(ctx context.Context, columnID int64, opt *ListOptions) ([]*ProjectCard, *Response, error) { - u := fmt.Sprintf("projects/columns/%v/cards", columnID) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - cards := []*ProjectCard{} - resp, err := s.client.Do(ctx, req, &cards) - if err != nil { - return nil, resp, err - } - - return cards, resp, nil -} - -// GetProjectCard gets a card in a column of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#get-a-project-card -func (s *ProjectsService) GetProjectCard(ctx context.Context, columnID int64) (*ProjectCard, *Response, error) { - u := fmt.Sprintf("projects/columns/cards/%v", columnID) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - card := &ProjectCard{} - resp, err := s.client.Do(ctx, req, card) - if err != nil { - return nil, resp, err - } - - return card, resp, nil -} - -// ProjectCardOptions specifies the parameters to the -// ProjectsService.CreateProjectCard and -// ProjectsService.UpdateProjectCard methods. -type ProjectCardOptions struct { - // The note of the card. Note and ContentID are mutually exclusive. - Note string `json:"note,omitempty"` - // The ID (not Number) of the Issue to associate with this card. - // Note and ContentID are mutually exclusive. - ContentID int64 `json:"content_id,omitempty"` - // The type of content to associate with this card. Possible values are: "Issue". - ContentType string `json:"content_type,omitempty"` -} - -// CreateProjectCard creates a card in the specified column of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#create-a-project-card -func (s *ProjectsService) CreateProjectCard(ctx context.Context, columnID int64, opt *ProjectCardOptions) (*ProjectCard, *Response, error) { - u := fmt.Sprintf("projects/columns/%v/cards", columnID) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - card := &ProjectCard{} - resp, err := s.client.Do(ctx, req, card) - if err != nil { - return nil, resp, err - } - - return card, resp, nil -} - -// UpdateProjectCard updates a card of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#update-a-project-card -func (s *ProjectsService) UpdateProjectCard(ctx context.Context, cardID int64, opt *ProjectCardOptions) (*ProjectCard, *Response, error) { - u := fmt.Sprintf("projects/columns/cards/%v", cardID) - req, err := s.client.NewRequest("PATCH", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - card := &ProjectCard{} - resp, err := s.client.Do(ctx, req, card) - if err != nil { - return nil, resp, err - } - - return card, resp, nil -} - -// DeleteProjectCard deletes a card from a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#delete-a-project-card -func (s *ProjectsService) DeleteProjectCard(ctx context.Context, cardID int64) (*Response, error) { - u := fmt.Sprintf("projects/columns/cards/%v", cardID) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - return s.client.Do(ctx, req, nil) -} - -// ProjectCardMoveOptions specifies the parameters to the -// ProjectsService.MoveProjectCard method. -type ProjectCardMoveOptions struct { - // Position can be one of "top", "bottom", or "after:", where - // is the ID of a card in the same project. - Position string `json:"position"` - // ColumnID is the ID of a column in the same project. Note that ColumnID - // is required when using Position "after:" when that card is in - // another column; otherwise it is optional. - ColumnID int64 `json:"column_id,omitempty"` -} - -// MoveProjectCard moves a card within a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#move-a-project-card -func (s *ProjectsService) MoveProjectCard(ctx context.Context, cardID int64, opt *ProjectCardMoveOptions) (*Response, error) { - u := fmt.Sprintf("projects/columns/cards/%v/moves", cardID) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/pulls.go b/vendor/github.com/google/go-github/github/pulls.go deleted file mode 100644 index 31d492eea75..00000000000 --- a/vendor/github.com/google/go-github/github/pulls.go +++ /dev/null @@ -1,371 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "bytes" - "context" - "fmt" - "time" -) - -// PullRequestsService handles communication with the pull request related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/pulls/ -type PullRequestsService service - -// PullRequest represents a GitHub pull request on a repository. -type PullRequest struct { - ID *int64 `json:"id,omitempty"` - Number *int `json:"number,omitempty"` - State *string `json:"state,omitempty"` - Title *string `json:"title,omitempty"` - Body *string `json:"body,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - ClosedAt *time.Time `json:"closed_at,omitempty"` - MergedAt *time.Time `json:"merged_at,omitempty"` - User *User `json:"user,omitempty"` - Merged *bool `json:"merged,omitempty"` - Mergeable *bool `json:"mergeable,omitempty"` - MergeableState *string `json:"mergeable_state,omitempty"` - MergedBy *User `json:"merged_by,omitempty"` - MergeCommitSHA *string `json:"merge_commit_sha,omitempty"` - Comments *int `json:"comments,omitempty"` - Commits *int `json:"commits,omitempty"` - Additions *int `json:"additions,omitempty"` - Deletions *int `json:"deletions,omitempty"` - ChangedFiles *int `json:"changed_files,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - IssueURL *string `json:"issue_url,omitempty"` - StatusesURL *string `json:"statuses_url,omitempty"` - DiffURL *string `json:"diff_url,omitempty"` - PatchURL *string `json:"patch_url,omitempty"` - ReviewCommentsURL *string `json:"review_comments_url,omitempty"` - ReviewCommentURL *string `json:"review_comment_url,omitempty"` - Assignee *User `json:"assignee,omitempty"` - Assignees []*User `json:"assignees,omitempty"` - Milestone *Milestone `json:"milestone,omitempty"` - MaintainerCanModify *bool `json:"maintainer_can_modify,omitempty"` - AuthorAssociation *string `json:"author_association,omitempty"` - NodeID *string `json:"node_id,omitempty"` - - Head *PullRequestBranch `json:"head,omitempty"` - Base *PullRequestBranch `json:"base,omitempty"` -} - -func (p PullRequest) String() string { - return Stringify(p) -} - -// PullRequestBranch represents a base or head branch in a GitHub pull request. -type PullRequestBranch struct { - Label *string `json:"label,omitempty"` - Ref *string `json:"ref,omitempty"` - SHA *string `json:"sha,omitempty"` - Repo *Repository `json:"repo,omitempty"` - User *User `json:"user,omitempty"` -} - -// PullRequestListOptions specifies the optional parameters to the -// PullRequestsService.List method. -type PullRequestListOptions struct { - // State filters pull requests based on their state. Possible values are: - // open, closed. Default is "open". - State string `url:"state,omitempty"` - - // Head filters pull requests by head user and branch name in the format of: - // "user:ref-name". - Head string `url:"head,omitempty"` - - // Base filters pull requests by base branch name. - Base string `url:"base,omitempty"` - - // Sort specifies how to sort pull requests. Possible values are: created, - // updated, popularity, long-running. Default is "created". - Sort string `url:"sort,omitempty"` - - // Direction in which to sort pull requests. Possible values are: asc, desc. - // If Sort is "created" or not specified, Default is "desc", otherwise Default - // is "asc" - Direction string `url:"direction,omitempty"` - - ListOptions -} - -// List the pull requests for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#list-pull-requests -func (s *PullRequestsService) List(ctx context.Context, owner string, repo string, opt *PullRequestListOptions) ([]*PullRequest, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - var pulls []*PullRequest - resp, err := s.client.Do(ctx, req, &pulls) - if err != nil { - return nil, resp, err - } - - return pulls, resp, nil -} - -// Get a single pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#get-a-single-pull-request -func (s *PullRequestsService) Get(ctx context.Context, owner string, repo string, number int) (*PullRequest, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d", owner, repo, number) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - pull := new(PullRequest) - resp, err := s.client.Do(ctx, req, pull) - if err != nil { - return nil, resp, err - } - - return pull, resp, nil -} - -// GetRaw gets a single pull request in raw (diff or patch) format. -func (s *PullRequestsService) GetRaw(ctx context.Context, owner string, repo string, number int, opt RawOptions) (string, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d", owner, repo, number) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return "", nil, err - } - - switch opt.Type { - case Diff: - req.Header.Set("Accept", mediaTypeV3Diff) - case Patch: - req.Header.Set("Accept", mediaTypeV3Patch) - default: - return "", nil, fmt.Errorf("unsupported raw type %d", opt.Type) - } - - var buf bytes.Buffer - resp, err := s.client.Do(ctx, req, &buf) - if err != nil { - return "", resp, err - } - - return buf.String(), resp, nil -} - -// NewPullRequest represents a new pull request to be created. -type NewPullRequest struct { - Title *string `json:"title,omitempty"` - Head *string `json:"head,omitempty"` - Base *string `json:"base,omitempty"` - Body *string `json:"body,omitempty"` - Issue *int `json:"issue,omitempty"` - MaintainerCanModify *bool `json:"maintainer_can_modify,omitempty"` -} - -// Create a new pull request on the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#create-a-pull-request -func (s *PullRequestsService) Create(ctx context.Context, owner string, repo string, pull *NewPullRequest) (*PullRequest, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls", owner, repo) - req, err := s.client.NewRequest("POST", u, pull) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - p := new(PullRequest) - resp, err := s.client.Do(ctx, req, p) - if err != nil { - return nil, resp, err - } - - return p, resp, nil -} - -type pullRequestUpdate struct { - Title *string `json:"title,omitempty"` - Body *string `json:"body,omitempty"` - State *string `json:"state,omitempty"` - Base *string `json:"base,omitempty"` - MaintainerCanModify *bool `json:"maintainer_can_modify,omitempty"` -} - -// Edit a pull request. -// pull must not be nil. -// -// The following fields are editable: Title, Body, State, Base.Ref and MaintainerCanModify. -// Base.Ref updates the base branch of the pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#update-a-pull-request -func (s *PullRequestsService) Edit(ctx context.Context, owner string, repo string, number int, pull *PullRequest) (*PullRequest, *Response, error) { - if pull == nil { - return nil, nil, fmt.Errorf("pull must be provided") - } - - u := fmt.Sprintf("repos/%v/%v/pulls/%d", owner, repo, number) - - update := &pullRequestUpdate{ - Title: pull.Title, - Body: pull.Body, - State: pull.State, - MaintainerCanModify: pull.MaintainerCanModify, - } - if pull.Base != nil { - update.Base = pull.Base.Ref - } - - req, err := s.client.NewRequest("PATCH", u, update) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - p := new(PullRequest) - resp, err := s.client.Do(ctx, req, p) - if err != nil { - return nil, resp, err - } - - return p, resp, nil -} - -// ListCommits lists the commits in a pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#list-commits-on-a-pull-request -func (s *PullRequestsService) ListCommits(ctx context.Context, owner string, repo string, number int, opt *ListOptions) ([]*RepositoryCommit, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/commits", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - var commits []*RepositoryCommit - resp, err := s.client.Do(ctx, req, &commits) - if err != nil { - return nil, resp, err - } - - return commits, resp, nil -} - -// ListFiles lists the files in a pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#list-pull-requests-files -func (s *PullRequestsService) ListFiles(ctx context.Context, owner string, repo string, number int, opt *ListOptions) ([]*CommitFile, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/files", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var commitFiles []*CommitFile - resp, err := s.client.Do(ctx, req, &commitFiles) - if err != nil { - return nil, resp, err - } - - return commitFiles, resp, nil -} - -// IsMerged checks if a pull request has been merged. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#get-if-a-pull-request-has-been-merged -func (s *PullRequestsService) IsMerged(ctx context.Context, owner string, repo string, number int) (bool, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/merge", owner, repo, number) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - resp, err := s.client.Do(ctx, req, nil) - merged, err := parseBoolResponse(err) - return merged, resp, err -} - -// PullRequestMergeResult represents the result of merging a pull request. -type PullRequestMergeResult struct { - SHA *string `json:"sha,omitempty"` - Merged *bool `json:"merged,omitempty"` - Message *string `json:"message,omitempty"` -} - -// PullRequestOptions lets you define how a pull request will be merged. -type PullRequestOptions struct { - CommitTitle string // Extra detail to append to automatic commit message. (Optional.) - SHA string // SHA that pull request head must match to allow merge. (Optional.) - - // The merge method to use. Possible values include: "merge", "squash", and "rebase" with the default being merge. (Optional.) - MergeMethod string -} - -type pullRequestMergeRequest struct { - CommitMessage string `json:"commit_message"` - CommitTitle string `json:"commit_title,omitempty"` - MergeMethod string `json:"merge_method,omitempty"` - SHA string `json:"sha,omitempty"` -} - -// Merge a pull request (Merge Button™). -// commitMessage is the title for the automatic commit message. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-buttontrade -func (s *PullRequestsService) Merge(ctx context.Context, owner string, repo string, number int, commitMessage string, options *PullRequestOptions) (*PullRequestMergeResult, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/merge", owner, repo, number) - - pullRequestBody := &pullRequestMergeRequest{CommitMessage: commitMessage} - if options != nil { - pullRequestBody.CommitTitle = options.CommitTitle - pullRequestBody.MergeMethod = options.MergeMethod - pullRequestBody.SHA = options.SHA - } - req, err := s.client.NewRequest("PUT", u, pullRequestBody) - if err != nil { - return nil, nil, err - } - - mergeResult := new(PullRequestMergeResult) - resp, err := s.client.Do(ctx, req, mergeResult) - if err != nil { - return nil, resp, err - } - - return mergeResult, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/pulls_comments.go b/vendor/github.com/google/go-github/github/pulls_comments.go deleted file mode 100644 index ff892279e44..00000000000 --- a/vendor/github.com/google/go-github/github/pulls_comments.go +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// PullRequestComment represents a comment left on a pull request. -type PullRequestComment struct { - ID *int64 `json:"id,omitempty"` - InReplyTo *int64 `json:"in_reply_to,omitempty"` - Body *string `json:"body,omitempty"` - Path *string `json:"path,omitempty"` - DiffHunk *string `json:"diff_hunk,omitempty"` - Position *int `json:"position,omitempty"` - OriginalPosition *int `json:"original_position,omitempty"` - CommitID *string `json:"commit_id,omitempty"` - OriginalCommitID *string `json:"original_commit_id,omitempty"` - User *User `json:"user,omitempty"` - Reactions *Reactions `json:"reactions,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - PullRequestURL *string `json:"pull_request_url,omitempty"` -} - -func (p PullRequestComment) String() string { - return Stringify(p) -} - -// PullRequestListCommentsOptions specifies the optional parameters to the -// PullRequestsService.ListComments method. -type PullRequestListCommentsOptions struct { - // Sort specifies how to sort comments. Possible values are: created, updated. - Sort string `url:"sort,omitempty"` - - // Direction in which to sort comments. Possible values are: asc, desc. - Direction string `url:"direction,omitempty"` - - // Since filters comments by time. - Since time.Time `url:"since,omitempty"` - - ListOptions -} - -// ListComments lists all comments on the specified pull request. Specifying a -// pull request number of 0 will return all comments on all pull requests for -// the repository. -// -// GitHub API docs: https://developer.github.com/v3/pulls/comments/#list-comments-on-a-pull-request -func (s *PullRequestsService) ListComments(ctx context.Context, owner string, repo string, number int, opt *PullRequestListCommentsOptions) ([]*PullRequestComment, *Response, error) { - var u string - if number == 0 { - u = fmt.Sprintf("repos/%v/%v/pulls/comments", owner, repo) - } else { - u = fmt.Sprintf("repos/%v/%v/pulls/%d/comments", owner, repo, number) - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var comments []*PullRequestComment - resp, err := s.client.Do(ctx, req, &comments) - if err != nil { - return nil, resp, err - } - - return comments, resp, nil -} - -// GetComment fetches the specified pull request comment. -// -// GitHub API docs: https://developer.github.com/v3/pulls/comments/#get-a-single-comment -func (s *PullRequestsService) GetComment(ctx context.Context, owner string, repo string, number int) (*PullRequestComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/comments/%d", owner, repo, number) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - comment := new(PullRequestComment) - resp, err := s.client.Do(ctx, req, comment) - if err != nil { - return nil, resp, err - } - - return comment, resp, nil -} - -// CreateComment creates a new comment on the specified pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/comments/#create-a-comment -func (s *PullRequestsService) CreateComment(ctx context.Context, owner string, repo string, number int, comment *PullRequestComment) (*PullRequestComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/comments", owner, repo, number) - req, err := s.client.NewRequest("POST", u, comment) - if err != nil { - return nil, nil, err - } - - c := new(PullRequestComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// EditComment updates a pull request comment. -// -// GitHub API docs: https://developer.github.com/v3/pulls/comments/#edit-a-comment -func (s *PullRequestsService) EditComment(ctx context.Context, owner string, repo string, number int, comment *PullRequestComment) (*PullRequestComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/comments/%d", owner, repo, number) - req, err := s.client.NewRequest("PATCH", u, comment) - if err != nil { - return nil, nil, err - } - - c := new(PullRequestComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// DeleteComment deletes a pull request comment. -// -// GitHub API docs: https://developer.github.com/v3/pulls/comments/#delete-a-comment -func (s *PullRequestsService) DeleteComment(ctx context.Context, owner string, repo string, number int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/comments/%d", owner, repo, number) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/pulls_reviewers.go b/vendor/github.com/google/go-github/github/pulls_reviewers.go deleted file mode 100644 index 15b47be31fd..00000000000 --- a/vendor/github.com/google/go-github/github/pulls_reviewers.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ReviewersRequest specifies users and teams for a pull request review request. -type ReviewersRequest struct { - Reviewers []string `json:"reviewers,omitempty"` - TeamReviewers []string `json:"team_reviewers,omitempty"` -} - -// Reviewers represents reviewers of a pull request. -type Reviewers struct { - Users []*User `json:"users,omitempty"` - Teams []*Team `json:"teams,omitempty"` -} - -// RequestReviewers creates a review request for the provided reviewers for the specified pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/review_requests/#create-a-review-request -func (s *PullRequestsService) RequestReviewers(ctx context.Context, owner, repo string, number int, reviewers ReviewersRequest) (*PullRequest, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/pulls/%d/requested_reviewers", owner, repo, number) - req, err := s.client.NewRequest("POST", u, &reviewers) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTeamReviewPreview) - - r := new(PullRequest) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// ListReviewers lists reviewers whose reviews have been requested on the specified pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/review_requests/#list-review-requests -func (s *PullRequestsService) ListReviewers(ctx context.Context, owner, repo string, number int, opt *ListOptions) (*Reviewers, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/requested_reviewers", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTeamReviewPreview) - - reviewers := new(Reviewers) - resp, err := s.client.Do(ctx, req, reviewers) - if err != nil { - return nil, resp, err - } - - return reviewers, resp, nil -} - -// RemoveReviewers removes the review request for the provided reviewers for the specified pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/review_requests/#delete-a-review-request -func (s *PullRequestsService) RemoveReviewers(ctx context.Context, owner, repo string, number int, reviewers ReviewersRequest) (*Response, error) { - u := fmt.Sprintf("repos/%s/%s/pulls/%d/requested_reviewers", owner, repo, number) - req, err := s.client.NewRequest("DELETE", u, &reviewers) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTeamReviewPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/pulls_reviews.go b/vendor/github.com/google/go-github/github/pulls_reviews.go deleted file mode 100644 index 1aceb0d4ddf..00000000000 --- a/vendor/github.com/google/go-github/github/pulls_reviews.go +++ /dev/null @@ -1,236 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// PullRequestReview represents a review of a pull request. -type PullRequestReview struct { - ID *int64 `json:"id,omitempty"` - User *User `json:"user,omitempty"` - Body *string `json:"body,omitempty"` - SubmittedAt *time.Time `json:"submitted_at,omitempty"` - CommitID *string `json:"commit_id,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - PullRequestURL *string `json:"pull_request_url,omitempty"` - State *string `json:"state,omitempty"` -} - -func (p PullRequestReview) String() string { - return Stringify(p) -} - -// DraftReviewComment represents a comment part of the review. -type DraftReviewComment struct { - Path *string `json:"path,omitempty"` - Position *int `json:"position,omitempty"` - Body *string `json:"body,omitempty"` -} - -func (c DraftReviewComment) String() string { - return Stringify(c) -} - -// PullRequestReviewRequest represents a request to create a review. -type PullRequestReviewRequest struct { - CommitID *string `json:"commit_id,omitempty"` - Body *string `json:"body,omitempty"` - Event *string `json:"event,omitempty"` - Comments []*DraftReviewComment `json:"comments,omitempty"` -} - -func (r PullRequestReviewRequest) String() string { - return Stringify(r) -} - -// PullRequestReviewDismissalRequest represents a request to dismiss a review. -type PullRequestReviewDismissalRequest struct { - Message *string `json:"message,omitempty"` -} - -func (r PullRequestReviewDismissalRequest) String() string { - return Stringify(r) -} - -// ListReviews lists all reviews on the specified pull request. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request -func (s *PullRequestsService) ListReviews(ctx context.Context, owner, repo string, number int, opt *ListOptions) ([]*PullRequestReview, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var reviews []*PullRequestReview - resp, err := s.client.Do(ctx, req, &reviews) - if err != nil { - return nil, resp, err - } - - return reviews, resp, nil -} - -// GetReview fetches the specified pull request review. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#get-a-single-review -func (s *PullRequestsService) GetReview(ctx context.Context, owner, repo string, number, reviewID int64) (*PullRequestReview, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews/%d", owner, repo, number, reviewID) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - review := new(PullRequestReview) - resp, err := s.client.Do(ctx, req, review) - if err != nil { - return nil, resp, err - } - - return review, resp, nil -} - -// DeletePendingReview deletes the specified pull request pending review. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#delete-a-pending-review -func (s *PullRequestsService) DeletePendingReview(ctx context.Context, owner, repo string, number, reviewID int64) (*PullRequestReview, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews/%d", owner, repo, number, reviewID) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, nil, err - } - - review := new(PullRequestReview) - resp, err := s.client.Do(ctx, req, review) - if err != nil { - return nil, resp, err - } - - return review, resp, nil -} - -// ListReviewComments lists all the comments for the specified review. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#get-comments-for-a-single-review -func (s *PullRequestsService) ListReviewComments(ctx context.Context, owner, repo string, number, reviewID int64, opt *ListOptions) ([]*PullRequestComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews/%d/comments", owner, repo, number, reviewID) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var comments []*PullRequestComment - resp, err := s.client.Do(ctx, req, &comments) - if err != nil { - return nil, resp, err - } - - return comments, resp, nil -} - -// CreateReview creates a new review on the specified pull request. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#create-a-pull-request-review -func (s *PullRequestsService) CreateReview(ctx context.Context, owner, repo string, number int, review *PullRequestReviewRequest) (*PullRequestReview, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews", owner, repo, number) - - req, err := s.client.NewRequest("POST", u, review) - if err != nil { - return nil, nil, err - } - - r := new(PullRequestReview) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// SubmitReview submits a specified review on the specified pull request. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#submit-a-pull-request-review -func (s *PullRequestsService) SubmitReview(ctx context.Context, owner, repo string, number, reviewID int64, review *PullRequestReviewRequest) (*PullRequestReview, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews/%d/events", owner, repo, number, reviewID) - - req, err := s.client.NewRequest("POST", u, review) - if err != nil { - return nil, nil, err - } - - r := new(PullRequestReview) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// DismissReview dismisses a specified review on the specified pull request. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#dismiss-a-pull-request-review -func (s *PullRequestsService) DismissReview(ctx context.Context, owner, repo string, number, reviewID int64, review *PullRequestReviewDismissalRequest) (*PullRequestReview, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews/%d/dismissals", owner, repo, number, reviewID) - - req, err := s.client.NewRequest("PUT", u, review) - if err != nil { - return nil, nil, err - } - - r := new(PullRequestReview) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/reactions.go b/vendor/github.com/google/go-github/github/reactions.go deleted file mode 100644 index b276ff3e059..00000000000 --- a/vendor/github.com/google/go-github/github/reactions.go +++ /dev/null @@ -1,273 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ReactionsService provides access to the reactions-related functions in the -// GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/reactions/ -type ReactionsService service - -// Reaction represents a GitHub reaction. -type Reaction struct { - // ID is the Reaction ID. - ID *int64 `json:"id,omitempty"` - User *User `json:"user,omitempty"` - // Content is the type of reaction. - // Possible values are: - // "+1", "-1", "laugh", "confused", "heart", "hooray". - Content *string `json:"content,omitempty"` -} - -// Reactions represents a summary of GitHub reactions. -type Reactions struct { - TotalCount *int `json:"total_count,omitempty"` - PlusOne *int `json:"+1,omitempty"` - MinusOne *int `json:"-1,omitempty"` - Laugh *int `json:"laugh,omitempty"` - Confused *int `json:"confused,omitempty"` - Heart *int `json:"heart,omitempty"` - Hooray *int `json:"hooray,omitempty"` - URL *string `json:"url,omitempty"` -} - -func (r Reaction) String() string { - return Stringify(r) -} - -// ListCommentReactions lists the reactions for a commit comment. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-a-commit-comment -func (s *ReactionsService) ListCommentReactions(ctx context.Context, owner, repo string, id int64, opt *ListOptions) ([]*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/comments/%v/reactions", owner, repo, id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var m []*Reaction - resp, err := s.client.Do(ctx, req, &m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// CreateCommentReaction creates a reaction for a commit comment. -// Note that if you have already created a reaction of type content, the -// previously created reaction will be returned with Status: 200 OK. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-a-commit-comment -func (s ReactionsService) CreateCommentReaction(ctx context.Context, owner, repo string, id int64, content string) (*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/comments/%v/reactions", owner, repo, id) - - body := &Reaction{Content: String(content)} - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - m := &Reaction{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// ListIssueReactions lists the reactions for an issue. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-an-issue -func (s *ReactionsService) ListIssueReactions(ctx context.Context, owner, repo string, number int, opt *ListOptions) ([]*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%v/reactions", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var m []*Reaction - resp, err := s.client.Do(ctx, req, &m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// CreateIssueReaction creates a reaction for an issue. -// Note that if you have already created a reaction of type content, the -// previously created reaction will be returned with Status: 200 OK. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-an-issue -func (s ReactionsService) CreateIssueReaction(ctx context.Context, owner, repo string, number int, content string) (*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%v/reactions", owner, repo, number) - - body := &Reaction{Content: String(content)} - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - m := &Reaction{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// ListIssueCommentReactions lists the reactions for an issue comment. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-an-issue-comment -func (s *ReactionsService) ListIssueCommentReactions(ctx context.Context, owner, repo string, id int64, opt *ListOptions) ([]*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/comments/%v/reactions", owner, repo, id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var m []*Reaction - resp, err := s.client.Do(ctx, req, &m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// CreateIssueCommentReaction creates a reaction for an issue comment. -// Note that if you have already created a reaction of type content, the -// previously created reaction will be returned with Status: 200 OK. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-an-issue-comment -func (s ReactionsService) CreateIssueCommentReaction(ctx context.Context, owner, repo string, id int64, content string) (*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/comments/%v/reactions", owner, repo, id) - - body := &Reaction{Content: String(content)} - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - m := &Reaction{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// ListPullRequestCommentReactions lists the reactions for a pull request review comment. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-an-issue-comment -func (s *ReactionsService) ListPullRequestCommentReactions(ctx context.Context, owner, repo string, id int64, opt *ListOptions) ([]*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/comments/%v/reactions", owner, repo, id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var m []*Reaction - resp, err := s.client.Do(ctx, req, &m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// CreatePullRequestCommentReaction creates a reaction for a pull request review comment. -// Note that if you have already created a reaction of type content, the -// previously created reaction will be returned with Status: 200 OK. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-an-issue-comment -func (s ReactionsService) CreatePullRequestCommentReaction(ctx context.Context, owner, repo string, id int64, content string) (*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/comments/%v/reactions", owner, repo, id) - - body := &Reaction{Content: String(content)} - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - m := &Reaction{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// DeleteReaction deletes a reaction. -// -// GitHub API docs: https://developer.github.com/v3/reaction/reactions/#delete-a-reaction-archive -func (s *ReactionsService) DeleteReaction(ctx context.Context, id int64) (*Response, error) { - u := fmt.Sprintf("reactions/%v", id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/repos.go b/vendor/github.com/google/go-github/github/repos.go deleted file mode 100644 index 68accf7ff15..00000000000 --- a/vendor/github.com/google/go-github/github/repos.go +++ /dev/null @@ -1,1076 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "strings" -) - -// RepositoriesService handles communication with the repository related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/repos/ -type RepositoriesService service - -// Repository represents a GitHub repository. -type Repository struct { - ID *int64 `json:"id,omitempty"` - Owner *User `json:"owner,omitempty"` - Name *string `json:"name,omitempty"` - FullName *string `json:"full_name,omitempty"` - Description *string `json:"description,omitempty"` - Homepage *string `json:"homepage,omitempty"` - CodeOfConduct *CodeOfConduct `json:"code_of_conduct,omitempty"` - DefaultBranch *string `json:"default_branch,omitempty"` - MasterBranch *string `json:"master_branch,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - PushedAt *Timestamp `json:"pushed_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - CloneURL *string `json:"clone_url,omitempty"` - GitURL *string `json:"git_url,omitempty"` - MirrorURL *string `json:"mirror_url,omitempty"` - SSHURL *string `json:"ssh_url,omitempty"` - SVNURL *string `json:"svn_url,omitempty"` - Language *string `json:"language,omitempty"` - Fork *bool `json:"fork,omitempty"` - ForksCount *int `json:"forks_count,omitempty"` - NetworkCount *int `json:"network_count,omitempty"` - OpenIssuesCount *int `json:"open_issues_count,omitempty"` - StargazersCount *int `json:"stargazers_count,omitempty"` - SubscribersCount *int `json:"subscribers_count,omitempty"` - WatchersCount *int `json:"watchers_count,omitempty"` - Size *int `json:"size,omitempty"` - AutoInit *bool `json:"auto_init,omitempty"` - Parent *Repository `json:"parent,omitempty"` - Source *Repository `json:"source,omitempty"` - Organization *Organization `json:"organization,omitempty"` - Permissions *map[string]bool `json:"permissions,omitempty"` - AllowRebaseMerge *bool `json:"allow_rebase_merge,omitempty"` - AllowSquashMerge *bool `json:"allow_squash_merge,omitempty"` - AllowMergeCommit *bool `json:"allow_merge_commit,omitempty"` - Topics []string `json:"topics,omitempty"` - - // Only provided when using RepositoriesService.Get while in preview - License *License `json:"license,omitempty"` - - // Additional mutable fields when creating and editing a repository - Private *bool `json:"private,omitempty"` - HasIssues *bool `json:"has_issues,omitempty"` - HasWiki *bool `json:"has_wiki,omitempty"` - HasPages *bool `json:"has_pages,omitempty"` - HasProjects *bool `json:"has_projects,omitempty"` - HasDownloads *bool `json:"has_downloads,omitempty"` - LicenseTemplate *string `json:"license_template,omitempty"` - GitignoreTemplate *string `json:"gitignore_template,omitempty"` - Archived *bool `json:"archived,omitempty"` - - // Creating an organization repository. Required for non-owners. - TeamID *int64 `json:"team_id,omitempty"` - - // API URLs - URL *string `json:"url,omitempty"` - ArchiveURL *string `json:"archive_url,omitempty"` - AssigneesURL *string `json:"assignees_url,omitempty"` - BlobsURL *string `json:"blobs_url,omitempty"` - BranchesURL *string `json:"branches_url,omitempty"` - CollaboratorsURL *string `json:"collaborators_url,omitempty"` - CommentsURL *string `json:"comments_url,omitempty"` - CommitsURL *string `json:"commits_url,omitempty"` - CompareURL *string `json:"compare_url,omitempty"` - ContentsURL *string `json:"contents_url,omitempty"` - ContributorsURL *string `json:"contributors_url,omitempty"` - DeploymentsURL *string `json:"deployments_url,omitempty"` - DownloadsURL *string `json:"downloads_url,omitempty"` - EventsURL *string `json:"events_url,omitempty"` - ForksURL *string `json:"forks_url,omitempty"` - GitCommitsURL *string `json:"git_commits_url,omitempty"` - GitRefsURL *string `json:"git_refs_url,omitempty"` - GitTagsURL *string `json:"git_tags_url,omitempty"` - HooksURL *string `json:"hooks_url,omitempty"` - IssueCommentURL *string `json:"issue_comment_url,omitempty"` - IssueEventsURL *string `json:"issue_events_url,omitempty"` - IssuesURL *string `json:"issues_url,omitempty"` - KeysURL *string `json:"keys_url,omitempty"` - LabelsURL *string `json:"labels_url,omitempty"` - LanguagesURL *string `json:"languages_url,omitempty"` - MergesURL *string `json:"merges_url,omitempty"` - MilestonesURL *string `json:"milestones_url,omitempty"` - NotificationsURL *string `json:"notifications_url,omitempty"` - PullsURL *string `json:"pulls_url,omitempty"` - ReleasesURL *string `json:"releases_url,omitempty"` - StargazersURL *string `json:"stargazers_url,omitempty"` - StatusesURL *string `json:"statuses_url,omitempty"` - SubscribersURL *string `json:"subscribers_url,omitempty"` - SubscriptionURL *string `json:"subscription_url,omitempty"` - TagsURL *string `json:"tags_url,omitempty"` - TreesURL *string `json:"trees_url,omitempty"` - TeamsURL *string `json:"teams_url,omitempty"` - - // TextMatches is only populated from search results that request text matches - // See: search.go and https://developer.github.com/v3/search/#text-match-metadata - TextMatches []TextMatch `json:"text_matches,omitempty"` -} - -func (r Repository) String() string { - return Stringify(r) -} - -// RepositoryListOptions specifies the optional parameters to the -// RepositoriesService.List method. -type RepositoryListOptions struct { - // Visibility of repositories to list. Can be one of all, public, or private. - // Default: all - Visibility string `url:"visibility,omitempty"` - - // List repos of given affiliation[s]. - // Comma-separated list of values. Can include: - // * owner: Repositories that are owned by the authenticated user. - // * collaborator: Repositories that the user has been added to as a - // collaborator. - // * organization_member: Repositories that the user has access to through - // being a member of an organization. This includes every repository on - // every team that the user is on. - // Default: owner,collaborator,organization_member - Affiliation string `url:"affiliation,omitempty"` - - // Type of repositories to list. - // Can be one of all, owner, public, private, member. Default: all - // Will cause a 422 error if used in the same request as visibility or - // affiliation. - Type string `url:"type,omitempty"` - - // How to sort the repository list. Can be one of created, updated, pushed, - // full_name. Default: full_name - Sort string `url:"sort,omitempty"` - - // Direction in which to sort repositories. Can be one of asc or desc. - // Default: when using full_name: asc; otherwise desc - Direction string `url:"direction,omitempty"` - - ListOptions -} - -// List the repositories for a user. Passing the empty string will list -// repositories for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-user-repositories -func (s *RepositoriesService) List(ctx context.Context, user string, opt *RepositoryListOptions) ([]*Repository, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/repos", user) - } else { - u = "user/repos" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - acceptHeaders := []string{mediaTypeLicensesPreview, mediaTypeCodesOfConductPreview, mediaTypeTopicsPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - var repos []*Repository - resp, err := s.client.Do(ctx, req, &repos) - if err != nil { - return nil, resp, err - } - - return repos, resp, nil -} - -// RepositoryListByOrgOptions specifies the optional parameters to the -// RepositoriesService.ListByOrg method. -type RepositoryListByOrgOptions struct { - // Type of repositories to list. Possible values are: all, public, private, - // forks, sources, member. Default is "all". - Type string `url:"type,omitempty"` - - ListOptions -} - -// ListByOrg lists the repositories for an organization. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-organization-repositories -func (s *RepositoriesService) ListByOrg(ctx context.Context, org string, opt *RepositoryListByOrgOptions) ([]*Repository, *Response, error) { - u := fmt.Sprintf("orgs/%v/repos", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - acceptHeaders := []string{mediaTypeLicensesPreview, mediaTypeCodesOfConductPreview, mediaTypeTopicsPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - var repos []*Repository - resp, err := s.client.Do(ctx, req, &repos) - if err != nil { - return nil, resp, err - } - - return repos, resp, nil -} - -// RepositoryListAllOptions specifies the optional parameters to the -// RepositoriesService.ListAll method. -type RepositoryListAllOptions struct { - // ID of the last repository seen - Since int64 `url:"since,omitempty"` -} - -// ListAll lists all GitHub repositories in the order that they were created. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-all-public-repositories -func (s *RepositoriesService) ListAll(ctx context.Context, opt *RepositoryListAllOptions) ([]*Repository, *Response, error) { - u, err := addOptions("repositories", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var repos []*Repository - resp, err := s.client.Do(ctx, req, &repos) - if err != nil { - return nil, resp, err - } - - return repos, resp, nil -} - -// Create a new repository. If an organization is specified, the new -// repository will be created under that org. If the empty string is -// specified, it will be created for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/repos/#create -func (s *RepositoriesService) Create(ctx context.Context, org string, repo *Repository) (*Repository, *Response, error) { - var u string - if org != "" { - u = fmt.Sprintf("orgs/%v/repos", org) - } else { - u = "user/repos" - } - - req, err := s.client.NewRequest("POST", u, repo) - if err != nil { - return nil, nil, err - } - - r := new(Repository) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// Get fetches a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#get -func (s *RepositoriesService) Get(ctx context.Context, owner, repo string) (*Repository, *Response, error) { - u := fmt.Sprintf("repos/%v/%v", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when the license support fully launches - // https://developer.github.com/v3/licenses/#get-a-repositorys-license - acceptHeaders := []string{mediaTypeLicensesPreview, mediaTypeCodesOfConductPreview, mediaTypeTopicsPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - repository := new(Repository) - resp, err := s.client.Do(ctx, req, repository) - if err != nil { - return nil, resp, err - } - - return repository, resp, nil -} - -// GetCodeOfConduct gets the contents of a repository's code of conduct. -// -// GitHub API docs: https://developer.github.com/v3/codes_of_conduct/#get-the-contents-of-a-repositorys-code-of-conduct -func (s *RepositoriesService) GetCodeOfConduct(ctx context.Context, owner, repo string) (*CodeOfConduct, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/community/code_of_conduct", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeCodesOfConductPreview) - - coc := new(CodeOfConduct) - resp, err := s.client.Do(ctx, req, coc) - if err != nil { - return nil, resp, err - } - - return coc, resp, nil -} - -// GetByID fetches a repository. -// -// Note: GetByID uses the undocumented GitHub API endpoint /repositories/:id. -func (s *RepositoriesService) GetByID(ctx context.Context, id int64) (*Repository, *Response, error) { - u := fmt.Sprintf("repositories/%d", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when the license support fully launches - // https://developer.github.com/v3/licenses/#get-a-repositorys-license - req.Header.Set("Accept", mediaTypeLicensesPreview) - - repository := new(Repository) - resp, err := s.client.Do(ctx, req, repository) - if err != nil { - return nil, resp, err - } - - return repository, resp, nil -} - -// Edit updates a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#edit -func (s *RepositoriesService) Edit(ctx context.Context, owner, repo string, repository *Repository) (*Repository, *Response, error) { - u := fmt.Sprintf("repos/%v/%v", owner, repo) - req, err := s.client.NewRequest("PATCH", u, repository) - if err != nil { - return nil, nil, err - } - - r := new(Repository) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// Delete a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#delete-a-repository -func (s *RepositoriesService) Delete(ctx context.Context, owner, repo string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v", owner, repo) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// Contributor represents a repository contributor -type Contributor struct { - Login *string `json:"login,omitempty"` - ID *int64 `json:"id,omitempty"` - AvatarURL *string `json:"avatar_url,omitempty"` - GravatarID *string `json:"gravatar_id,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - FollowersURL *string `json:"followers_url,omitempty"` - FollowingURL *string `json:"following_url,omitempty"` - GistsURL *string `json:"gists_url,omitempty"` - StarredURL *string `json:"starred_url,omitempty"` - SubscriptionsURL *string `json:"subscriptions_url,omitempty"` - OrganizationsURL *string `json:"organizations_url,omitempty"` - ReposURL *string `json:"repos_url,omitempty"` - EventsURL *string `json:"events_url,omitempty"` - ReceivedEventsURL *string `json:"received_events_url,omitempty"` - Type *string `json:"type,omitempty"` - SiteAdmin *bool `json:"site_admin,omitempty"` - Contributions *int `json:"contributions,omitempty"` -} - -// ListContributorsOptions specifies the optional parameters to the -// RepositoriesService.ListContributors method. -type ListContributorsOptions struct { - // Include anonymous contributors in results or not - Anon string `url:"anon,omitempty"` - - ListOptions -} - -// ListContributors lists contributors for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-contributors -func (s *RepositoriesService) ListContributors(ctx context.Context, owner string, repository string, opt *ListContributorsOptions) ([]*Contributor, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/contributors", owner, repository) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var contributor []*Contributor - resp, err := s.client.Do(ctx, req, &contributor) - if err != nil { - return nil, nil, err - } - - return contributor, resp, nil -} - -// ListLanguages lists languages for the specified repository. The returned map -// specifies the languages and the number of bytes of code written in that -// language. For example: -// -// { -// "C": 78769, -// "Python": 7769 -// } -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-languages -func (s *RepositoriesService) ListLanguages(ctx context.Context, owner string, repo string) (map[string]int, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/languages", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - languages := make(map[string]int) - resp, err := s.client.Do(ctx, req, &languages) - if err != nil { - return nil, resp, err - } - - return languages, resp, nil -} - -// ListTeams lists the teams for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-teams -func (s *RepositoriesService) ListTeams(ctx context.Context, owner string, repo string, opt *ListOptions) ([]*Team, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/teams", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - var teams []*Team - resp, err := s.client.Do(ctx, req, &teams) - if err != nil { - return nil, resp, err - } - - return teams, resp, nil -} - -// RepositoryTag represents a repository tag. -type RepositoryTag struct { - Name *string `json:"name,omitempty"` - Commit *Commit `json:"commit,omitempty"` - ZipballURL *string `json:"zipball_url,omitempty"` - TarballURL *string `json:"tarball_url,omitempty"` -} - -// ListTags lists tags for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-tags -func (s *RepositoriesService) ListTags(ctx context.Context, owner string, repo string, opt *ListOptions) ([]*RepositoryTag, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/tags", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var tags []*RepositoryTag - resp, err := s.client.Do(ctx, req, &tags) - if err != nil { - return nil, resp, err - } - - return tags, resp, nil -} - -// Branch represents a repository branch -type Branch struct { - Name *string `json:"name,omitempty"` - Commit *RepositoryCommit `json:"commit,omitempty"` - Protected *bool `json:"protected,omitempty"` -} - -// Protection represents a repository branch's protection. -type Protection struct { - RequiredStatusChecks *RequiredStatusChecks `json:"required_status_checks"` - RequiredPullRequestReviews *PullRequestReviewsEnforcement `json:"required_pull_request_reviews"` - EnforceAdmins *AdminEnforcement `json:"enforce_admins"` - Restrictions *BranchRestrictions `json:"restrictions"` -} - -// ProtectionRequest represents a request to create/edit a branch's protection. -type ProtectionRequest struct { - RequiredStatusChecks *RequiredStatusChecks `json:"required_status_checks"` - RequiredPullRequestReviews *PullRequestReviewsEnforcementRequest `json:"required_pull_request_reviews"` - EnforceAdmins bool `json:"enforce_admins"` - Restrictions *BranchRestrictionsRequest `json:"restrictions"` -} - -// RequiredStatusChecks represents the protection status of a individual branch. -type RequiredStatusChecks struct { - // Require branches to be up to date before merging. (Required.) - Strict bool `json:"strict"` - // The list of status checks to require in order to merge into this - // branch. (Required; use []string{} instead of nil for empty list.) - Contexts []string `json:"contexts"` -} - -// PullRequestReviewsEnforcement represents the pull request reviews enforcement of a protected branch. -type PullRequestReviewsEnforcement struct { - // Specifies which users and teams can dismiss pull request reviews. - DismissalRestrictions DismissalRestrictions `json:"dismissal_restrictions"` - // Specifies if approved reviews are dismissed automatically, when a new commit is pushed. - DismissStaleReviews bool `json:"dismiss_stale_reviews"` - // RequireCodeOwnerReviews specifies if an approved review is required in pull requests including files with a designated code owner. - RequireCodeOwnerReviews bool `json:"require_code_owner_reviews"` -} - -// PullRequestReviewsEnforcementRequest represents request to set the pull request review -// enforcement of a protected branch. It is separate from PullRequestReviewsEnforcement above -// because the request structure is different from the response structure. -type PullRequestReviewsEnforcementRequest struct { - // Specifies which users and teams should be allowed to dismiss pull request reviews. Can be nil to disable the restrictions. - DismissalRestrictionsRequest *DismissalRestrictionsRequest `json:"dismissal_restrictions"` - // Specifies if approved reviews can be dismissed automatically, when a new commit is pushed. (Required) - DismissStaleReviews bool `json:"dismiss_stale_reviews"` - // RequireCodeOwnerReviews specifies if an approved review is required in pull requests including files with a designated code owner. - RequireCodeOwnerReviews bool `json:"require_code_owner_reviews"` -} - -// MarshalJSON implements the json.Marshaler interface. -// Converts nil value of PullRequestReviewsEnforcementRequest.DismissalRestrictionsRequest to empty array -func (req PullRequestReviewsEnforcementRequest) MarshalJSON() ([]byte, error) { - if req.DismissalRestrictionsRequest == nil { - newReq := struct { - R []interface{} `json:"dismissal_restrictions"` - D bool `json:"dismiss_stale_reviews"` - O bool `json:"require_code_owner_reviews"` - }{ - R: []interface{}{}, - D: req.DismissStaleReviews, - O: req.RequireCodeOwnerReviews, - } - return json.Marshal(newReq) - } - newReq := struct { - R *DismissalRestrictionsRequest `json:"dismissal_restrictions"` - D bool `json:"dismiss_stale_reviews"` - O bool `json:"require_code_owner_reviews"` - }{ - R: req.DismissalRestrictionsRequest, - D: req.DismissStaleReviews, - O: req.RequireCodeOwnerReviews, - } - return json.Marshal(newReq) -} - -// PullRequestReviewsEnforcementUpdate represents request to patch the pull request review -// enforcement of a protected branch. It is separate from PullRequestReviewsEnforcementRequest above -// because the patch request does not require all fields to be initialized. -type PullRequestReviewsEnforcementUpdate struct { - // Specifies which users and teams can dismiss pull request reviews. Can be omitted. - DismissalRestrictionsRequest *DismissalRestrictionsRequest `json:"dismissal_restrictions,omitempty"` - // Specifies if approved reviews can be dismissed automatically, when a new commit is pushed. Can be omitted. - DismissStaleReviews *bool `json:"dismiss_stale_reviews,omitempty"` - // RequireCodeOwnerReviews specifies if an approved review is required in pull requests including files with a designated code owner. - RequireCodeOwnerReviews bool `json:"require_code_owner_reviews,omitempty"` -} - -// AdminEnforcement represents the configuration to enforce required status checks for repository administrators. -type AdminEnforcement struct { - URL *string `json:"url,omitempty"` - Enabled bool `json:"enabled"` -} - -// BranchRestrictions represents the restriction that only certain users or -// teams may push to a branch. -type BranchRestrictions struct { - // The list of user logins with push access. - Users []*User `json:"users"` - // The list of team slugs with push access. - Teams []*Team `json:"teams"` -} - -// BranchRestrictionsRequest represents the request to create/edit the -// restriction that only certain users or teams may push to a branch. It is -// separate from BranchRestrictions above because the request structure is -// different from the response structure. -type BranchRestrictionsRequest struct { - // The list of user logins with push access. (Required; use []string{} instead of nil for empty list.) - Users []string `json:"users"` - // The list of team slugs with push access. (Required; use []string{} instead of nil for empty list.) - Teams []string `json:"teams"` -} - -// DismissalRestrictions specifies which users and teams can dismiss pull request reviews. -type DismissalRestrictions struct { - // The list of users who can dimiss pull request reviews. - Users []*User `json:"users"` - // The list of teams which can dismiss pull request reviews. - Teams []*Team `json:"teams"` -} - -// DismissalRestrictionsRequest represents the request to create/edit the -// restriction to allows only specific users or teams to dimiss pull request reviews. It is -// separate from DismissalRestrictions above because the request structure is -// different from the response structure. -type DismissalRestrictionsRequest struct { - // The list of user logins who can dismiss pull request reviews. (Required; use []string{} instead of nil for empty list.) - Users []string `json:"users"` - // The list of team slugs which can dismiss pull request reviews. (Required; use []string{} instead of nil for empty list.) - Teams []string `json:"teams"` -} - -// ListBranches lists branches for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-branches -func (s *RepositoriesService) ListBranches(ctx context.Context, owner string, repo string, opt *ListOptions) ([]*Branch, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - var branches []*Branch - resp, err := s.client.Do(ctx, req, &branches) - if err != nil { - return nil, resp, err - } - - return branches, resp, nil -} - -// GetBranch gets the specified branch for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#get-branch -func (s *RepositoriesService) GetBranch(ctx context.Context, owner, repo, branch string) (*Branch, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v", owner, repo, branch) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - b := new(Branch) - resp, err := s.client.Do(ctx, req, b) - if err != nil { - return nil, resp, err - } - - return b, resp, nil -} - -// GetBranchProtection gets the protection of a given branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#get-branch-protection -func (s *RepositoriesService) GetBranchProtection(ctx context.Context, owner, repo, branch string) (*Protection, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection", owner, repo, branch) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - p := new(Protection) - resp, err := s.client.Do(ctx, req, p) - if err != nil { - return nil, resp, err - } - - return p, resp, nil -} - -// GetRequiredStatusChecks gets the required status checks for a given protected branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#get-required-status-checks-of-protected-branch -func (s *RepositoriesService) GetRequiredStatusChecks(ctx context.Context, owner, repo, branch string) (*RequiredStatusChecks, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_status_checks", owner, repo, branch) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - p := new(RequiredStatusChecks) - resp, err := s.client.Do(ctx, req, p) - if err != nil { - return nil, resp, err - } - - return p, resp, nil -} - -// ListRequiredStatusChecksContexts lists the required status checks contexts for a given protected branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#list-required-status-checks-contexts-of-protected-branch -func (s *RepositoriesService) ListRequiredStatusChecksContexts(ctx context.Context, owner, repo, branch string) (contexts []string, resp *Response, err error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_status_checks/contexts", owner, repo, branch) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - resp, err = s.client.Do(ctx, req, &contexts) - if err != nil { - return nil, resp, err - } - - return contexts, resp, nil -} - -// UpdateBranchProtection updates the protection of a given branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#update-branch-protection -func (s *RepositoriesService) UpdateBranchProtection(ctx context.Context, owner, repo, branch string, preq *ProtectionRequest) (*Protection, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection", owner, repo, branch) - req, err := s.client.NewRequest("PUT", u, preq) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - p := new(Protection) - resp, err := s.client.Do(ctx, req, p) - if err != nil { - return nil, resp, err - } - - return p, resp, nil -} - -// RemoveBranchProtection removes the protection of a given branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#remove-branch-protection -func (s *RepositoriesService) RemoveBranchProtection(ctx context.Context, owner, repo, branch string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection", owner, repo, branch) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - return s.client.Do(ctx, req, nil) -} - -// License gets the contents of a repository's license if one is detected. -// -// GitHub API docs: https://developer.github.com/v3/licenses/#get-the-contents-of-a-repositorys-license -func (s *RepositoriesService) License(ctx context.Context, owner, repo string) (*RepositoryLicense, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/license", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - r := &RepositoryLicense{} - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// GetPullRequestReviewEnforcement gets pull request review enforcement of a protected branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#get-pull-request-review-enforcement-of-protected-branch -func (s *RepositoriesService) GetPullRequestReviewEnforcement(ctx context.Context, owner, repo, branch string) (*PullRequestReviewsEnforcement, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_pull_request_reviews", owner, repo, branch) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - r := new(PullRequestReviewsEnforcement) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// UpdatePullRequestReviewEnforcement patches pull request review enforcement of a protected branch. -// It requires admin access and branch protection to be enabled. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#update-pull-request-review-enforcement-of-protected-branch -func (s *RepositoriesService) UpdatePullRequestReviewEnforcement(ctx context.Context, owner, repo, branch string, patch *PullRequestReviewsEnforcementUpdate) (*PullRequestReviewsEnforcement, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_pull_request_reviews", owner, repo, branch) - req, err := s.client.NewRequest("PATCH", u, patch) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - r := new(PullRequestReviewsEnforcement) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, err -} - -// DisableDismissalRestrictions disables dismissal restrictions of a protected branch. -// It requires admin access and branch protection to be enabled. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#update-pull-request-review-enforcement-of-protected-branch -func (s *RepositoriesService) DisableDismissalRestrictions(ctx context.Context, owner, repo, branch string) (*PullRequestReviewsEnforcement, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_pull_request_reviews", owner, repo, branch) - - data := struct { - R []interface{} `json:"dismissal_restrictions"` - }{[]interface{}{}} - - req, err := s.client.NewRequest("PATCH", u, data) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - r := new(PullRequestReviewsEnforcement) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, err -} - -// RemovePullRequestReviewEnforcement removes pull request enforcement of a protected branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#remove-pull-request-review-enforcement-of-protected-branch -func (s *RepositoriesService) RemovePullRequestReviewEnforcement(ctx context.Context, owner, repo, branch string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_pull_request_reviews", owner, repo, branch) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - return s.client.Do(ctx, req, nil) -} - -// GetAdminEnforcement gets admin enforcement information of a protected branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#get-admin-enforcement-of-protected-branch -func (s *RepositoriesService) GetAdminEnforcement(ctx context.Context, owner, repo, branch string) (*AdminEnforcement, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/enforce_admins", owner, repo, branch) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - r := new(AdminEnforcement) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// AddAdminEnforcement adds admin enforcement to a protected branch. -// It requires admin access and branch protection to be enabled. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#add-admin-enforcement-of-protected-branch -func (s *RepositoriesService) AddAdminEnforcement(ctx context.Context, owner, repo, branch string) (*AdminEnforcement, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/enforce_admins", owner, repo, branch) - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - r := new(AdminEnforcement) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, err -} - -// RemoveAdminEnforcement removes admin enforcement from a protected branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#remove-admin-enforcement-of-protected-branch -func (s *RepositoriesService) RemoveAdminEnforcement(ctx context.Context, owner, repo, branch string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/enforce_admins", owner, repo, branch) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - return s.client.Do(ctx, req, nil) -} - -// repositoryTopics represents a collection of repository topics. -type repositoryTopics struct { - Names []string `json:"names"` -} - -// ListAllTopics lists topics for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-all-topics-for-a-repository -func (s *RepositoriesService) ListAllTopics(ctx context.Context, owner, repo string) ([]string, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/topics", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTopicsPreview) - - topics := new(repositoryTopics) - resp, err := s.client.Do(ctx, req, topics) - if err != nil { - return nil, resp, err - } - - return topics.Names, resp, nil -} - -// ReplaceAllTopics replaces topics for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#replace-all-topics-for-a-repository -func (s *RepositoriesService) ReplaceAllTopics(ctx context.Context, owner, repo string, topics []string) ([]string, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/topics", owner, repo) - t := &repositoryTopics{ - Names: topics, - } - if t.Names == nil { - t.Names = []string{} - } - req, err := s.client.NewRequest("PUT", u, t) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTopicsPreview) - - t = new(repositoryTopics) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t.Names, resp, nil -} - -// TransferRequest represents a request to transfer a repository. -type TransferRequest struct { - NewOwner string `json:"new_owner"` - TeamID []int64 `json:"team_id,omitempty"` -} - -// Transfer transfers a repository from one account or organization to another. -// -// This method might return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it has now scheduled the transfer of the repository in a background task. -// A follow up request, after a delay of a second or so, should result -// in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/#transfer-a-repository -func (s *RepositoriesService) Transfer(ctx context.Context, owner, repo string, transfer TransferRequest) (*Repository, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/transfer", owner, repo) - - req, err := s.client.NewRequest("POST", u, &transfer) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryTransferPreview) - - r := new(Repository) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_collaborators.go b/vendor/github.com/google/go-github/github/repos_collaborators.go deleted file mode 100644 index 61ee9d39c62..00000000000 --- a/vendor/github.com/google/go-github/github/repos_collaborators.go +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ListCollaboratorsOptions specifies the optional parameters to the -// RepositoriesService.ListCollaborators method. -type ListCollaboratorsOptions struct { - // Affiliation specifies how collaborators should be filtered by their affiliation. - // Possible values are: - // outside - All outside collaborators of an organization-owned repository - // direct - All collaborators with permissions to an organization-owned repository, - // regardless of organization membership status - // all - All collaborators the authenticated user can see - // - // Default value is "all". - Affiliation string `url:"affiliation,omitempty"` - - ListOptions -} - -// ListCollaborators lists the GitHub users that have access to the repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/collaborators/#list-collaborators -func (s *RepositoriesService) ListCollaborators(ctx context.Context, owner, repo string, opt *ListCollaboratorsOptions) ([]*User, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/collaborators", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeNestedTeamsPreview) - - var users []*User - resp, err := s.client.Do(ctx, req, &users) - if err != nil { - return nil, resp, err - } - - return users, resp, nil -} - -// IsCollaborator checks whether the specified GitHub user has collaborator -// access to the given repo. -// Note: This will return false if the user is not a collaborator OR the user -// is not a GitHub user. -// -// GitHub API docs: https://developer.github.com/v3/repos/collaborators/#get -func (s *RepositoriesService) IsCollaborator(ctx context.Context, owner, repo, user string) (bool, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/collaborators/%v", owner, repo, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - resp, err := s.client.Do(ctx, req, nil) - isCollab, err := parseBoolResponse(err) - return isCollab, resp, err -} - -// RepositoryPermissionLevel represents the permission level an organization -// member has for a given repository. -type RepositoryPermissionLevel struct { - // Possible values: "admin", "write", "read", "none" - Permission *string `json:"permission,omitempty"` - - User *User `json:"user,omitempty"` -} - -// GetPermissionLevel retrieves the specific permission level a collaborator has for a given repository. -// GitHub API docs: https://developer.github.com/v3/repos/collaborators/#review-a-users-permission-level -func (s *RepositoriesService) GetPermissionLevel(ctx context.Context, owner, repo, user string) (*RepositoryPermissionLevel, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/collaborators/%v/permission", owner, repo, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - rpl := new(RepositoryPermissionLevel) - resp, err := s.client.Do(ctx, req, rpl) - if err != nil { - return nil, resp, err - } - return rpl, resp, nil -} - -// RepositoryAddCollaboratorOptions specifies the optional parameters to the -// RepositoriesService.AddCollaborator method. -type RepositoryAddCollaboratorOptions struct { - // Permission specifies the permission to grant the user on this repository. - // Possible values are: - // pull - team members can pull, but not push to or administer this repository - // push - team members can pull and push, but not administer this repository - // admin - team members can pull, push and administer this repository - // - // Default value is "push". This option is only valid for organization-owned repositories. - Permission string `json:"permission,omitempty"` -} - -// AddCollaborator sends an invitation to the specified GitHub user -// to become a collaborator to the given repo. -// -// GitHub API docs: https://developer.github.com/v3/repos/collaborators/#add-user-as-a-collaborator -func (s *RepositoriesService) AddCollaborator(ctx context.Context, owner, repo, user string, opt *RepositoryAddCollaboratorOptions) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/collaborators/%v", owner, repo, user) - req, err := s.client.NewRequest("PUT", u, opt) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - return s.client.Do(ctx, req, nil) -} - -// RemoveCollaborator removes the specified GitHub user as collaborator from the given repo. -// Note: Does not return error if a valid user that is not a collaborator is removed. -// -// GitHub API docs: https://developer.github.com/v3/repos/collaborators/#remove-collaborator -func (s *RepositoriesService) RemoveCollaborator(ctx context.Context, owner, repo, user string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/collaborators/%v", owner, repo, user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/repos_comments.go b/vendor/github.com/google/go-github/github/repos_comments.go deleted file mode 100644 index fa2377d403d..00000000000 --- a/vendor/github.com/google/go-github/github/repos_comments.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// RepositoryComment represents a comment for a commit, file, or line in a repository. -type RepositoryComment struct { - HTMLURL *string `json:"html_url,omitempty"` - URL *string `json:"url,omitempty"` - ID *int64 `json:"id,omitempty"` - CommitID *string `json:"commit_id,omitempty"` - User *User `json:"user,omitempty"` - Reactions *Reactions `json:"reactions,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - - // User-mutable fields - Body *string `json:"body"` - // User-initialized fields - Path *string `json:"path,omitempty"` - Position *int `json:"position,omitempty"` -} - -func (r RepositoryComment) String() string { - return Stringify(r) -} - -// ListComments lists all the comments for the repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/comments/#list-commit-comments-for-a-repository -func (s *RepositoriesService) ListComments(ctx context.Context, owner, repo string, opt *ListOptions) ([]*RepositoryComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/comments", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var comments []*RepositoryComment - resp, err := s.client.Do(ctx, req, &comments) - if err != nil { - return nil, resp, err - } - - return comments, resp, nil -} - -// ListCommitComments lists all the comments for a given commit SHA. -// -// GitHub API docs: https://developer.github.com/v3/repos/comments/#list-comments-for-a-single-commit -func (s *RepositoriesService) ListCommitComments(ctx context.Context, owner, repo, sha string, opt *ListOptions) ([]*RepositoryComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v/comments", owner, repo, sha) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var comments []*RepositoryComment - resp, err := s.client.Do(ctx, req, &comments) - if err != nil { - return nil, resp, err - } - - return comments, resp, nil -} - -// CreateComment creates a comment for the given commit. -// Note: GitHub allows for comments to be created for non-existing files and positions. -// -// GitHub API docs: https://developer.github.com/v3/repos/comments/#create-a-commit-comment -func (s *RepositoriesService) CreateComment(ctx context.Context, owner, repo, sha string, comment *RepositoryComment) (*RepositoryComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v/comments", owner, repo, sha) - req, err := s.client.NewRequest("POST", u, comment) - if err != nil { - return nil, nil, err - } - - c := new(RepositoryComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// GetComment gets a single comment from a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/comments/#get-a-single-commit-comment -func (s *RepositoriesService) GetComment(ctx context.Context, owner, repo string, id int64) (*RepositoryComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/comments/%v", owner, repo, id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - c := new(RepositoryComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// UpdateComment updates the body of a single comment. -// -// GitHub API docs: https://developer.github.com/v3/repos/comments/#update-a-commit-comment -func (s *RepositoriesService) UpdateComment(ctx context.Context, owner, repo string, id int64, comment *RepositoryComment) (*RepositoryComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/comments/%v", owner, repo, id) - req, err := s.client.NewRequest("PATCH", u, comment) - if err != nil { - return nil, nil, err - } - - c := new(RepositoryComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// DeleteComment deletes a single comment from a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/comments/#delete-a-commit-comment -func (s *RepositoriesService) DeleteComment(ctx context.Context, owner, repo string, id int64) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/comments/%v", owner, repo, id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/repos_commits.go b/vendor/github.com/google/go-github/github/repos_commits.go deleted file mode 100644 index 0484737342c..00000000000 --- a/vendor/github.com/google/go-github/github/repos_commits.go +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "bytes" - "context" - "fmt" - "time" -) - -// RepositoryCommit represents a commit in a repo. -// Note that it's wrapping a Commit, so author/committer information is in two places, -// but contain different details about them: in RepositoryCommit "github details", in Commit - "git details". -type RepositoryCommit struct { - SHA *string `json:"sha,omitempty"` - Commit *Commit `json:"commit,omitempty"` - Author *User `json:"author,omitempty"` - Committer *User `json:"committer,omitempty"` - Parents []Commit `json:"parents,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - URL *string `json:"url,omitempty"` - CommentsURL *string `json:"comments_url,omitempty"` - - // Details about how many changes were made in this commit. Only filled in during GetCommit! - Stats *CommitStats `json:"stats,omitempty"` - // Details about which files, and how this commit touched. Only filled in during GetCommit! - Files []CommitFile `json:"files,omitempty"` -} - -func (r RepositoryCommit) String() string { - return Stringify(r) -} - -// CommitStats represents the number of additions / deletions from a file in a given RepositoryCommit or GistCommit. -type CommitStats struct { - Additions *int `json:"additions,omitempty"` - Deletions *int `json:"deletions,omitempty"` - Total *int `json:"total,omitempty"` -} - -func (c CommitStats) String() string { - return Stringify(c) -} - -// CommitFile represents a file modified in a commit. -type CommitFile struct { - SHA *string `json:"sha,omitempty"` - Filename *string `json:"filename,omitempty"` - Additions *int `json:"additions,omitempty"` - Deletions *int `json:"deletions,omitempty"` - Changes *int `json:"changes,omitempty"` - Status *string `json:"status,omitempty"` - Patch *string `json:"patch,omitempty"` - BlobURL *string `json:"blob_url,omitempty"` - RawURL *string `json:"raw_url,omitempty"` - ContentsURL *string `json:"contents_url,omitempty"` -} - -func (c CommitFile) String() string { - return Stringify(c) -} - -// CommitsComparison is the result of comparing two commits. -// See CompareCommits() for details. -type CommitsComparison struct { - BaseCommit *RepositoryCommit `json:"base_commit,omitempty"` - MergeBaseCommit *RepositoryCommit `json:"merge_base_commit,omitempty"` - - // Head can be 'behind' or 'ahead' - Status *string `json:"status,omitempty"` - AheadBy *int `json:"ahead_by,omitempty"` - BehindBy *int `json:"behind_by,omitempty"` - TotalCommits *int `json:"total_commits,omitempty"` - - Commits []RepositoryCommit `json:"commits,omitempty"` - - Files []CommitFile `json:"files,omitempty"` - - HTMLURL *string `json:"html_url,omitempty"` - PermalinkURL *string `json:"permalink_url,omitempty"` - DiffURL *string `json:"diff_url,omitempty"` - PatchURL *string `json:"patch_url,omitempty"` - URL *string `json:"url,omitempty"` // API URL. -} - -func (c CommitsComparison) String() string { - return Stringify(c) -} - -// CommitsListOptions specifies the optional parameters to the -// RepositoriesService.ListCommits method. -type CommitsListOptions struct { - // SHA or branch to start listing Commits from. - SHA string `url:"sha,omitempty"` - - // Path that should be touched by the returned Commits. - Path string `url:"path,omitempty"` - - // Author of by which to filter Commits. - Author string `url:"author,omitempty"` - - // Since when should Commits be included in the response. - Since time.Time `url:"since,omitempty"` - - // Until when should Commits be included in the response. - Until time.Time `url:"until,omitempty"` - - ListOptions -} - -// ListCommits lists the commits of a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/commits/#list -func (s *RepositoriesService) ListCommits(ctx context.Context, owner, repo string, opt *CommitsListOptions) ([]*RepositoryCommit, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - var commits []*RepositoryCommit - resp, err := s.client.Do(ctx, req, &commits) - if err != nil { - return nil, resp, err - } - - return commits, resp, nil -} - -// GetCommit fetches the specified commit, including all details about it. -// -// GitHub API docs: https://developer.github.com/v3/repos/commits/#get-a-single-commit -// See also: https://developer.github.com/v3/git/commits/#get-a-single-commit provides the same functionality -func (s *RepositoriesService) GetCommit(ctx context.Context, owner, repo, sha string) (*RepositoryCommit, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v", owner, repo, sha) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - commit := new(RepositoryCommit) - resp, err := s.client.Do(ctx, req, commit) - if err != nil { - return nil, resp, err - } - - return commit, resp, nil -} - -// GetCommitRaw fetches the specified commit in raw (diff or patch) format. -func (s *RepositoriesService) GetCommitRaw(ctx context.Context, owner string, repo string, sha string, opt RawOptions) (string, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v", owner, repo, sha) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return "", nil, err - } - - switch opt.Type { - case Diff: - req.Header.Set("Accept", mediaTypeV3Diff) - case Patch: - req.Header.Set("Accept", mediaTypeV3Patch) - default: - return "", nil, fmt.Errorf("unsupported raw type %d", opt.Type) - } - - var buf bytes.Buffer - resp, err := s.client.Do(ctx, req, &buf) - if err != nil { - return "", resp, err - } - - return buf.String(), resp, nil -} - -// GetCommitSHA1 gets the SHA-1 of a commit reference. If a last-known SHA1 is -// supplied and no new commits have occurred, a 304 Unmodified response is returned. -// -// GitHub API docs: https://developer.github.com/v3/repos/commits/#get-the-sha-1-of-a-commit-reference -func (s *RepositoriesService) GetCommitSHA1(ctx context.Context, owner, repo, ref, lastSHA string) (string, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v", owner, repo, ref) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return "", nil, err - } - if lastSHA != "" { - req.Header.Set("If-None-Match", `"`+lastSHA+`"`) - } - - req.Header.Set("Accept", mediaTypeV3SHA) - - var buf bytes.Buffer - resp, err := s.client.Do(ctx, req, &buf) - if err != nil { - return "", resp, err - } - - return buf.String(), resp, nil -} - -// CompareCommits compares a range of commits with each other. -// todo: support media formats - https://github.com/google/go-github/issues/6 -// -// GitHub API docs: https://developer.github.com/v3/repos/commits/index.html#compare-two-commits -func (s *RepositoriesService) CompareCommits(ctx context.Context, owner, repo string, base, head string) (*CommitsComparison, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/compare/%v...%v", owner, repo, base, head) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - comp := new(CommitsComparison) - resp, err := s.client.Do(ctx, req, comp) - if err != nil { - return nil, resp, err - } - - return comp, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_community_health.go b/vendor/github.com/google/go-github/github/repos_community_health.go deleted file mode 100644 index b5c75d6f562..00000000000 --- a/vendor/github.com/google/go-github/github/repos_community_health.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// Metric represents the different fields for one file in community health files. -type Metric struct { - Name *string `json:"name"` - Key *string `json:"key"` - URL *string `json:"url"` - HTMLURL *string `json:"html_url"` -} - -// CommunityHealthFiles represents the different files in the community health metrics response. -type CommunityHealthFiles struct { - CodeOfConduct *Metric `json:"code_of_conduct"` - Contributing *Metric `json:"contributing"` - License *Metric `json:"license"` - Readme *Metric `json:"readme"` -} - -// CommunityHealthMetrics represents a response containing the community metrics of a repository. -type CommunityHealthMetrics struct { - HealthPercentage *int `json:"health_percentage"` - Files *CommunityHealthFiles `json:"files"` - UpdatedAt *time.Time `json:"updated_at"` -} - -// GetCommunityHealthMetrics retrieves all the community health metrics for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/community/#retrieve-community-health-metrics -func (s *RepositoriesService) GetCommunityHealthMetrics(ctx context.Context, owner, repo string) (*CommunityHealthMetrics, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/community/profile", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryCommunityHealthMetricsPreview) - - metrics := &CommunityHealthMetrics{} - resp, err := s.client.Do(ctx, req, metrics) - if err != nil { - return nil, resp, err - } - - return metrics, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_contents.go b/vendor/github.com/google/go-github/github/repos_contents.go deleted file mode 100644 index ffb56b90df2..00000000000 --- a/vendor/github.com/google/go-github/github/repos_contents.go +++ /dev/null @@ -1,266 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Repository contents API methods. -// GitHub API docs: https://developer.github.com/v3/repos/contents/ - -package github - -import ( - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" -) - -// RepositoryContent represents a file or directory in a github repository. -type RepositoryContent struct { - Type *string `json:"type,omitempty"` - Encoding *string `json:"encoding,omitempty"` - Size *int `json:"size,omitempty"` - Name *string `json:"name,omitempty"` - Path *string `json:"path,omitempty"` - // Content contains the actual file content, which may be encoded. - // Callers should call GetContent which will decode the content if - // necessary. - Content *string `json:"content,omitempty"` - SHA *string `json:"sha,omitempty"` - URL *string `json:"url,omitempty"` - GitURL *string `json:"git_url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - DownloadURL *string `json:"download_url,omitempty"` -} - -// RepositoryContentResponse holds the parsed response from CreateFile, UpdateFile, and DeleteFile. -type RepositoryContentResponse struct { - Content *RepositoryContent `json:"content,omitempty"` - Commit `json:"commit,omitempty"` -} - -// RepositoryContentFileOptions specifies optional parameters for CreateFile, UpdateFile, and DeleteFile. -type RepositoryContentFileOptions struct { - Message *string `json:"message,omitempty"` - Content []byte `json:"content,omitempty"` // unencoded - SHA *string `json:"sha,omitempty"` - Branch *string `json:"branch,omitempty"` - Author *CommitAuthor `json:"author,omitempty"` - Committer *CommitAuthor `json:"committer,omitempty"` -} - -// RepositoryContentGetOptions represents an optional ref parameter, which can be a SHA, -// branch, or tag -type RepositoryContentGetOptions struct { - Ref string `url:"ref,omitempty"` -} - -// String converts RepositoryContent to a string. It's primarily for testing. -func (r RepositoryContent) String() string { - return Stringify(r) -} - -// GetContent returns the content of r, decoding it if necessary. -func (r *RepositoryContent) GetContent() (string, error) { - var encoding string - if r.Encoding != nil { - encoding = *r.Encoding - } - - switch encoding { - case "base64": - c, err := base64.StdEncoding.DecodeString(*r.Content) - return string(c), err - case "": - if r.Content == nil { - return "", nil - } - return *r.Content, nil - default: - return "", fmt.Errorf("unsupported content encoding: %v", encoding) - } -} - -// GetReadme gets the Readme file for the repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/contents/#get-the-readme -func (s *RepositoriesService) GetReadme(ctx context.Context, owner, repo string, opt *RepositoryContentGetOptions) (*RepositoryContent, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/readme", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - readme := new(RepositoryContent) - resp, err := s.client.Do(ctx, req, readme) - if err != nil { - return nil, resp, err - } - return readme, resp, nil -} - -// DownloadContents returns an io.ReadCloser that reads the contents of the -// specified file. This function will work with files of any size, as opposed -// to GetContents which is limited to 1 Mb files. It is the caller's -// responsibility to close the ReadCloser. -func (s *RepositoriesService) DownloadContents(ctx context.Context, owner, repo, filepath string, opt *RepositoryContentGetOptions) (io.ReadCloser, error) { - dir := path.Dir(filepath) - filename := path.Base(filepath) - _, dirContents, _, err := s.GetContents(ctx, owner, repo, dir, opt) - if err != nil { - return nil, err - } - for _, contents := range dirContents { - if *contents.Name == filename { - if contents.DownloadURL == nil || *contents.DownloadURL == "" { - return nil, fmt.Errorf("No download link found for %s", filepath) - } - resp, err := s.client.client.Get(*contents.DownloadURL) - if err != nil { - return nil, err - } - return resp.Body, nil - } - } - return nil, fmt.Errorf("No file named %s found in %s", filename, dir) -} - -// GetContents can return either the metadata and content of a single file -// (when path references a file) or the metadata of all the files and/or -// subdirectories of a directory (when path references a directory). To make it -// easy to distinguish between both result types and to mimic the API as much -// as possible, both result types will be returned but only one will contain a -// value and the other will be nil. -// -// GitHub API docs: https://developer.github.com/v3/repos/contents/#get-contents -func (s *RepositoriesService) GetContents(ctx context.Context, owner, repo, path string, opt *RepositoryContentGetOptions) (fileContent *RepositoryContent, directoryContent []*RepositoryContent, resp *Response, err error) { - escapedPath := (&url.URL{Path: path}).String() - u := fmt.Sprintf("repos/%s/%s/contents/%s", owner, repo, escapedPath) - u, err = addOptions(u, opt) - if err != nil { - return nil, nil, nil, err - } - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, nil, err - } - var rawJSON json.RawMessage - resp, err = s.client.Do(ctx, req, &rawJSON) - if err != nil { - return nil, nil, resp, err - } - fileUnmarshalError := json.Unmarshal(rawJSON, &fileContent) - if fileUnmarshalError == nil { - return fileContent, nil, resp, nil - } - directoryUnmarshalError := json.Unmarshal(rawJSON, &directoryContent) - if directoryUnmarshalError == nil { - return nil, directoryContent, resp, nil - } - return nil, nil, resp, fmt.Errorf("unmarshalling failed for both file and directory content: %s and %s", fileUnmarshalError, directoryUnmarshalError) -} - -// CreateFile creates a new file in a repository at the given path and returns -// the commit and file metadata. -// -// GitHub API docs: https://developer.github.com/v3/repos/contents/#create-a-file -func (s *RepositoriesService) CreateFile(ctx context.Context, owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/contents/%s", owner, repo, path) - req, err := s.client.NewRequest("PUT", u, opt) - if err != nil { - return nil, nil, err - } - createResponse := new(RepositoryContentResponse) - resp, err := s.client.Do(ctx, req, createResponse) - if err != nil { - return nil, resp, err - } - return createResponse, resp, nil -} - -// UpdateFile updates a file in a repository at the given path and returns the -// commit and file metadata. Requires the blob SHA of the file being updated. -// -// GitHub API docs: https://developer.github.com/v3/repos/contents/#update-a-file -func (s *RepositoriesService) UpdateFile(ctx context.Context, owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/contents/%s", owner, repo, path) - req, err := s.client.NewRequest("PUT", u, opt) - if err != nil { - return nil, nil, err - } - updateResponse := new(RepositoryContentResponse) - resp, err := s.client.Do(ctx, req, updateResponse) - if err != nil { - return nil, resp, err - } - return updateResponse, resp, nil -} - -// DeleteFile deletes a file from a repository and returns the commit. -// Requires the blob SHA of the file to be deleted. -// -// GitHub API docs: https://developer.github.com/v3/repos/contents/#delete-a-file -func (s *RepositoriesService) DeleteFile(ctx context.Context, owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/contents/%s", owner, repo, path) - req, err := s.client.NewRequest("DELETE", u, opt) - if err != nil { - return nil, nil, err - } - deleteResponse := new(RepositoryContentResponse) - resp, err := s.client.Do(ctx, req, deleteResponse) - if err != nil { - return nil, resp, err - } - return deleteResponse, resp, nil -} - -// archiveFormat is used to define the archive type when calling GetArchiveLink. -type archiveFormat string - -const ( - // Tarball specifies an archive in gzipped tar format. - Tarball archiveFormat = "tarball" - - // Zipball specifies an archive in zip format. - Zipball archiveFormat = "zipball" -) - -// GetArchiveLink returns an URL to download a tarball or zipball archive for a -// repository. The archiveFormat can be specified by either the github.Tarball -// or github.Zipball constant. -// -// GitHub API docs: https://developer.github.com/v3/repos/contents/#get-archive-link -func (s *RepositoriesService) GetArchiveLink(ctx context.Context, owner, repo string, archiveformat archiveFormat, opt *RepositoryContentGetOptions) (*url.URL, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/%s", owner, repo, archiveformat) - if opt != nil && opt.Ref != "" { - u += fmt.Sprintf("/%s", opt.Ref) - } - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - var resp *http.Response - // Use http.DefaultTransport if no custom Transport is configured - req = withContext(ctx, req) - if s.client.client.Transport == nil { - resp, err = http.DefaultTransport.RoundTrip(req) - } else { - resp, err = s.client.client.Transport.RoundTrip(req) - } - if err != nil { - return nil, nil, err - } - resp.Body.Close() - if resp.StatusCode != http.StatusFound { - return nil, newResponse(resp), fmt.Errorf("unexpected status code: %s", resp.Status) - } - parsedURL, err := url.Parse(resp.Header.Get("Location")) - return parsedURL, newResponse(resp), err -} diff --git a/vendor/github.com/google/go-github/github/repos_deployments.go b/vendor/github.com/google/go-github/github/repos_deployments.go deleted file mode 100644 index 1300f05ee29..00000000000 --- a/vendor/github.com/google/go-github/github/repos_deployments.go +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "encoding/json" - "fmt" - "strings" -) - -// Deployment represents a deployment in a repo -type Deployment struct { - URL *string `json:"url,omitempty"` - ID *int64 `json:"id,omitempty"` - SHA *string `json:"sha,omitempty"` - Ref *string `json:"ref,omitempty"` - Task *string `json:"task,omitempty"` - Payload json.RawMessage `json:"payload,omitempty"` - Environment *string `json:"environment,omitempty"` - Description *string `json:"description,omitempty"` - Creator *User `json:"creator,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - StatusesURL *string `json:"statuses_url,omitempty"` - RepositoryURL *string `json:"repository_url,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -// DeploymentRequest represents a deployment request -type DeploymentRequest struct { - Ref *string `json:"ref,omitempty"` - Task *string `json:"task,omitempty"` - AutoMerge *bool `json:"auto_merge,omitempty"` - RequiredContexts *[]string `json:"required_contexts,omitempty"` - Payload *string `json:"payload,omitempty"` - Environment *string `json:"environment,omitempty"` - Description *string `json:"description,omitempty"` - TransientEnvironment *bool `json:"transient_environment,omitempty"` - ProductionEnvironment *bool `json:"production_environment,omitempty"` -} - -// DeploymentsListOptions specifies the optional parameters to the -// RepositoriesService.ListDeployments method. -type DeploymentsListOptions struct { - // SHA of the Deployment. - SHA string `url:"sha,omitempty"` - - // List deployments for a given ref. - Ref string `url:"ref,omitempty"` - - // List deployments for a given task. - Task string `url:"task,omitempty"` - - // List deployments for a given environment. - Environment string `url:"environment,omitempty"` - - ListOptions -} - -// ListDeployments lists the deployments of a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/deployments/#list-deployments -func (s *RepositoriesService) ListDeployments(ctx context.Context, owner, repo string, opt *DeploymentsListOptions) ([]*Deployment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/deployments", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - var deployments []*Deployment - resp, err := s.client.Do(ctx, req, &deployments) - if err != nil { - return nil, resp, err - } - - return deployments, resp, nil -} - -// GetDeployment returns a single deployment of a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/deployments/#get-a-single-deployment -func (s *RepositoriesService) GetDeployment(ctx context.Context, owner, repo string, deploymentID int64) (*Deployment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/deployments/%v", owner, repo, deploymentID) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - deployment := new(Deployment) - resp, err := s.client.Do(ctx, req, deployment) - if err != nil { - return nil, resp, err - } - - return deployment, resp, nil -} - -// CreateDeployment creates a new deployment for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/deployments/#create-a-deployment -func (s *RepositoriesService) CreateDeployment(ctx context.Context, owner, repo string, request *DeploymentRequest) (*Deployment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/deployments", owner, repo) - - req, err := s.client.NewRequest("POST", u, request) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - acceptHeaders := []string{mediaTypeDeploymentStatusPreview, mediaTypeGraphQLNodeIDPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - d := new(Deployment) - resp, err := s.client.Do(ctx, req, d) - if err != nil { - return nil, resp, err - } - - return d, resp, nil -} - -// DeploymentStatus represents the status of a -// particular deployment. -type DeploymentStatus struct { - ID *int64 `json:"id,omitempty"` - // State is the deployment state. - // Possible values are: "pending", "success", "failure", "error", "inactive". - State *string `json:"state,omitempty"` - Creator *User `json:"creator,omitempty"` - Description *string `json:"description,omitempty"` - TargetURL *string `json:"target_url,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - DeploymentURL *string `json:"deployment_url,omitempty"` - RepositoryURL *string `json:"repository_url,omitempty"` - NodeID *string `json:"node_id,omitempty"` -} - -// DeploymentStatusRequest represents a deployment request -type DeploymentStatusRequest struct { - State *string `json:"state,omitempty"` - LogURL *string `json:"log_url,omitempty"` - Description *string `json:"description,omitempty"` - EnvironmentURL *string `json:"environment_url,omitempty"` - AutoInactive *bool `json:"auto_inactive,omitempty"` -} - -// ListDeploymentStatuses lists the statuses of a given deployment of a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/deployments/#list-deployment-statuses -func (s *RepositoriesService) ListDeploymentStatuses(ctx context.Context, owner, repo string, deployment int64, opt *ListOptions) ([]*DeploymentStatus, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/deployments/%v/statuses", owner, repo, deployment) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGraphQLNodeIDPreview) - - var statuses []*DeploymentStatus - resp, err := s.client.Do(ctx, req, &statuses) - if err != nil { - return nil, resp, err - } - - return statuses, resp, nil -} - -// GetDeploymentStatus returns a single deployment status of a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/deployments/#get-a-single-deployment-status -func (s *RepositoriesService) GetDeploymentStatus(ctx context.Context, owner, repo string, deploymentID, deploymentStatusID int64) (*DeploymentStatus, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/deployments/%v/statuses/%v", owner, repo, deploymentID, deploymentStatusID) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - acceptHeaders := []string{mediaTypeDeploymentStatusPreview, mediaTypeGraphQLNodeIDPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - d := new(DeploymentStatus) - resp, err := s.client.Do(ctx, req, d) - if err != nil { - return nil, resp, err - } - - return d, resp, nil -} - -// CreateDeploymentStatus creates a new status for a deployment. -// -// GitHub API docs: https://developer.github.com/v3/repos/deployments/#create-a-deployment-status -func (s *RepositoriesService) CreateDeploymentStatus(ctx context.Context, owner, repo string, deployment int64, request *DeploymentStatusRequest) (*DeploymentStatus, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/deployments/%v/statuses", owner, repo, deployment) - - req, err := s.client.NewRequest("POST", u, request) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - acceptHeaders := []string{mediaTypeDeploymentStatusPreview, mediaTypeGraphQLNodeIDPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - d := new(DeploymentStatus) - resp, err := s.client.Do(ctx, req, d) - if err != nil { - return nil, resp, err - } - - return d, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_forks.go b/vendor/github.com/google/go-github/github/repos_forks.go deleted file mode 100644 index 4ca19a42dc3..00000000000 --- a/vendor/github.com/google/go-github/github/repos_forks.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// RepositoryListForksOptions specifies the optional parameters to the -// RepositoriesService.ListForks method. -type RepositoryListForksOptions struct { - // How to sort the forks list. Possible values are: newest, oldest, - // watchers. Default is "newest". - Sort string `url:"sort,omitempty"` - - ListOptions -} - -// ListForks lists the forks of the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/forks/#list-forks -func (s *RepositoriesService) ListForks(ctx context.Context, owner, repo string, opt *RepositoryListForksOptions) ([]*Repository, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/forks", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when topics API fully launches. - req.Header.Set("Accept", mediaTypeTopicsPreview) - - var repos []*Repository - resp, err := s.client.Do(ctx, req, &repos) - if err != nil { - return nil, resp, err - } - - return repos, resp, nil -} - -// RepositoryCreateForkOptions specifies the optional parameters to the -// RepositoriesService.CreateFork method. -type RepositoryCreateForkOptions struct { - // The organization to fork the repository into. - Organization string `url:"organization,omitempty"` -} - -// CreateFork creates a fork of the specified repository. -// -// This method might return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it is now computing creating the fork in a background task. -// A follow up request, after a delay of a second or so, should result -// in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/forks/#create-a-fork -func (s *RepositoriesService) CreateFork(ctx context.Context, owner, repo string, opt *RepositoryCreateForkOptions) (*Repository, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/forks", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, nil, err - } - - fork := new(Repository) - resp, err := s.client.Do(ctx, req, fork) - if err != nil { - return nil, resp, err - } - - return fork, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_hooks.go b/vendor/github.com/google/go-github/github/repos_hooks.go deleted file mode 100644 index f7ab3a13d63..00000000000 --- a/vendor/github.com/google/go-github/github/repos_hooks.go +++ /dev/null @@ -1,192 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// WebHookPayload represents the data that is received from GitHub when a push -// event hook is triggered. The format of these payloads pre-date most of the -// GitHub v3 API, so there are lots of minor incompatibilities with the types -// defined in the rest of the API. Therefore, several types are duplicated -// here to account for these differences. -// -// GitHub API docs: https://help.github.com/articles/post-receive-hooks -type WebHookPayload struct { - After *string `json:"after,omitempty"` - Before *string `json:"before,omitempty"` - Commits []WebHookCommit `json:"commits,omitempty"` - Compare *string `json:"compare,omitempty"` - Created *bool `json:"created,omitempty"` - Deleted *bool `json:"deleted,omitempty"` - Forced *bool `json:"forced,omitempty"` - HeadCommit *WebHookCommit `json:"head_commit,omitempty"` - Pusher *User `json:"pusher,omitempty"` - Ref *string `json:"ref,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` -} - -func (w WebHookPayload) String() string { - return Stringify(w) -} - -// WebHookCommit represents the commit variant we receive from GitHub in a -// WebHookPayload. -type WebHookCommit struct { - Added []string `json:"added,omitempty"` - Author *WebHookAuthor `json:"author,omitempty"` - Committer *WebHookAuthor `json:"committer,omitempty"` - Distinct *bool `json:"distinct,omitempty"` - ID *string `json:"id,omitempty"` - Message *string `json:"message,omitempty"` - Modified []string `json:"modified,omitempty"` - Removed []string `json:"removed,omitempty"` - Timestamp *time.Time `json:"timestamp,omitempty"` -} - -func (w WebHookCommit) String() string { - return Stringify(w) -} - -// WebHookAuthor represents the author or committer of a commit, as specified -// in a WebHookCommit. The commit author may not correspond to a GitHub User. -type WebHookAuthor struct { - Email *string `json:"email,omitempty"` - Name *string `json:"name,omitempty"` - Username *string `json:"username,omitempty"` -} - -func (w WebHookAuthor) String() string { - return Stringify(w) -} - -// Hook represents a GitHub (web and service) hook for a repository. -type Hook struct { - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - Name *string `json:"name,omitempty"` - URL *string `json:"url,omitempty"` - Events []string `json:"events,omitempty"` - Active *bool `json:"active,omitempty"` - Config map[string]interface{} `json:"config,omitempty"` - ID *int64 `json:"id,omitempty"` -} - -func (h Hook) String() string { - return Stringify(h) -} - -// CreateHook creates a Hook for the specified repository. -// Name and Config are required fields. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#create-a-hook -func (s *RepositoriesService) CreateHook(ctx context.Context, owner, repo string, hook *Hook) (*Hook, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks", owner, repo) - req, err := s.client.NewRequest("POST", u, hook) - if err != nil { - return nil, nil, err - } - - h := new(Hook) - resp, err := s.client.Do(ctx, req, h) - if err != nil { - return nil, resp, err - } - - return h, resp, nil -} - -// ListHooks lists all Hooks for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#list -func (s *RepositoriesService) ListHooks(ctx context.Context, owner, repo string, opt *ListOptions) ([]*Hook, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var hooks []*Hook - resp, err := s.client.Do(ctx, req, &hooks) - if err != nil { - return nil, resp, err - } - - return hooks, resp, nil -} - -// GetHook returns a single specified Hook. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#get-single-hook -func (s *RepositoriesService) GetHook(ctx context.Context, owner, repo string, id int64) (*Hook, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks/%d", owner, repo, id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - hook := new(Hook) - resp, err := s.client.Do(ctx, req, hook) - return hook, resp, err -} - -// EditHook updates a specified Hook. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#edit-a-hook -func (s *RepositoriesService) EditHook(ctx context.Context, owner, repo string, id int64, hook *Hook) (*Hook, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks/%d", owner, repo, id) - req, err := s.client.NewRequest("PATCH", u, hook) - if err != nil { - return nil, nil, err - } - h := new(Hook) - resp, err := s.client.Do(ctx, req, h) - return h, resp, err -} - -// DeleteHook deletes a specified Hook. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#delete-a-hook -func (s *RepositoriesService) DeleteHook(ctx context.Context, owner, repo string, id int64) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks/%d", owner, repo, id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// PingHook triggers a 'ping' event to be sent to the Hook. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#ping-a-hook -func (s *RepositoriesService) PingHook(ctx context.Context, owner, repo string, id int64) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks/%d/pings", owner, repo, id) - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// TestHook triggers a test Hook by github. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#test-a-push-hook -func (s *RepositoriesService) TestHook(ctx context.Context, owner, repo string, id int64) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks/%d/tests", owner, repo, id) - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/repos_invitations.go b/vendor/github.com/google/go-github/github/repos_invitations.go deleted file mode 100644 index 34bf3830fb1..00000000000 --- a/vendor/github.com/google/go-github/github/repos_invitations.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// RepositoryInvitation represents an invitation to collaborate on a repo. -type RepositoryInvitation struct { - ID *int64 `json:"id,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Invitee *User `json:"invitee,omitempty"` - Inviter *User `json:"inviter,omitempty"` - - // Permissions represents the permissions that the associated user will have - // on the repository. Possible values are: "read", "write", "admin". - Permissions *string `json:"permissions,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` -} - -// ListInvitations lists all currently-open repository invitations. -// -// GitHub API docs: https://developer.github.com/v3/repos/invitations/#list-invitations-for-a-repository -func (s *RepositoriesService) ListInvitations(ctx context.Context, owner, repo string, opt *ListOptions) ([]*RepositoryInvitation, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/invitations", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - invites := []*RepositoryInvitation{} - resp, err := s.client.Do(ctx, req, &invites) - if err != nil { - return nil, resp, err - } - - return invites, resp, nil -} - -// DeleteInvitation deletes a repository invitation. -// -// GitHub API docs: https://developer.github.com/v3/repos/invitations/#delete-a-repository-invitation -func (s *RepositoriesService) DeleteInvitation(ctx context.Context, owner, repo string, invitationID int64) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/invitations/%v", owner, repo, invitationID) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - return s.client.Do(ctx, req, nil) -} - -// UpdateInvitation updates the permissions associated with a repository -// invitation. -// -// permissions represents the permissions that the associated user will have -// on the repository. Possible values are: "read", "write", "admin". -// -// GitHub API docs: https://developer.github.com/v3/repos/invitations/#update-a-repository-invitation -func (s *RepositoriesService) UpdateInvitation(ctx context.Context, owner, repo string, invitationID int64, permissions string) (*RepositoryInvitation, *Response, error) { - opts := &struct { - Permissions string `json:"permissions"` - }{Permissions: permissions} - u := fmt.Sprintf("repos/%v/%v/invitations/%v", owner, repo, invitationID) - req, err := s.client.NewRequest("PATCH", u, opts) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - invite := &RepositoryInvitation{} - resp, err := s.client.Do(ctx, req, invite) - if err != nil { - return nil, resp, err - } - - return invite, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_keys.go b/vendor/github.com/google/go-github/github/repos_keys.go deleted file mode 100644 index 966d7b540b1..00000000000 --- a/vendor/github.com/google/go-github/github/repos_keys.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// The Key type is defined in users_keys.go - -// ListKeys lists the deploy keys for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/keys/#list -func (s *RepositoriesService) ListKeys(ctx context.Context, owner string, repo string, opt *ListOptions) ([]*Key, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/keys", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var keys []*Key - resp, err := s.client.Do(ctx, req, &keys) - if err != nil { - return nil, resp, err - } - - return keys, resp, nil -} - -// GetKey fetches a single deploy key. -// -// GitHub API docs: https://developer.github.com/v3/repos/keys/#get -func (s *RepositoriesService) GetKey(ctx context.Context, owner string, repo string, id int64) (*Key, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/keys/%v", owner, repo, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - key := new(Key) - resp, err := s.client.Do(ctx, req, key) - if err != nil { - return nil, resp, err - } - - return key, resp, nil -} - -// CreateKey adds a deploy key for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/keys/#create -func (s *RepositoriesService) CreateKey(ctx context.Context, owner string, repo string, key *Key) (*Key, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/keys", owner, repo) - - req, err := s.client.NewRequest("POST", u, key) - if err != nil { - return nil, nil, err - } - - k := new(Key) - resp, err := s.client.Do(ctx, req, k) - if err != nil { - return nil, resp, err - } - - return k, resp, nil -} - -// EditKey edits a deploy key. -// -// GitHub API docs: https://developer.github.com/v3/repos/keys/#edit -func (s *RepositoriesService) EditKey(ctx context.Context, owner string, repo string, id int, key *Key) (*Key, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/keys/%v", owner, repo, id) - - req, err := s.client.NewRequest("PATCH", u, key) - if err != nil { - return nil, nil, err - } - - k := new(Key) - resp, err := s.client.Do(ctx, req, k) - if err != nil { - return nil, resp, err - } - - return k, resp, nil -} - -// DeleteKey deletes a deploy key. -// -// GitHub API docs: https://developer.github.com/v3/repos/keys/#delete -func (s *RepositoriesService) DeleteKey(ctx context.Context, owner string, repo string, id int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/keys/%v", owner, repo, id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/repos_merging.go b/vendor/github.com/google/go-github/github/repos_merging.go deleted file mode 100644 index 04383c1ae32..00000000000 --- a/vendor/github.com/google/go-github/github/repos_merging.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// RepositoryMergeRequest represents a request to merge a branch in a -// repository. -type RepositoryMergeRequest struct { - Base *string `json:"base,omitempty"` - Head *string `json:"head,omitempty"` - CommitMessage *string `json:"commit_message,omitempty"` -} - -// Merge a branch in the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/merging/#perform-a-merge -func (s *RepositoriesService) Merge(ctx context.Context, owner, repo string, request *RepositoryMergeRequest) (*RepositoryCommit, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/merges", owner, repo) - req, err := s.client.NewRequest("POST", u, request) - if err != nil { - return nil, nil, err - } - - commit := new(RepositoryCommit) - resp, err := s.client.Do(ctx, req, commit) - if err != nil { - return nil, resp, err - } - - return commit, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_pages.go b/vendor/github.com/google/go-github/github/repos_pages.go deleted file mode 100644 index 94a95f2b8ed..00000000000 --- a/vendor/github.com/google/go-github/github/repos_pages.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// Pages represents a GitHub Pages site configuration. -type Pages struct { - URL *string `json:"url,omitempty"` - Status *string `json:"status,omitempty"` - CNAME *string `json:"cname,omitempty"` - Custom404 *bool `json:"custom_404,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` -} - -// PagesError represents a build error for a GitHub Pages site. -type PagesError struct { - Message *string `json:"message,omitempty"` -} - -// PagesBuild represents the build information for a GitHub Pages site. -type PagesBuild struct { - URL *string `json:"url,omitempty"` - Status *string `json:"status,omitempty"` - Error *PagesError `json:"error,omitempty"` - Pusher *User `json:"pusher,omitempty"` - Commit *string `json:"commit,omitempty"` - Duration *int `json:"duration,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` -} - -// GetPagesInfo fetches information about a GitHub Pages site. -// -// GitHub API docs: https://developer.github.com/v3/repos/pages/#get-information-about-a-pages-site -func (s *RepositoriesService) GetPagesInfo(ctx context.Context, owner, repo string) (*Pages, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pages", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypePagesPreview) - - site := new(Pages) - resp, err := s.client.Do(ctx, req, site) - if err != nil { - return nil, resp, err - } - - return site, resp, nil -} - -// ListPagesBuilds lists the builds for a GitHub Pages site. -// -// GitHub API docs: https://developer.github.com/v3/repos/pages/#list-pages-builds -func (s *RepositoriesService) ListPagesBuilds(ctx context.Context, owner, repo string, opt *ListOptions) ([]*PagesBuild, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pages/builds", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var pages []*PagesBuild - resp, err := s.client.Do(ctx, req, &pages) - if err != nil { - return nil, resp, err - } - - return pages, resp, nil -} - -// GetLatestPagesBuild fetches the latest build information for a GitHub pages site. -// -// GitHub API docs: https://developer.github.com/v3/repos/pages/#list-latest-pages-build -func (s *RepositoriesService) GetLatestPagesBuild(ctx context.Context, owner, repo string) (*PagesBuild, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pages/builds/latest", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - build := new(PagesBuild) - resp, err := s.client.Do(ctx, req, build) - if err != nil { - return nil, resp, err - } - - return build, resp, nil -} - -// GetPageBuild fetches the specific build information for a GitHub pages site. -// -// GitHub API docs: https://developer.github.com/v3/repos/pages/#list-a-specific-pages-build -func (s *RepositoriesService) GetPageBuild(ctx context.Context, owner, repo string, id int64) (*PagesBuild, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pages/builds/%v", owner, repo, id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - build := new(PagesBuild) - resp, err := s.client.Do(ctx, req, build) - if err != nil { - return nil, resp, err - } - - return build, resp, nil -} - -// RequestPageBuild requests a build of a GitHub Pages site without needing to push new commit. -// -// GitHub API docs: https://developer.github.com/v3/repos/pages/#request-a-page-build -func (s *RepositoriesService) RequestPageBuild(ctx context.Context, owner, repo string) (*PagesBuild, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pages/builds", owner, repo) - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypePagesPreview) - - build := new(PagesBuild) - resp, err := s.client.Do(ctx, req, build) - if err != nil { - return nil, resp, err - } - - return build, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_projects.go b/vendor/github.com/google/go-github/github/repos_projects.go deleted file mode 100644 index 770ffc76fa6..00000000000 --- a/vendor/github.com/google/go-github/github/repos_projects.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ProjectListOptions specifies the optional parameters to the -// OrganizationsService.ListProjects and RepositoriesService.ListProjects methods. -type ProjectListOptions struct { - // Indicates the state of the projects to return. Can be either open, closed, or all. Default: open - State string `url:"state,omitempty"` - - ListOptions -} - -// ListProjects lists the projects for a repo. -// -// GitHub API docs: https://developer.github.com/v3/projects/#list-repository-projects -func (s *RepositoriesService) ListProjects(ctx context.Context, owner, repo string, opt *ProjectListOptions) ([]*Project, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/projects", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - var projects []*Project - resp, err := s.client.Do(ctx, req, &projects) - if err != nil { - return nil, resp, err - } - - return projects, resp, nil -} - -// CreateProject creates a GitHub Project for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/projects/#create-a-repository-project -func (s *RepositoriesService) CreateProject(ctx context.Context, owner, repo string, opt *ProjectOptions) (*Project, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/projects", owner, repo) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - project := &Project{} - resp, err := s.client.Do(ctx, req, project) - if err != nil { - return nil, resp, err - } - - return project, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_releases.go b/vendor/github.com/google/go-github/github/repos_releases.go deleted file mode 100644 index 7ad2b278ab5..00000000000 --- a/vendor/github.com/google/go-github/github/repos_releases.go +++ /dev/null @@ -1,327 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "errors" - "fmt" - "io" - "mime" - "net/http" - "os" - "path/filepath" - "strings" -) - -// RepositoryRelease represents a GitHub release in a repository. -type RepositoryRelease struct { - ID *int64 `json:"id,omitempty"` - TagName *string `json:"tag_name,omitempty"` - TargetCommitish *string `json:"target_commitish,omitempty"` - Name *string `json:"name,omitempty"` - Body *string `json:"body,omitempty"` - Draft *bool `json:"draft,omitempty"` - Prerelease *bool `json:"prerelease,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - PublishedAt *Timestamp `json:"published_at,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - AssetsURL *string `json:"assets_url,omitempty"` - Assets []ReleaseAsset `json:"assets,omitempty"` - UploadURL *string `json:"upload_url,omitempty"` - ZipballURL *string `json:"zipball_url,omitempty"` - TarballURL *string `json:"tarball_url,omitempty"` - Author *User `json:"author,omitempty"` -} - -func (r RepositoryRelease) String() string { - return Stringify(r) -} - -// ReleaseAsset represents a GitHub release asset in a repository. -type ReleaseAsset struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - Name *string `json:"name,omitempty"` - Label *string `json:"label,omitempty"` - State *string `json:"state,omitempty"` - ContentType *string `json:"content_type,omitempty"` - Size *int `json:"size,omitempty"` - DownloadCount *int `json:"download_count,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - BrowserDownloadURL *string `json:"browser_download_url,omitempty"` - Uploader *User `json:"uploader,omitempty"` -} - -func (r ReleaseAsset) String() string { - return Stringify(r) -} - -// ListReleases lists the releases for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#list-releases-for-a-repository -func (s *RepositoriesService) ListReleases(ctx context.Context, owner, repo string, opt *ListOptions) ([]*RepositoryRelease, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var releases []*RepositoryRelease - resp, err := s.client.Do(ctx, req, &releases) - if err != nil { - return nil, resp, err - } - return releases, resp, nil -} - -// GetRelease fetches a single release. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#get-a-single-release -func (s *RepositoriesService) GetRelease(ctx context.Context, owner, repo string, id int64) (*RepositoryRelease, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/%d", owner, repo, id) - return s.getSingleRelease(ctx, u) -} - -// GetLatestRelease fetches the latest published release for the repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#get-the-latest-release -func (s *RepositoriesService) GetLatestRelease(ctx context.Context, owner, repo string) (*RepositoryRelease, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/latest", owner, repo) - return s.getSingleRelease(ctx, u) -} - -// GetReleaseByTag fetches a release with the specified tag. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#get-a-release-by-tag-name -func (s *RepositoriesService) GetReleaseByTag(ctx context.Context, owner, repo, tag string) (*RepositoryRelease, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/tags/%s", owner, repo, tag) - return s.getSingleRelease(ctx, u) -} - -func (s *RepositoriesService) getSingleRelease(ctx context.Context, url string) (*RepositoryRelease, *Response, error) { - req, err := s.client.NewRequest("GET", url, nil) - if err != nil { - return nil, nil, err - } - - release := new(RepositoryRelease) - resp, err := s.client.Do(ctx, req, release) - if err != nil { - return nil, resp, err - } - return release, resp, nil -} - -// CreateRelease adds a new release for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#create-a-release -func (s *RepositoriesService) CreateRelease(ctx context.Context, owner, repo string, release *RepositoryRelease) (*RepositoryRelease, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases", owner, repo) - - req, err := s.client.NewRequest("POST", u, release) - if err != nil { - return nil, nil, err - } - - r := new(RepositoryRelease) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - return r, resp, nil -} - -// EditRelease edits a repository release. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#edit-a-release -func (s *RepositoriesService) EditRelease(ctx context.Context, owner, repo string, id int64, release *RepositoryRelease) (*RepositoryRelease, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/%d", owner, repo, id) - - req, err := s.client.NewRequest("PATCH", u, release) - if err != nil { - return nil, nil, err - } - - r := new(RepositoryRelease) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - return r, resp, nil -} - -// DeleteRelease delete a single release from a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#delete-a-release -func (s *RepositoriesService) DeleteRelease(ctx context.Context, owner, repo string, id int64) (*Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/%d", owner, repo, id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// ListReleaseAssets lists the release's assets. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#list-assets-for-a-release -func (s *RepositoriesService) ListReleaseAssets(ctx context.Context, owner, repo string, id int64, opt *ListOptions) ([]*ReleaseAsset, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/%d/assets", owner, repo, id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var assets []*ReleaseAsset - resp, err := s.client.Do(ctx, req, &assets) - if err != nil { - return nil, resp, err - } - return assets, resp, nil -} - -// GetReleaseAsset fetches a single release asset. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#get-a-single-release-asset -func (s *RepositoriesService) GetReleaseAsset(ctx context.Context, owner, repo string, id int64) (*ReleaseAsset, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/assets/%d", owner, repo, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - asset := new(ReleaseAsset) - resp, err := s.client.Do(ctx, req, asset) - if err != nil { - return nil, resp, err - } - return asset, resp, nil -} - -// DownloadReleaseAsset downloads a release asset or returns a redirect URL. -// -// DownloadReleaseAsset returns an io.ReadCloser that reads the contents of the -// specified release asset. It is the caller's responsibility to close the ReadCloser. -// If a redirect is returned, the redirect URL will be returned as a string instead -// of the io.ReadCloser. Exactly one of rc and redirectURL will be zero. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#get-a-single-release-asset -func (s *RepositoriesService) DownloadReleaseAsset(ctx context.Context, owner, repo string, id int64) (rc io.ReadCloser, redirectURL string, err error) { - u := fmt.Sprintf("repos/%s/%s/releases/assets/%d", owner, repo, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, "", err - } - req.Header.Set("Accept", defaultMediaType) - - s.client.clientMu.Lock() - defer s.client.clientMu.Unlock() - - var loc string - saveRedirect := s.client.client.CheckRedirect - s.client.client.CheckRedirect = func(req *http.Request, via []*http.Request) error { - loc = req.URL.String() - return errors.New("disable redirect") - } - defer func() { s.client.client.CheckRedirect = saveRedirect }() - - req = withContext(ctx, req) - resp, err := s.client.client.Do(req) - if err != nil { - if !strings.Contains(err.Error(), "disable redirect") { - return nil, "", err - } - return nil, loc, nil // Intentionally return no error with valid redirect URL. - } - - if err := CheckResponse(resp); err != nil { - resp.Body.Close() - return nil, "", err - } - - return resp.Body, "", nil -} - -// EditReleaseAsset edits a repository release asset. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#edit-a-release-asset -func (s *RepositoriesService) EditReleaseAsset(ctx context.Context, owner, repo string, id int64, release *ReleaseAsset) (*ReleaseAsset, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/assets/%d", owner, repo, id) - - req, err := s.client.NewRequest("PATCH", u, release) - if err != nil { - return nil, nil, err - } - - asset := new(ReleaseAsset) - resp, err := s.client.Do(ctx, req, asset) - if err != nil { - return nil, resp, err - } - return asset, resp, nil -} - -// DeleteReleaseAsset delete a single release asset from a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#delete-a-release-asset -func (s *RepositoriesService) DeleteReleaseAsset(ctx context.Context, owner, repo string, id int64) (*Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/assets/%d", owner, repo, id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// UploadReleaseAsset creates an asset by uploading a file into a release repository. -// To upload assets that cannot be represented by an os.File, call NewUploadRequest directly. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#upload-a-release-asset -func (s *RepositoriesService) UploadReleaseAsset(ctx context.Context, owner, repo string, id int64, opt *UploadOptions, file *os.File) (*ReleaseAsset, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/%d/assets", owner, repo, id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - stat, err := file.Stat() - if err != nil { - return nil, nil, err - } - if stat.IsDir() { - return nil, nil, errors.New("the asset to upload can't be a directory") - } - - mediaType := mime.TypeByExtension(filepath.Ext(file.Name())) - req, err := s.client.NewUploadRequest(u, file, stat.Size(), mediaType) - if err != nil { - return nil, nil, err - } - - asset := new(ReleaseAsset) - resp, err := s.client.Do(ctx, req, asset) - if err != nil { - return nil, resp, err - } - return asset, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_stats.go b/vendor/github.com/google/go-github/github/repos_stats.go deleted file mode 100644 index bb355aeadd3..00000000000 --- a/vendor/github.com/google/go-github/github/repos_stats.go +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// ContributorStats represents a contributor to a repository and their -// weekly contributions to a given repo. -type ContributorStats struct { - Author *Contributor `json:"author,omitempty"` - Total *int `json:"total,omitempty"` - Weeks []WeeklyStats `json:"weeks,omitempty"` -} - -func (c ContributorStats) String() string { - return Stringify(c) -} - -// WeeklyStats represents the number of additions, deletions and commits -// a Contributor made in a given week. -type WeeklyStats struct { - Week *Timestamp `json:"w,omitempty"` - Additions *int `json:"a,omitempty"` - Deletions *int `json:"d,omitempty"` - Commits *int `json:"c,omitempty"` -} - -func (w WeeklyStats) String() string { - return Stringify(w) -} - -// ListContributorsStats gets a repo's contributor list with additions, -// deletions and commit counts. -// -// If this is the first time these statistics are requested for the given -// repository, this method will return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it is now computing the requested statistics. A follow up request, after a -// delay of a second or so, should result in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/statistics/#contributors -func (s *RepositoriesService) ListContributorsStats(ctx context.Context, owner, repo string) ([]*ContributorStats, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/stats/contributors", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var contributorStats []*ContributorStats - resp, err := s.client.Do(ctx, req, &contributorStats) - if err != nil { - return nil, resp, err - } - - return contributorStats, resp, nil -} - -// WeeklyCommitActivity represents the weekly commit activity for a repository. -// The days array is a group of commits per day, starting on Sunday. -type WeeklyCommitActivity struct { - Days []int `json:"days,omitempty"` - Total *int `json:"total,omitempty"` - Week *Timestamp `json:"week,omitempty"` -} - -func (w WeeklyCommitActivity) String() string { - return Stringify(w) -} - -// ListCommitActivity returns the last year of commit activity -// grouped by week. The days array is a group of commits per day, -// starting on Sunday. -// -// If this is the first time these statistics are requested for the given -// repository, this method will return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it is now computing the requested statistics. A follow up request, after a -// delay of a second or so, should result in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/statistics/#commit-activity -func (s *RepositoriesService) ListCommitActivity(ctx context.Context, owner, repo string) ([]*WeeklyCommitActivity, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/stats/commit_activity", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var weeklyCommitActivity []*WeeklyCommitActivity - resp, err := s.client.Do(ctx, req, &weeklyCommitActivity) - if err != nil { - return nil, resp, err - } - - return weeklyCommitActivity, resp, nil -} - -// ListCodeFrequency returns a weekly aggregate of the number of additions and -// deletions pushed to a repository. Returned WeeklyStats will contain -// additions and deletions, but not total commits. -// -// If this is the first time these statistics are requested for the given -// repository, this method will return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it is now computing the requested statistics. A follow up request, after a -// delay of a second or so, should result in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/statistics/#code-frequency -func (s *RepositoriesService) ListCodeFrequency(ctx context.Context, owner, repo string) ([]*WeeklyStats, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/stats/code_frequency", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var weeks [][]int - resp, err := s.client.Do(ctx, req, &weeks) - - // convert int slices into WeeklyStats - var stats []*WeeklyStats - for _, week := range weeks { - if len(week) != 3 { - continue - } - stat := &WeeklyStats{ - Week: &Timestamp{time.Unix(int64(week[0]), 0)}, - Additions: Int(week[1]), - Deletions: Int(week[2]), - } - stats = append(stats, stat) - } - - return stats, resp, err -} - -// RepositoryParticipation is the number of commits by everyone -// who has contributed to the repository (including the owner) -// as well as the number of commits by the owner themself. -type RepositoryParticipation struct { - All []int `json:"all,omitempty"` - Owner []int `json:"owner,omitempty"` -} - -func (r RepositoryParticipation) String() string { - return Stringify(r) -} - -// ListParticipation returns the total commit counts for the 'owner' -// and total commit counts in 'all'. 'all' is everyone combined, -// including the 'owner' in the last 52 weeks. If you’d like to get -// the commit counts for non-owners, you can subtract 'all' from 'owner'. -// -// The array order is oldest week (index 0) to most recent week. -// -// If this is the first time these statistics are requested for the given -// repository, this method will return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it is now computing the requested statistics. A follow up request, after a -// delay of a second or so, should result in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/statistics/#participation -func (s *RepositoriesService) ListParticipation(ctx context.Context, owner, repo string) (*RepositoryParticipation, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/stats/participation", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - participation := new(RepositoryParticipation) - resp, err := s.client.Do(ctx, req, participation) - if err != nil { - return nil, resp, err - } - - return participation, resp, nil -} - -// PunchCard represents the number of commits made during a given hour of a -// day of the week. -type PunchCard struct { - Day *int // Day of the week (0-6: =Sunday - Saturday). - Hour *int // Hour of day (0-23). - Commits *int // Number of commits. -} - -// ListPunchCard returns the number of commits per hour in each day. -// -// If this is the first time these statistics are requested for the given -// repository, this method will return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it is now computing the requested statistics. A follow up request, after a -// delay of a second or so, should result in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/statistics/#punch-card -func (s *RepositoriesService) ListPunchCard(ctx context.Context, owner, repo string) ([]*PunchCard, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/stats/punch_card", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var results [][]int - resp, err := s.client.Do(ctx, req, &results) - - // convert int slices into Punchcards - var cards []*PunchCard - for _, result := range results { - if len(result) != 3 { - continue - } - card := &PunchCard{ - Day: Int(result[0]), - Hour: Int(result[1]), - Commits: Int(result[2]), - } - cards = append(cards, card) - } - - return cards, resp, err -} diff --git a/vendor/github.com/google/go-github/github/repos_statuses.go b/vendor/github.com/google/go-github/github/repos_statuses.go deleted file mode 100644 index f94fdc858b8..00000000000 --- a/vendor/github.com/google/go-github/github/repos_statuses.go +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// RepoStatus represents the status of a repository at a particular reference. -type RepoStatus struct { - ID *int64 `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - - // State is the current state of the repository. Possible values are: - // pending, success, error, or failure. - State *string `json:"state,omitempty"` - - // TargetURL is the URL of the page representing this status. It will be - // linked from the GitHub UI to allow users to see the source of the status. - TargetURL *string `json:"target_url,omitempty"` - - // Description is a short high level summary of the status. - Description *string `json:"description,omitempty"` - - // A string label to differentiate this status from the statuses of other systems. - Context *string `json:"context,omitempty"` - - Creator *User `json:"creator,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` -} - -func (r RepoStatus) String() string { - return Stringify(r) -} - -// ListStatuses lists the statuses of a repository at the specified -// reference. ref can be a SHA, a branch name, or a tag name. -// -// GitHub API docs: https://developer.github.com/v3/repos/statuses/#list-statuses-for-a-specific-ref -func (s *RepositoriesService) ListStatuses(ctx context.Context, owner, repo, ref string, opt *ListOptions) ([]*RepoStatus, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v/statuses", owner, repo, ref) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var statuses []*RepoStatus - resp, err := s.client.Do(ctx, req, &statuses) - if err != nil { - return nil, resp, err - } - - return statuses, resp, nil -} - -// CreateStatus creates a new status for a repository at the specified -// reference. Ref can be a SHA, a branch name, or a tag name. -// -// GitHub API docs: https://developer.github.com/v3/repos/statuses/#create-a-status -func (s *RepositoriesService) CreateStatus(ctx context.Context, owner, repo, ref string, status *RepoStatus) (*RepoStatus, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/statuses/%v", owner, repo, ref) - req, err := s.client.NewRequest("POST", u, status) - if err != nil { - return nil, nil, err - } - - repoStatus := new(RepoStatus) - resp, err := s.client.Do(ctx, req, repoStatus) - if err != nil { - return nil, resp, err - } - - return repoStatus, resp, nil -} - -// CombinedStatus represents the combined status of a repository at a particular reference. -type CombinedStatus struct { - // State is the combined state of the repository. Possible values are: - // failure, pending, or success. - State *string `json:"state,omitempty"` - - Name *string `json:"name,omitempty"` - SHA *string `json:"sha,omitempty"` - TotalCount *int `json:"total_count,omitempty"` - Statuses []RepoStatus `json:"statuses,omitempty"` - - CommitURL *string `json:"commit_url,omitempty"` - RepositoryURL *string `json:"repository_url,omitempty"` -} - -func (s CombinedStatus) String() string { - return Stringify(s) -} - -// GetCombinedStatus returns the combined status of a repository at the specified -// reference. ref can be a SHA, a branch name, or a tag name. -// -// GitHub API docs: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref -func (s *RepositoriesService) GetCombinedStatus(ctx context.Context, owner, repo, ref string, opt *ListOptions) (*CombinedStatus, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v/status", owner, repo, ref) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - status := new(CombinedStatus) - resp, err := s.client.Do(ctx, req, status) - if err != nil { - return nil, resp, err - } - - return status, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_traffic.go b/vendor/github.com/google/go-github/github/repos_traffic.go deleted file mode 100644 index fb1c97648a7..00000000000 --- a/vendor/github.com/google/go-github/github/repos_traffic.go +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// TrafficReferrer represent information about traffic from a referrer . -type TrafficReferrer struct { - Referrer *string `json:"referrer,omitempty"` - Count *int `json:"count,omitempty"` - Uniques *int `json:"uniques,omitempty"` -} - -// TrafficPath represent information about the traffic on a path of the repo. -type TrafficPath struct { - Path *string `json:"path,omitempty"` - Title *string `json:"title,omitempty"` - Count *int `json:"count,omitempty"` - Uniques *int `json:"uniques,omitempty"` -} - -// TrafficData represent information about a specific timestamp in views or clones list. -type TrafficData struct { - Timestamp *Timestamp `json:"timestamp,omitempty"` - Count *int `json:"count,omitempty"` - Uniques *int `json:"uniques,omitempty"` -} - -// TrafficViews represent information about the number of views in the last 14 days. -type TrafficViews struct { - Views []*TrafficData `json:"views,omitempty"` - Count *int `json:"count,omitempty"` - Uniques *int `json:"uniques,omitempty"` -} - -// TrafficClones represent information about the number of clones in the last 14 days. -type TrafficClones struct { - Clones []*TrafficData `json:"clones,omitempty"` - Count *int `json:"count,omitempty"` - Uniques *int `json:"uniques,omitempty"` -} - -// TrafficBreakdownOptions specifies the parameters to methods that support breakdown per day or week. -// Can be one of: day, week. Default: day. -type TrafficBreakdownOptions struct { - Per string `url:"per,omitempty"` -} - -// ListTrafficReferrers list the top 10 referrers over the last 14 days. -// -// GitHub API docs: https://developer.github.com/v3/repos/traffic/#list-referrers -func (s *RepositoriesService) ListTrafficReferrers(ctx context.Context, owner, repo string) ([]*TrafficReferrer, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/traffic/popular/referrers", owner, repo) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var trafficReferrers []*TrafficReferrer - resp, err := s.client.Do(ctx, req, &trafficReferrers) - if err != nil { - return nil, resp, err - } - - return trafficReferrers, resp, nil -} - -// ListTrafficPaths list the top 10 popular content over the last 14 days. -// -// GitHub API docs: https://developer.github.com/v3/repos/traffic/#list-paths -func (s *RepositoriesService) ListTrafficPaths(ctx context.Context, owner, repo string) ([]*TrafficPath, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/traffic/popular/paths", owner, repo) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var paths []*TrafficPath - resp, err := s.client.Do(ctx, req, &paths) - if err != nil { - return nil, resp, err - } - - return paths, resp, nil -} - -// ListTrafficViews get total number of views for the last 14 days and breaks it down either per day or week. -// -// GitHub API docs: https://developer.github.com/v3/repos/traffic/#views -func (s *RepositoriesService) ListTrafficViews(ctx context.Context, owner, repo string, opt *TrafficBreakdownOptions) (*TrafficViews, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/traffic/views", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - trafficViews := new(TrafficViews) - resp, err := s.client.Do(ctx, req, &trafficViews) - if err != nil { - return nil, resp, err - } - - return trafficViews, resp, nil -} - -// ListTrafficClones get total number of clones for the last 14 days and breaks it down either per day or week for the last 14 days. -// -// GitHub API docs: https://developer.github.com/v3/repos/traffic/#views -func (s *RepositoriesService) ListTrafficClones(ctx context.Context, owner, repo string, opt *TrafficBreakdownOptions) (*TrafficClones, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/traffic/clones", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - trafficClones := new(TrafficClones) - resp, err := s.client.Do(ctx, req, &trafficClones) - if err != nil { - return nil, resp, err - } - - return trafficClones, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/search.go b/vendor/github.com/google/go-github/github/search.go deleted file mode 100644 index a5973520208..00000000000 --- a/vendor/github.com/google/go-github/github/search.go +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - - qs "github.com/google/go-querystring/query" -) - -// SearchService provides access to the search related functions -// in the GitHub API. -// -// Each method takes a query string defining the search keywords and any search qualifiers. -// For example, when searching issues, the query "gopher is:issue language:go" will search -// for issues containing the word "gopher" in Go repositories. The method call -// opts := &github.SearchOptions{Sort: "created", Order: "asc"} -// cl.Search.Issues(ctx, "gopher is:issue language:go", opts) -// will search for such issues, sorting by creation date in ascending order -// (i.e., oldest first). -// -// GitHub API docs: https://developer.github.com/v3/search/ -type SearchService service - -// SearchOptions specifies optional parameters to the SearchService methods. -type SearchOptions struct { - // How to sort the search results. Possible values are: - // - for repositories: stars, fork, updated - // - for commits: author-date, committer-date - // - for code: indexed - // - for issues: comments, created, updated - // - for users: followers, repositories, joined - // - // Default is to sort by best match. - Sort string `url:"sort,omitempty"` - - // Sort order if sort parameter is provided. Possible values are: asc, - // desc. Default is desc. - Order string `url:"order,omitempty"` - - // Whether to retrieve text match metadata with a query - TextMatch bool `url:"-"` - - ListOptions -} - -// RepositoriesSearchResult represents the result of a repositories search. -type RepositoriesSearchResult struct { - Total *int `json:"total_count,omitempty"` - IncompleteResults *bool `json:"incomplete_results,omitempty"` - Repositories []Repository `json:"items,omitempty"` -} - -// Repositories searches repositories via various criteria. -// -// GitHub API docs: https://developer.github.com/v3/search/#search-repositories -func (s *SearchService) Repositories(ctx context.Context, query string, opt *SearchOptions) (*RepositoriesSearchResult, *Response, error) { - result := new(RepositoriesSearchResult) - resp, err := s.search(ctx, "repositories", query, opt, result) - return result, resp, err -} - -// CommitsSearchResult represents the result of a commits search. -type CommitsSearchResult struct { - Total *int `json:"total_count,omitempty"` - IncompleteResults *bool `json:"incomplete_results,omitempty"` - Commits []*CommitResult `json:"items,omitempty"` -} - -// CommitResult represents a commit object as returned in commit search endpoint response. -type CommitResult struct { - SHA *string `json:"sha,omitempty"` - Commit *Commit `json:"commit,omitempty"` - Author *User `json:"author,omitempty"` - Committer *User `json:"committer,omitempty"` - Parents []*Commit `json:"parents,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - URL *string `json:"url,omitempty"` - CommentsURL *string `json:"comments_url,omitempty"` - - Repository *Repository `json:"repository,omitempty"` - Score *float64 `json:"score,omitempty"` -} - -// Commits searches commits via various criteria. -// -// GitHub API docs: https://developer.github.com/v3/search/#search-commits -func (s *SearchService) Commits(ctx context.Context, query string, opt *SearchOptions) (*CommitsSearchResult, *Response, error) { - result := new(CommitsSearchResult) - resp, err := s.search(ctx, "commits", query, opt, result) - return result, resp, err -} - -// IssuesSearchResult represents the result of an issues search. -type IssuesSearchResult struct { - Total *int `json:"total_count,omitempty"` - IncompleteResults *bool `json:"incomplete_results,omitempty"` - Issues []Issue `json:"items,omitempty"` -} - -// Issues searches issues via various criteria. -// -// GitHub API docs: https://developer.github.com/v3/search/#search-issues -func (s *SearchService) Issues(ctx context.Context, query string, opt *SearchOptions) (*IssuesSearchResult, *Response, error) { - result := new(IssuesSearchResult) - resp, err := s.search(ctx, "issues", query, opt, result) - return result, resp, err -} - -// UsersSearchResult represents the result of a users search. -type UsersSearchResult struct { - Total *int `json:"total_count,omitempty"` - IncompleteResults *bool `json:"incomplete_results,omitempty"` - Users []User `json:"items,omitempty"` -} - -// Users searches users via various criteria. -// -// GitHub API docs: https://developer.github.com/v3/search/#search-users -func (s *SearchService) Users(ctx context.Context, query string, opt *SearchOptions) (*UsersSearchResult, *Response, error) { - result := new(UsersSearchResult) - resp, err := s.search(ctx, "users", query, opt, result) - return result, resp, err -} - -// Match represents a single text match. -type Match struct { - Text *string `json:"text,omitempty"` - Indices []int `json:"indices,omitempty"` -} - -// TextMatch represents a text match for a SearchResult -type TextMatch struct { - ObjectURL *string `json:"object_url,omitempty"` - ObjectType *string `json:"object_type,omitempty"` - Property *string `json:"property,omitempty"` - Fragment *string `json:"fragment,omitempty"` - Matches []Match `json:"matches,omitempty"` -} - -func (tm TextMatch) String() string { - return Stringify(tm) -} - -// CodeSearchResult represents the result of a code search. -type CodeSearchResult struct { - Total *int `json:"total_count,omitempty"` - IncompleteResults *bool `json:"incomplete_results,omitempty"` - CodeResults []CodeResult `json:"items,omitempty"` -} - -// CodeResult represents a single search result. -type CodeResult struct { - Name *string `json:"name,omitempty"` - Path *string `json:"path,omitempty"` - SHA *string `json:"sha,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - Repository *Repository `json:"repository,omitempty"` - TextMatches []TextMatch `json:"text_matches,omitempty"` -} - -func (c CodeResult) String() string { - return Stringify(c) -} - -// Code searches code via various criteria. -// -// GitHub API docs: https://developer.github.com/v3/search/#search-code -func (s *SearchService) Code(ctx context.Context, query string, opt *SearchOptions) (*CodeSearchResult, *Response, error) { - result := new(CodeSearchResult) - resp, err := s.search(ctx, "code", query, opt, result) - return result, resp, err -} - -// Helper function that executes search queries against different -// GitHub search types (repositories, commits, code, issues, users) -func (s *SearchService) search(ctx context.Context, searchType string, query string, opt *SearchOptions, result interface{}) (*Response, error) { - params, err := qs.Values(opt) - if err != nil { - return nil, err - } - params.Set("q", query) - u := fmt.Sprintf("search/%s?%s", searchType, params.Encode()) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, err - } - - switch { - case searchType == "commits": - // Accept header for search commits preview endpoint - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeCommitSearchPreview) - case searchType == "repositories": - // Accept header for search repositories based on topics preview endpoint - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTopicsPreview) - case opt != nil && opt.TextMatch: - // Accept header defaults to "application/vnd.github.v3+json" - // We change it here to fetch back text-match metadata - req.Header.Set("Accept", "application/vnd.github.v3.text-match+json") - } - - return s.client.Do(ctx, req, result) -} diff --git a/vendor/github.com/google/go-github/github/strings.go b/vendor/github.com/google/go-github/github/strings.go deleted file mode 100644 index 431e1cc6c1d..00000000000 --- a/vendor/github.com/google/go-github/github/strings.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "bytes" - "fmt" - "io" - - "reflect" -) - -var timestampType = reflect.TypeOf(Timestamp{}) - -// Stringify attempts to create a reasonable string representation of types in -// the GitHub library. It does things like resolve pointers to their values -// and omits struct fields with nil values. -func Stringify(message interface{}) string { - var buf bytes.Buffer - v := reflect.ValueOf(message) - stringifyValue(&buf, v) - return buf.String() -} - -// stringifyValue was heavily inspired by the goprotobuf library. - -func stringifyValue(w io.Writer, val reflect.Value) { - if val.Kind() == reflect.Ptr && val.IsNil() { - w.Write([]byte("")) - return - } - - v := reflect.Indirect(val) - - switch v.Kind() { - case reflect.String: - fmt.Fprintf(w, `"%s"`, v) - case reflect.Slice: - w.Write([]byte{'['}) - for i := 0; i < v.Len(); i++ { - if i > 0 { - w.Write([]byte{' '}) - } - - stringifyValue(w, v.Index(i)) - } - - w.Write([]byte{']'}) - return - case reflect.Struct: - if v.Type().Name() != "" { - w.Write([]byte(v.Type().String())) - } - - // special handling of Timestamp values - if v.Type() == timestampType { - fmt.Fprintf(w, "{%s}", v.Interface()) - return - } - - w.Write([]byte{'{'}) - - var sep bool - for i := 0; i < v.NumField(); i++ { - fv := v.Field(i) - if fv.Kind() == reflect.Ptr && fv.IsNil() { - continue - } - if fv.Kind() == reflect.Slice && fv.IsNil() { - continue - } - - if sep { - w.Write([]byte(", ")) - } else { - sep = true - } - - w.Write([]byte(v.Type().Field(i).Name)) - w.Write([]byte{':'}) - stringifyValue(w, fv) - } - - w.Write([]byte{'}'}) - default: - if v.CanInterface() { - fmt.Fprint(w, v.Interface()) - } - } -} diff --git a/vendor/github.com/google/go-github/github/timestamp.go b/vendor/github.com/google/go-github/github/timestamp.go deleted file mode 100644 index a1c1554a30e..00000000000 --- a/vendor/github.com/google/go-github/github/timestamp.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "strconv" - "time" -) - -// Timestamp represents a time that can be unmarshalled from a JSON string -// formatted as either an RFC3339 or Unix timestamp. This is necessary for some -// fields since the GitHub API is inconsistent in how it represents times. All -// exported methods of time.Time can be called on Timestamp. -type Timestamp struct { - time.Time -} - -func (t Timestamp) String() string { - return t.Time.String() -} - -// UnmarshalJSON implements the json.Unmarshaler interface. -// Time is expected in RFC3339 or Unix format. -func (t *Timestamp) UnmarshalJSON(data []byte) (err error) { - str := string(data) - i, err := strconv.ParseInt(str, 10, 64) - if err == nil { - (*t).Time = time.Unix(i, 0) - } else { - (*t).Time, err = time.Parse(`"`+time.RFC3339+`"`, str) - } - return -} - -// Equal reports whether t and u are equal based on time.Equal -func (t Timestamp) Equal(u Timestamp) bool { - return t.Time.Equal(u.Time) -} diff --git a/vendor/github.com/google/go-github/github/users.go b/vendor/github.com/google/go-github/github/users.go deleted file mode 100644 index ef8f3dd573a..00000000000 --- a/vendor/github.com/google/go-github/github/users.go +++ /dev/null @@ -1,230 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// UsersService handles communication with the user related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/users/ -type UsersService service - -// User represents a GitHub user. -type User struct { - Login *string `json:"login,omitempty"` - ID *int64 `json:"id,omitempty"` - AvatarURL *string `json:"avatar_url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - GravatarID *string `json:"gravatar_id,omitempty"` - Name *string `json:"name,omitempty"` - Company *string `json:"company,omitempty"` - Blog *string `json:"blog,omitempty"` - Location *string `json:"location,omitempty"` - Email *string `json:"email,omitempty"` - Hireable *bool `json:"hireable,omitempty"` - Bio *string `json:"bio,omitempty"` - PublicRepos *int `json:"public_repos,omitempty"` - PublicGists *int `json:"public_gists,omitempty"` - Followers *int `json:"followers,omitempty"` - Following *int `json:"following,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - SuspendedAt *Timestamp `json:"suspended_at,omitempty"` - Type *string `json:"type,omitempty"` - SiteAdmin *bool `json:"site_admin,omitempty"` - TotalPrivateRepos *int `json:"total_private_repos,omitempty"` - OwnedPrivateRepos *int `json:"owned_private_repos,omitempty"` - PrivateGists *int `json:"private_gists,omitempty"` - DiskUsage *int `json:"disk_usage,omitempty"` - Collaborators *int `json:"collaborators,omitempty"` - Plan *Plan `json:"plan,omitempty"` - - // API URLs - URL *string `json:"url,omitempty"` - EventsURL *string `json:"events_url,omitempty"` - FollowingURL *string `json:"following_url,omitempty"` - FollowersURL *string `json:"followers_url,omitempty"` - GistsURL *string `json:"gists_url,omitempty"` - OrganizationsURL *string `json:"organizations_url,omitempty"` - ReceivedEventsURL *string `json:"received_events_url,omitempty"` - ReposURL *string `json:"repos_url,omitempty"` - StarredURL *string `json:"starred_url,omitempty"` - SubscriptionsURL *string `json:"subscriptions_url,omitempty"` - - // TextMatches is only populated from search results that request text matches - // See: search.go and https://developer.github.com/v3/search/#text-match-metadata - TextMatches []TextMatch `json:"text_matches,omitempty"` - - // Permissions identifies the permissions that a user has on a given - // repository. This is only populated when calling Repositories.ListCollaborators. - Permissions *map[string]bool `json:"permissions,omitempty"` -} - -func (u User) String() string { - return Stringify(u) -} - -// Get fetches a user. Passing the empty string will fetch the authenticated -// user. -// -// GitHub API docs: https://developer.github.com/v3/users/#get-a-single-user -func (s *UsersService) Get(ctx context.Context, user string) (*User, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v", user) - } else { - u = "user" - } - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - uResp := new(User) - resp, err := s.client.Do(ctx, req, uResp) - if err != nil { - return nil, resp, err - } - - return uResp, resp, nil -} - -// GetByID fetches a user. -// -// Note: GetByID uses the undocumented GitHub API endpoint /user/:id. -func (s *UsersService) GetByID(ctx context.Context, id int64) (*User, *Response, error) { - u := fmt.Sprintf("user/%d", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - user := new(User) - resp, err := s.client.Do(ctx, req, user) - if err != nil { - return nil, resp, err - } - - return user, resp, nil -} - -// Edit the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/#update-the-authenticated-user -func (s *UsersService) Edit(ctx context.Context, user *User) (*User, *Response, error) { - u := "user" - req, err := s.client.NewRequest("PATCH", u, user) - if err != nil { - return nil, nil, err - } - - uResp := new(User) - resp, err := s.client.Do(ctx, req, uResp) - if err != nil { - return nil, resp, err - } - - return uResp, resp, nil -} - -// UserListOptions specifies optional parameters to the UsersService.ListAll -// method. -type UserListOptions struct { - // ID of the last user seen - Since int64 `url:"since,omitempty"` - - ListOptions -} - -// ListAll lists all GitHub users. -// -// To paginate through all users, populate 'Since' with the ID of the last user. -// -// GitHub API docs: https://developer.github.com/v3/users/#get-all-users -func (s *UsersService) ListAll(ctx context.Context, opt *UserListOptions) ([]*User, *Response, error) { - u, err := addOptions("users", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var users []*User - resp, err := s.client.Do(ctx, req, &users) - if err != nil { - return nil, resp, err - } - - return users, resp, nil -} - -// ListInvitations lists all currently-open repository invitations for the -// authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/repos/invitations/#list-a-users-repository-invitations -func (s *UsersService) ListInvitations(ctx context.Context, opt *ListOptions) ([]*RepositoryInvitation, *Response, error) { - u, err := addOptions("user/repository_invitations", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - invites := []*RepositoryInvitation{} - resp, err := s.client.Do(ctx, req, &invites) - if err != nil { - return nil, resp, err - } - - return invites, resp, nil -} - -// AcceptInvitation accepts the currently-open repository invitation for the -// authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/repos/invitations/#accept-a-repository-invitation -func (s *UsersService) AcceptInvitation(ctx context.Context, invitationID int64) (*Response, error) { - u := fmt.Sprintf("user/repository_invitations/%v", invitationID) - req, err := s.client.NewRequest("PATCH", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - return s.client.Do(ctx, req, nil) -} - -// DeclineInvitation declines the currently-open repository invitation for the -// authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/repos/invitations/#decline-a-repository-invitation -func (s *UsersService) DeclineInvitation(ctx context.Context, invitationID int64) (*Response, error) { - u := fmt.Sprintf("user/repository_invitations/%v", invitationID) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/users_administration.go b/vendor/github.com/google/go-github/github/users_administration.go deleted file mode 100644 index e042398d8c5..00000000000 --- a/vendor/github.com/google/go-github/github/users_administration.go +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2014 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// PromoteSiteAdmin promotes a user to a site administrator of a GitHub Enterprise instance. -// -// GitHub API docs: https://developer.github.com/v3/users/administration/#promote-an-ordinary-user-to-a-site-administrator -func (s *UsersService) PromoteSiteAdmin(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("users/%v/site_admin", user) - - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// DemoteSiteAdmin demotes a user from site administrator of a GitHub Enterprise instance. -// -// GitHub API docs: https://developer.github.com/v3/users/administration/#demote-a-site-administrator-to-an-ordinary-user -func (s *UsersService) DemoteSiteAdmin(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("users/%v/site_admin", user) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// Suspend a user on a GitHub Enterprise instance. -// -// GitHub API docs: https://developer.github.com/v3/users/administration/#suspend-a-user -func (s *UsersService) Suspend(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("users/%v/suspended", user) - - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// Unsuspend a user on a GitHub Enterprise instance. -// -// GitHub API docs: https://developer.github.com/v3/users/administration/#unsuspend-a-user -func (s *UsersService) Unsuspend(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("users/%v/suspended", user) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/users_blocking.go b/vendor/github.com/google/go-github/github/users_blocking.go deleted file mode 100644 index 39e45601cc1..00000000000 --- a/vendor/github.com/google/go-github/github/users_blocking.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ListBlockedUsers lists all the blocked users by the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/blocking/#list-blocked-users -func (s *UsersService) ListBlockedUsers(ctx context.Context, opt *ListOptions) ([]*User, *Response, error) { - u := "user/blocks" - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - var blockedUsers []*User - resp, err := s.client.Do(ctx, req, &blockedUsers) - if err != nil { - return nil, resp, err - } - - return blockedUsers, resp, nil -} - -// IsBlocked reports whether specified user is blocked by the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/blocking/#check-whether-youve-blocked-a-user -func (s *UsersService) IsBlocked(ctx context.Context, user string) (bool, *Response, error) { - u := fmt.Sprintf("user/blocks/%v", user) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - resp, err := s.client.Do(ctx, req, nil) - isBlocked, err := parseBoolResponse(err) - return isBlocked, resp, err -} - -// BlockUser blocks specified user for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/blocking/#block-a-user -func (s *UsersService) BlockUser(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("user/blocks/%v", user) - - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - return s.client.Do(ctx, req, nil) -} - -// UnblockUser unblocks specified user for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/blocking/#unblock-a-user -func (s *UsersService) UnblockUser(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("user/blocks/%v", user) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/users_emails.go b/vendor/github.com/google/go-github/github/users_emails.go deleted file mode 100644 index 0bbd4627e3b..00000000000 --- a/vendor/github.com/google/go-github/github/users_emails.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import "context" - -// UserEmail represents user's email address -type UserEmail struct { - Email *string `json:"email,omitempty"` - Primary *bool `json:"primary,omitempty"` - Verified *bool `json:"verified,omitempty"` -} - -// ListEmails lists all email addresses for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/emails/#list-email-addresses-for-a-user -func (s *UsersService) ListEmails(ctx context.Context, opt *ListOptions) ([]*UserEmail, *Response, error) { - u := "user/emails" - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var emails []*UserEmail - resp, err := s.client.Do(ctx, req, &emails) - if err != nil { - return nil, resp, err - } - - return emails, resp, nil -} - -// AddEmails adds email addresses of the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/emails/#add-email-addresses -func (s *UsersService) AddEmails(ctx context.Context, emails []string) ([]*UserEmail, *Response, error) { - u := "user/emails" - req, err := s.client.NewRequest("POST", u, emails) - if err != nil { - return nil, nil, err - } - - var e []*UserEmail - resp, err := s.client.Do(ctx, req, &e) - if err != nil { - return nil, resp, err - } - - return e, resp, nil -} - -// DeleteEmails deletes email addresses from authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/emails/#delete-email-addresses -func (s *UsersService) DeleteEmails(ctx context.Context, emails []string) (*Response, error) { - u := "user/emails" - req, err := s.client.NewRequest("DELETE", u, emails) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/users_followers.go b/vendor/github.com/google/go-github/github/users_followers.go deleted file mode 100644 index c2224096a62..00000000000 --- a/vendor/github.com/google/go-github/github/users_followers.go +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// ListFollowers lists the followers for a user. Passing the empty string will -// fetch followers for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/followers/#list-followers-of-a-user -func (s *UsersService) ListFollowers(ctx context.Context, user string, opt *ListOptions) ([]*User, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/followers", user) - } else { - u = "user/followers" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var users []*User - resp, err := s.client.Do(ctx, req, &users) - if err != nil { - return nil, resp, err - } - - return users, resp, nil -} - -// ListFollowing lists the people that a user is following. Passing the empty -// string will list people the authenticated user is following. -// -// GitHub API docs: https://developer.github.com/v3/users/followers/#list-users-followed-by-another-user -func (s *UsersService) ListFollowing(ctx context.Context, user string, opt *ListOptions) ([]*User, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/following", user) - } else { - u = "user/following" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var users []*User - resp, err := s.client.Do(ctx, req, &users) - if err != nil { - return nil, resp, err - } - - return users, resp, nil -} - -// IsFollowing checks if "user" is following "target". Passing the empty -// string for "user" will check if the authenticated user is following "target". -// -// GitHub API docs: https://developer.github.com/v3/users/followers/#check-if-you-are-following-a-user -func (s *UsersService) IsFollowing(ctx context.Context, user, target string) (bool, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/following/%v", user, target) - } else { - u = fmt.Sprintf("user/following/%v", target) - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - resp, err := s.client.Do(ctx, req, nil) - following, err := parseBoolResponse(err) - return following, resp, err -} - -// Follow will cause the authenticated user to follow the specified user. -// -// GitHub API docs: https://developer.github.com/v3/users/followers/#follow-a-user -func (s *UsersService) Follow(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("user/following/%v", user) - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// Unfollow will cause the authenticated user to unfollow the specified user. -// -// GitHub API docs: https://developer.github.com/v3/users/followers/#unfollow-a-user -func (s *UsersService) Unfollow(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("user/following/%v", user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/users_gpg_keys.go b/vendor/github.com/google/go-github/github/users_gpg_keys.go deleted file mode 100644 index d8bbc5201f3..00000000000 --- a/vendor/github.com/google/go-github/github/users_gpg_keys.go +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// GPGKey represents a GitHub user's public GPG key used to verify GPG signed commits and tags. -// -// https://developer.github.com/changes/2016-04-04-git-signing-api-preview/ -type GPGKey struct { - ID *int64 `json:"id,omitempty"` - PrimaryKeyID *int64 `json:"primary_key_id,omitempty"` - KeyID *string `json:"key_id,omitempty"` - PublicKey *string `json:"public_key,omitempty"` - Emails []GPGEmail `json:"emails,omitempty"` - Subkeys []GPGKey `json:"subkeys,omitempty"` - CanSign *bool `json:"can_sign,omitempty"` - CanEncryptComms *bool `json:"can_encrypt_comms,omitempty"` - CanEncryptStorage *bool `json:"can_encrypt_storage,omitempty"` - CanCertify *bool `json:"can_certify,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - ExpiresAt *time.Time `json:"expires_at,omitempty"` -} - -// String stringifies a GPGKey. -func (k GPGKey) String() string { - return Stringify(k) -} - -// GPGEmail represents an email address associated to a GPG key. -type GPGEmail struct { - Email *string `json:"email,omitempty"` - Verified *bool `json:"verified,omitempty"` -} - -// ListGPGKeys lists the public GPG keys for a user. Passing the empty -// string will fetch keys for the authenticated user. It requires authentication -// via Basic Auth or via OAuth with at least read:gpg_key scope. -// -// GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#list-gpg-keys-for-a-user -func (s *UsersService) ListGPGKeys(ctx context.Context, user string, opt *ListOptions) ([]*GPGKey, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/gpg_keys", user) - } else { - u = "user/gpg_keys" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - var keys []*GPGKey - resp, err := s.client.Do(ctx, req, &keys) - if err != nil { - return nil, resp, err - } - - return keys, resp, nil -} - -// GetGPGKey gets extended details for a single GPG key. It requires authentication -// via Basic Auth or via OAuth with at least read:gpg_key scope. -// -// GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#get-a-single-gpg-key -func (s *UsersService) GetGPGKey(ctx context.Context, id int64) (*GPGKey, *Response, error) { - u := fmt.Sprintf("user/gpg_keys/%v", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - key := &GPGKey{} - resp, err := s.client.Do(ctx, req, key) - if err != nil { - return nil, resp, err - } - - return key, resp, nil -} - -// CreateGPGKey creates a GPG key. It requires authenticatation via Basic Auth -// or OAuth with at least write:gpg_key scope. -// -// GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#create-a-gpg-key -func (s *UsersService) CreateGPGKey(ctx context.Context, armoredPublicKey string) (*GPGKey, *Response, error) { - gpgKey := &struct { - ArmoredPublicKey string `json:"armored_public_key"` - }{ArmoredPublicKey: armoredPublicKey} - req, err := s.client.NewRequest("POST", "user/gpg_keys", gpgKey) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - key := &GPGKey{} - resp, err := s.client.Do(ctx, req, key) - if err != nil { - return nil, resp, err - } - - return key, resp, nil -} - -// DeleteGPGKey deletes a GPG key. It requires authentication via Basic Auth or -// via OAuth with at least admin:gpg_key scope. -// -// GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#delete-a-gpg-key -func (s *UsersService) DeleteGPGKey(ctx context.Context, id int64) (*Response, error) { - u := fmt.Sprintf("user/gpg_keys/%v", id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/users_keys.go b/vendor/github.com/google/go-github/github/users_keys.go deleted file mode 100644 index ddc832a1ece..00000000000 --- a/vendor/github.com/google/go-github/github/users_keys.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" -) - -// Key represents a public SSH key used to authenticate a user or deploy script. -type Key struct { - ID *int64 `json:"id,omitempty"` - Key *string `json:"key,omitempty"` - URL *string `json:"url,omitempty"` - Title *string `json:"title,omitempty"` - ReadOnly *bool `json:"read_only,omitempty"` -} - -func (k Key) String() string { - return Stringify(k) -} - -// ListKeys lists the verified public keys for a user. Passing the empty -// string will fetch keys for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/keys/#list-public-keys-for-a-user -func (s *UsersService) ListKeys(ctx context.Context, user string, opt *ListOptions) ([]*Key, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/keys", user) - } else { - u = "user/keys" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var keys []*Key - resp, err := s.client.Do(ctx, req, &keys) - if err != nil { - return nil, resp, err - } - - return keys, resp, nil -} - -// GetKey fetches a single public key. -// -// GitHub API docs: https://developer.github.com/v3/users/keys/#get-a-single-public-key -func (s *UsersService) GetKey(ctx context.Context, id int64) (*Key, *Response, error) { - u := fmt.Sprintf("user/keys/%v", id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - key := new(Key) - resp, err := s.client.Do(ctx, req, key) - if err != nil { - return nil, resp, err - } - - return key, resp, nil -} - -// CreateKey adds a public key for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/keys/#create-a-public-key -func (s *UsersService) CreateKey(ctx context.Context, key *Key) (*Key, *Response, error) { - u := "user/keys" - - req, err := s.client.NewRequest("POST", u, key) - if err != nil { - return nil, nil, err - } - - k := new(Key) - resp, err := s.client.Do(ctx, req, k) - if err != nil { - return nil, resp, err - } - - return k, resp, nil -} - -// DeleteKey deletes a public key. -// -// GitHub API docs: https://developer.github.com/v3/users/keys/#delete-a-public-key -func (s *UsersService) DeleteKey(ctx context.Context, id int64) (*Response, error) { - u := fmt.Sprintf("user/keys/%v", id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/with_appengine.go b/vendor/github.com/google/go-github/github/with_appengine.go deleted file mode 100644 index 87a228ad7be..00000000000 --- a/vendor/github.com/google/go-github/github/with_appengine.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build appengine - -// This file provides glue for making github work on App Engine. -// In order to get the entire github package to compile with -// Go 1.6, you will need to rewrite all the import "context" lines. -// Fortunately, this is easy with "gofmt": -// -// gofmt -w -r '"context" -> "golang.org/x/net/context"' *.go - -package github - -import ( - "context" - "net/http" -) - -func withContext(ctx context.Context, req *http.Request) *http.Request { - // No-op because App Engine adds context to a request differently. - return req -} diff --git a/vendor/github.com/google/go-github/github/without_appengine.go b/vendor/github.com/google/go-github/github/without_appengine.go deleted file mode 100644 index 6f8fdac5603..00000000000 --- a/vendor/github.com/google/go-github/github/without_appengine.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !appengine - -// This file provides glue for making github work without App Engine. - -package github - -import ( - "context" - "net/http" -) - -func withContext(ctx context.Context, req *http.Request) *http.Request { - return req.WithContext(ctx) -} diff --git a/vendor/github.com/google/go-querystring/LICENSE b/vendor/github.com/google/go-querystring/LICENSE deleted file mode 100644 index ae121a1e46d..00000000000 --- a/vendor/github.com/google/go-querystring/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2013 Google. All rights reserved. - -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. diff --git a/vendor/github.com/google/go-querystring/query/encode.go b/vendor/github.com/google/go-querystring/query/encode.go deleted file mode 100644 index 37080b19b5d..00000000000 --- a/vendor/github.com/google/go-querystring/query/encode.go +++ /dev/null @@ -1,320 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package query implements encoding of structs into URL query parameters. -// -// As a simple example: -// -// type Options struct { -// Query string `url:"q"` -// ShowAll bool `url:"all"` -// Page int `url:"page"` -// } -// -// opt := Options{ "foo", true, 2 } -// v, _ := query.Values(opt) -// fmt.Print(v.Encode()) // will output: "q=foo&all=true&page=2" -// -// The exact mapping between Go values and url.Values is described in the -// documentation for the Values() function. -package query - -import ( - "bytes" - "fmt" - "net/url" - "reflect" - "strconv" - "strings" - "time" -) - -var timeType = reflect.TypeOf(time.Time{}) - -var encoderType = reflect.TypeOf(new(Encoder)).Elem() - -// Encoder is an interface implemented by any type that wishes to encode -// itself into URL values in a non-standard way. -type Encoder interface { - EncodeValues(key string, v *url.Values) error -} - -// Values returns the url.Values encoding of v. -// -// Values expects to be passed a struct, and traverses it recursively using the -// following encoding rules. -// -// Each exported struct field is encoded as a URL parameter unless -// -// - the field's tag is "-", or -// - the field is empty and its tag specifies the "omitempty" option -// -// The empty values are false, 0, any nil pointer or interface value, any array -// slice, map, or string of length zero, and any time.Time that returns true -// for IsZero(). -// -// The URL parameter name defaults to the struct field name but can be -// specified in the struct field's tag value. The "url" key in the struct -// field's tag value is the key name, followed by an optional comma and -// options. For example: -// -// // Field is ignored by this package. -// Field int `url:"-"` -// -// // Field appears as URL parameter "myName". -// Field int `url:"myName"` -// -// // Field appears as URL parameter "myName" and the field is omitted if -// // its value is empty -// Field int `url:"myName,omitempty"` -// -// // Field appears as URL parameter "Field" (the default), but the field -// // is skipped if empty. Note the leading comma. -// Field int `url:",omitempty"` -// -// For encoding individual field values, the following type-dependent rules -// apply: -// -// Boolean values default to encoding as the strings "true" or "false". -// Including the "int" option signals that the field should be encoded as the -// strings "1" or "0". -// -// time.Time values default to encoding as RFC3339 timestamps. Including the -// "unix" option signals that the field should be encoded as a Unix time (see -// time.Unix()) -// -// Slice and Array values default to encoding as multiple URL values of the -// same name. Including the "comma" option signals that the field should be -// encoded as a single comma-delimited value. Including the "space" option -// similarly encodes the value as a single space-delimited string. Including -// the "semicolon" option will encode the value as a semicolon-delimited string. -// Including the "brackets" option signals that the multiple URL values should -// have "[]" appended to the value name. "numbered" will append a number to -// the end of each incidence of the value name, example: -// name0=value0&name1=value1, etc. -// -// Anonymous struct fields are usually encoded as if their inner exported -// fields were fields in the outer struct, subject to the standard Go -// visibility rules. An anonymous struct field with a name given in its URL -// tag is treated as having that name, rather than being anonymous. -// -// Non-nil pointer values are encoded as the value pointed to. -// -// Nested structs are encoded including parent fields in value names for -// scoping. e.g: -// -// "user[name]=acme&user[addr][postcode]=1234&user[addr][city]=SFO" -// -// All other values are encoded using their default string representation. -// -// Multiple fields that encode to the same URL parameter name will be included -// as multiple URL values of the same name. -func Values(v interface{}) (url.Values, error) { - values := make(url.Values) - val := reflect.ValueOf(v) - for val.Kind() == reflect.Ptr { - if val.IsNil() { - return values, nil - } - val = val.Elem() - } - - if v == nil { - return values, nil - } - - if val.Kind() != reflect.Struct { - return nil, fmt.Errorf("query: Values() expects struct input. Got %v", val.Kind()) - } - - err := reflectValue(values, val, "") - return values, err -} - -// reflectValue populates the values parameter from the struct fields in val. -// Embedded structs are followed recursively (using the rules defined in the -// Values function documentation) breadth-first. -func reflectValue(values url.Values, val reflect.Value, scope string) error { - var embedded []reflect.Value - - typ := val.Type() - for i := 0; i < typ.NumField(); i++ { - sf := typ.Field(i) - if sf.PkgPath != "" && !sf.Anonymous { // unexported - continue - } - - sv := val.Field(i) - tag := sf.Tag.Get("url") - if tag == "-" { - continue - } - name, opts := parseTag(tag) - if name == "" { - if sf.Anonymous && sv.Kind() == reflect.Struct { - // save embedded struct for later processing - embedded = append(embedded, sv) - continue - } - - name = sf.Name - } - - if scope != "" { - name = scope + "[" + name + "]" - } - - if opts.Contains("omitempty") && isEmptyValue(sv) { - continue - } - - if sv.Type().Implements(encoderType) { - if !reflect.Indirect(sv).IsValid() { - sv = reflect.New(sv.Type().Elem()) - } - - m := sv.Interface().(Encoder) - if err := m.EncodeValues(name, &values); err != nil { - return err - } - continue - } - - if sv.Kind() == reflect.Slice || sv.Kind() == reflect.Array { - var del byte - if opts.Contains("comma") { - del = ',' - } else if opts.Contains("space") { - del = ' ' - } else if opts.Contains("semicolon") { - del = ';' - } else if opts.Contains("brackets") { - name = name + "[]" - } - - if del != 0 { - s := new(bytes.Buffer) - first := true - for i := 0; i < sv.Len(); i++ { - if first { - first = false - } else { - s.WriteByte(del) - } - s.WriteString(valueString(sv.Index(i), opts)) - } - values.Add(name, s.String()) - } else { - for i := 0; i < sv.Len(); i++ { - k := name - if opts.Contains("numbered") { - k = fmt.Sprintf("%s%d", name, i) - } - values.Add(k, valueString(sv.Index(i), opts)) - } - } - continue - } - - for sv.Kind() == reflect.Ptr { - if sv.IsNil() { - break - } - sv = sv.Elem() - } - - if sv.Type() == timeType { - values.Add(name, valueString(sv, opts)) - continue - } - - if sv.Kind() == reflect.Struct { - reflectValue(values, sv, name) - continue - } - - values.Add(name, valueString(sv, opts)) - } - - for _, f := range embedded { - if err := reflectValue(values, f, scope); err != nil { - return err - } - } - - return nil -} - -// valueString returns the string representation of a value. -func valueString(v reflect.Value, opts tagOptions) string { - for v.Kind() == reflect.Ptr { - if v.IsNil() { - return "" - } - v = v.Elem() - } - - if v.Kind() == reflect.Bool && opts.Contains("int") { - if v.Bool() { - return "1" - } - return "0" - } - - if v.Type() == timeType { - t := v.Interface().(time.Time) - if opts.Contains("unix") { - return strconv.FormatInt(t.Unix(), 10) - } - return t.Format(time.RFC3339) - } - - return fmt.Sprint(v.Interface()) -} - -// isEmptyValue checks if a value should be considered empty for the purposes -// of omitting fields with the "omitempty" option. -func isEmptyValue(v reflect.Value) bool { - switch v.Kind() { - case reflect.Array, reflect.Map, reflect.Slice, reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Ptr: - return v.IsNil() - } - - if v.Type() == timeType { - return v.Interface().(time.Time).IsZero() - } - - return false -} - -// tagOptions is the string following a comma in a struct field's "url" tag, or -// the empty string. It does not include the leading comma. -type tagOptions []string - -// parseTag splits a struct field's url tag into its name and comma-separated -// options. -func parseTag(tag string) (string, tagOptions) { - s := strings.Split(tag, ",") - return s[0], s[1:] -} - -// Contains checks whether the tagOptions contains the specified option. -func (o tagOptions) Contains(option string) bool { - for _, s := range o { - if s == option { - return true - } - } - return false -} diff --git a/vendor/google.golang.org/genproto/LICENSE b/vendor/github.com/google/licenseclassifier/LICENSE similarity index 100% rename from vendor/google.golang.org/genproto/LICENSE rename to vendor/github.com/google/licenseclassifier/LICENSE diff --git a/vendor/github.com/google/licenseclassifier/classifier.go b/vendor/github.com/google/licenseclassifier/classifier.go new file mode 100644 index 00000000000..8d39cafbf73 --- /dev/null +++ b/vendor/github.com/google/licenseclassifier/classifier.go @@ -0,0 +1,429 @@ +// Copyright 2017 Google Inc. +// +// 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 licenseclassifier provides methods to identify the open source +// license that most closely matches an unknown license. +package licenseclassifier + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "fmt" + "html" + "io" + "math" + "regexp" + "sort" + "strings" + "sync" + "unicode" + + "github.com/google/licenseclassifier/stringclassifier" + "github.com/google/licenseclassifier/stringclassifier/searchset" +) + +// DefaultConfidenceThreshold is the minimum confidence percentage we're willing to accept in order +// to say that a match is good. +const DefaultConfidenceThreshold = 0.80 + +var ( + // Normalizers is a list of functions that get applied to the strings + // before they are registered with the string classifier. + Normalizers = []stringclassifier.NormalizeFunc{ + html.UnescapeString, + removeShebangLine, + RemoveNonWords, + NormalizeEquivalentWords, + NormalizePunctuation, + strings.ToLower, + removeIgnorableTexts, + stringclassifier.FlattenWhitespace, + strings.TrimSpace, + } + + // commonLicenseWords are words that are common to all known licenses. + // If an unknown text doesn't have at least one of these, then we can + // ignore it. + commonLicenseWords = []*regexp.Regexp{ + regexp.MustCompile(`(?i)\bcode\b`), + regexp.MustCompile(`(?i)\blicense\b`), + regexp.MustCompile(`(?i)\boriginal\b`), + regexp.MustCompile(`(?i)\brights\b`), + regexp.MustCompile(`(?i)\bsoftware\b`), + regexp.MustCompile(`(?i)\bterms\b`), + regexp.MustCompile(`(?i)\bversion\b`), + regexp.MustCompile(`(?i)\bwork\b`), + } +) + +// License is a classifier pre-loaded with known open source licenses. +type License struct { + c *stringclassifier.Classifier + + // Threshold is the lowest confidence percentage acceptable for the + // classifier. + Threshold float64 +} + +// New creates a license classifier and pre-loads it with known open source licenses. +func New(threshold float64) (*License, error) { + classifier := &License{ + c: stringclassifier.New(threshold, Normalizers...), + Threshold: threshold, + } + if err := classifier.registerLicenses(LicenseArchive); err != nil { + return nil, fmt.Errorf("cannot register licenses: %v", err) + } + return classifier, nil +} + +// NewWithForbiddenLicenses creates a license classifier and pre-loads it with +// known open source licenses which are forbidden. +func NewWithForbiddenLicenses(threshold float64) (*License, error) { + classifier := &License{ + c: stringclassifier.New(threshold, Normalizers...), + Threshold: threshold, + } + if err := classifier.registerLicenses(ForbiddenLicenseArchive); err != nil { + return nil, fmt.Errorf("cannot register licenses: %v", err) + } + return classifier, nil +} + +// WithinConfidenceThreshold returns true if the confidence value is above or +// equal to the confidence threshold. +func (c *License) WithinConfidenceThreshold(conf float64) bool { + return conf > c.Threshold || math.Abs(conf-c.Threshold) < math.SmallestNonzeroFloat64 +} + +// NearestMatch returns the "nearest" match to the given set of known licenses. +// Returned are the name of the license, and a confidence percentage indicating +// how confident the classifier is in the result. +func (c *License) NearestMatch(contents string) *stringclassifier.Match { + if !c.hasCommonLicenseWords(contents) { + return nil + } + m := c.c.NearestMatch(contents) + m.Name = strings.TrimSuffix(m.Name, ".header") + return m +} + +// MultipleMatch matches all licenses within an unknown text. +func (c *License) MultipleMatch(contents string, includeHeaders bool) stringclassifier.Matches { + norm := normalizeText(contents) + if !c.hasCommonLicenseWords(norm) { + return nil + } + + m := make(map[stringclassifier.Match]bool) + var matches stringclassifier.Matches + for _, v := range c.c.MultipleMatch(norm) { + if !c.WithinConfidenceThreshold(v.Confidence) { + continue + } + + if !includeHeaders && strings.HasSuffix(v.Name, ".header") { + continue + } + + v.Name = strings.TrimSuffix(v.Name, ".header") + if re, ok := forbiddenRegexps[v.Name]; ok && !re.MatchString(norm) { + continue + } + if _, ok := m[*v]; !ok { + m[*v] = true + matches = append(matches, v) + } + } + sort.Sort(matches) + return matches +} + +func normalizeText(s string) string { + for _, n := range Normalizers { + s = n(s) + } + return s +} + +// hasCommonLicenseWords returns true if the unknown text has at least one word +// that's common to all licenses. +func (c *License) hasCommonLicenseWords(s string) bool { + for _, re := range commonLicenseWords { + if re.MatchString(s) { + return true + } + } + return false +} + +type archivedValue struct { + name string + normalized string + set *searchset.SearchSet +} + +// registerLicenses loads all known licenses and adds them to c as known values +// for comparison. The allocated space after ingesting the 'licenses.db' +// archive is ~167M. +func (c *License) registerLicenses(archive string) error { + contents, err := ReadLicenseFile(archive) + if err != nil { + return err + } + + reader := bytes.NewReader(contents) + gr, err := gzip.NewReader(reader) + if err != nil { + return err + } + defer gr.Close() + + tr := tar.NewReader(gr) + + var muVals sync.Mutex + var vals []archivedValue + for i := 0; ; i++ { + hdr, err := tr.Next() + if err == io.EOF { + break + } + if err != nil { + return err + } + + name := strings.TrimSuffix(hdr.Name, ".txt") + + // Read normalized value. + var b bytes.Buffer + if _, err := io.Copy(&b, tr); err != nil { + return err + } + normalized := b.String() + b.Reset() + + // Read precomputed hashes. + hdr, err = tr.Next() + if err != nil { + return err + } + + if _, err := io.Copy(&b, tr); err != nil { + return err + } + + var set searchset.SearchSet + searchset.Deserialize(&b, &set) + + muVals.Lock() + vals = append(vals, archivedValue{name, normalized, &set}) + muVals.Unlock() + } + + for _, v := range vals { + if err = c.c.AddPrecomputedValue(v.name, v.normalized, v.set); err != nil { + return err + } + } + return nil +} + +// endOfLicenseText is text commonly associated with the end of a license. We +// can remove text that occurs after it. +var endOfLicenseText = []string{ + "END OF TERMS AND CONDITIONS", +} + +// TrimExtraneousTrailingText removes text after an obvious end of the license +// and does not include substantive text of the license. +func TrimExtraneousTrailingText(s string) string { + for _, e := range endOfLicenseText { + if i := strings.LastIndex(s, e); i != -1 { + return s[:i+len(e)] + } + } + return s +} + +var copyrightRE = regexp.MustCompile(`(?m)(?i:Copyright)\s+(?i:©\s+|\(c\)\s+)?(?:\d{2,4})(?:[-,]\s*\d{2,4})*,?\s*(?i:by)?\s*(.*?(?i:\s+Inc\.)?)[.,]?\s*(?i:All rights reserved\.?)?\s*$`) + +// CopyrightHolder finds a copyright notification, if it exists, and returns +// the copyright holder. +func CopyrightHolder(contents string) string { + matches := copyrightRE.FindStringSubmatch(contents) + if len(matches) == 2 { + return matches[1] + } + return "" +} + +var publicDomainRE = regexp.MustCompile("(?i)(this file )?is( in the)? public domain") + +// HasPublicDomainNotice performs a simple regex over the contents to see if a +// public domain notice is in there. As you can imagine, this isn't 100% +// definitive, but can be useful if a license match isn't found. +func (c *License) HasPublicDomainNotice(contents string) bool { + return publicDomainRE.FindString(contents) != "" +} + +// ignorableTexts is a list of lines at the start of the string we can remove +// to get a cleaner match. +var ignorableTexts = []*regexp.Regexp{ + regexp.MustCompile(`(?i)^(?:the )?mit license(?: \(mit\))?$`), + regexp.MustCompile(`(?i)^(?:new )?bsd license$`), + regexp.MustCompile(`(?i)^copyright and permission notice$`), + regexp.MustCompile(`(?i)^copyright (\(c\) )?(\[yyyy\]|\d{4})[,.]? .*$`), + regexp.MustCompile(`(?i)^(all|some) rights reserved\.?$`), + regexp.MustCompile(`(?i)^@license$`), + regexp.MustCompile(`^\s*$`), +} + +// removeIgnorableTexts removes common text, which is not important for +// classification, that shows up before the body of the license. +func removeIgnorableTexts(s string) string { + lines := strings.Split(strings.TrimRight(s, "\n"), "\n") + var start int + for ; start < len(lines); start++ { + line := strings.TrimSpace(lines[start]) + var matches bool + for _, re := range ignorableTexts { + if re.MatchString(line) { + matches = true + break + } + } + if !matches { + break + } + } + end := len(lines) + if start > end { + return "\n" + } + return strings.Join(lines[start:end], "\n") + "\n" +} + +// removeShebangLine removes the '#!...' line if it's the first line in the +// file. Note that if it's the only line in a comment, it won't be removed. +func removeShebangLine(s string) string { + lines := strings.Split(s, "\n") + if len(lines) <= 1 || !strings.HasPrefix(lines[0], "#!") { + return s + } + + return strings.Join(lines[1:], "\n") +} + +// isDecorative returns true if the line is made up purely of non-letter and +// non-digit characters. +func isDecorative(s string) bool { + for _, c := range s { + if unicode.IsLetter(c) || unicode.IsDigit(c) { + return false + } + } + return true +} + +var nonWords = regexp.MustCompile("[[:punct:]]+") + +// RemoveNonWords removes non-words from the string. +func RemoveNonWords(s string) string { + return nonWords.ReplaceAllString(s, " ") +} + +// interchangeablePunctutation is punctuation that can be normalized. +var interchangeablePunctuation = []struct { + interchangeable *regexp.Regexp + substitute string +}{ + // Hyphen, Dash, En Dash, and Em Dash. + {regexp.MustCompile(`[-‒–—]`), "-"}, + // Single, Double, Curly Single, and Curly Double. + {regexp.MustCompile("['\"`‘’“”]"), "'"}, + // Copyright. + {regexp.MustCompile("©"), "(c)"}, + // Hyphen-separated words. + {regexp.MustCompile(`(\S)-\s+(\S)`), "${1}-${2}"}, + // Currency and Section. (Different copies of the CDDL use each marker.) + {regexp.MustCompile("[§¤]"), "(s)"}, + // Middle Dot + {regexp.MustCompile("·"), "*"}, +} + +// NormalizePunctuation takes all hyphens and quotes and normalizes them. +func NormalizePunctuation(s string) string { + for _, iw := range interchangeablePunctuation { + s = iw.interchangeable.ReplaceAllString(s, iw.substitute) + } + return s +} + +// interchangeableWords are words we can substitute for a normalized form +// without changing the meaning of the license. See +// https://spdx.org/spdx-license-list/matching-guidelines for the list. +var interchangeableWords = []struct { + interchangeable *regexp.Regexp + substitute string +}{ + {regexp.MustCompile("(?i)Acknowledgment"), "Acknowledgement"}, + {regexp.MustCompile("(?i)Analogue"), "Analog"}, + {regexp.MustCompile("(?i)Analyse"), "Analyze"}, + {regexp.MustCompile("(?i)Artefact"), "Artifact"}, + {regexp.MustCompile("(?i)Authorisation"), "Authorization"}, + {regexp.MustCompile("(?i)Authorised"), "Authorized"}, + {regexp.MustCompile("(?i)Calibre"), "Caliber"}, + {regexp.MustCompile("(?i)Cancelled"), "Canceled"}, + {regexp.MustCompile("(?i)Capitalisations"), "Capitalizations"}, + {regexp.MustCompile("(?i)Catalogue"), "Catalog"}, + {regexp.MustCompile("(?i)Categorise"), "Categorize"}, + {regexp.MustCompile("(?i)Centre"), "Center"}, + {regexp.MustCompile("(?i)Emphasised"), "Emphasized"}, + {regexp.MustCompile("(?i)Favour"), "Favor"}, + {regexp.MustCompile("(?i)Favourite"), "Favorite"}, + {regexp.MustCompile("(?i)Fulfil"), "Fulfill"}, + {regexp.MustCompile("(?i)Fulfilment"), "Fulfillment"}, + {regexp.MustCompile("(?i)Initialise"), "Initialize"}, + {regexp.MustCompile("(?i)Judgment"), "Judgement"}, + {regexp.MustCompile("(?i)Labelling"), "Labeling"}, + {regexp.MustCompile("(?i)Labour"), "Labor"}, + {regexp.MustCompile("(?i)Licence"), "License"}, + {regexp.MustCompile("(?i)Maximise"), "Maximize"}, + {regexp.MustCompile("(?i)Modelled"), "Modeled"}, + {regexp.MustCompile("(?i)Modelling"), "Modeling"}, + {regexp.MustCompile("(?i)Offence"), "Offense"}, + {regexp.MustCompile("(?i)Optimise"), "Optimize"}, + {regexp.MustCompile("(?i)Organisation"), "Organization"}, + {regexp.MustCompile("(?i)Organise"), "Organize"}, + {regexp.MustCompile("(?i)Practise"), "Practice"}, + {regexp.MustCompile("(?i)Programme"), "Program"}, + {regexp.MustCompile("(?i)Realise"), "Realize"}, + {regexp.MustCompile("(?i)Recognise"), "Recognize"}, + {regexp.MustCompile("(?i)Signalling"), "Signaling"}, + {regexp.MustCompile("(?i)Sub[- ]license"), "Sublicense"}, + {regexp.MustCompile("(?i)Utilisation"), "Utilization"}, + {regexp.MustCompile("(?i)Whilst"), "While"}, + {regexp.MustCompile("(?i)Wilful"), "Wilfull"}, + {regexp.MustCompile("(?i)Non-commercial"), "Noncommercial"}, + {regexp.MustCompile("(?i)Per cent"), "Percent"}, +} + +// NormalizeEquivalentWords normalizes equivalent words that are interchangeable. +func NormalizeEquivalentWords(s string) string { + for _, iw := range interchangeableWords { + s = iw.interchangeable.ReplaceAllString(s, iw.substitute) + } + return s +} diff --git a/vendor/github.com/google/licenseclassifier/file_system_resources.go b/vendor/github.com/google/licenseclassifier/file_system_resources.go new file mode 100644 index 00000000000..0d92e3aec8d --- /dev/null +++ b/vendor/github.com/google/licenseclassifier/file_system_resources.go @@ -0,0 +1,65 @@ +// Copyright 2017 Google Inc. +// +// 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 licenseclassifier + +import ( + "go/build" + "io/ioutil" + "os" + "path/filepath" +) + +const ( + // LicenseDirectory is the directory where the prototype licenses are kept. + LicenseDirectory = "src/github.com/google/licenseclassifier/licenses" + // LicenseArchive is the name of the archive containing preprocessed + // license texts. + LicenseArchive = "licenses.db" + // ForbiddenLicenseArchive is the name of the archive containing preprocessed + // forbidden license texts only. + ForbiddenLicenseArchive = "forbidden_licenses.db" +) + +func findInGOPATH(rel string) (fullPath string, err error) { + for _, path := range filepath.SplitList(build.Default.GOPATH) { + fullPath := filepath.Join(path, rel) + if _, err := os.Stat(fullPath); err != nil { + if os.IsNotExist(err) { + continue + } + return "", err + } + return fullPath, nil + } + return "", nil +} + +// ReadLicenseFile locates and reads the license file. +func ReadLicenseFile(filename string) ([]byte, error) { + archive, err := findInGOPATH(filepath.Join(LicenseDirectory, filename)) + if err != nil || archive == "" { + return nil, err + } + return ioutil.ReadFile(archive) +} + +// ReadLicenseDir reads directory containing the license files. +func ReadLicenseDir() ([]os.FileInfo, error) { + filename, err := findInGOPATH(filepath.Join(LicenseDirectory, LicenseArchive)) + if err != nil || filename == "" { + return nil, err + } + return ioutil.ReadDir(filepath.Dir(filename)) +} diff --git a/vendor/github.com/google/licenseclassifier/forbidden.go b/vendor/github.com/google/licenseclassifier/forbidden.go new file mode 100644 index 00000000000..6c02ee5d6da --- /dev/null +++ b/vendor/github.com/google/licenseclassifier/forbidden.go @@ -0,0 +1,48 @@ +// Copyright 2017 Google Inc. +// +// 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 licenseclassifier + +import "regexp" + +var ( + reCCBYNC = regexp.MustCompile(`(?i).*\bAttribution NonCommercial\b.*`) + reCCBYNCND = regexp.MustCompile(`(?i).*\bAttribution NonCommercial NoDerivs\b.*`) + reCCBYNCSA = regexp.MustCompile(`(?i).*\bAttribution NonCommercial ShareAlike\b.*`) + + // forbiddenRegexps are regular expressions we expect to find in + // forbidden licenses. If we think we have a forbidden license but + // don't find the equivalent phrase, then it's probably just a + // misclassification. + forbiddenRegexps = map[string]*regexp.Regexp{ + AGPL10: regexp.MustCompile(`(?i).*\bAFFERO GENERAL PUBLIC LICENSE\b.*`), + AGPL30: regexp.MustCompile(`(?i).*\bGNU AFFERO GENERAL PUBLIC LICENSE\b.*`), + CCBYNC10: reCCBYNC, + CCBYNC20: reCCBYNC, + CCBYNC25: reCCBYNC, + CCBYNC30: reCCBYNC, + CCBYNC40: reCCBYNC, + CCBYNCND10: regexp.MustCompile(`(?i).*\bAttribution NoDerivs NonCommercial\b.*`), + CCBYNCND20: reCCBYNCND, + CCBYNCND25: reCCBYNCND, + CCBYNCND30: reCCBYNCND, + CCBYNCND40: regexp.MustCompile(`(?i).*\bAttribution NonCommercial NoDerivatives\b.*`), + CCBYNCSA10: reCCBYNCSA, + CCBYNCSA20: reCCBYNCSA, + CCBYNCSA25: reCCBYNCSA, + CCBYNCSA30: reCCBYNCSA, + CCBYNCSA40: reCCBYNCSA, + WTFPL: regexp.MustCompile(`(?i).*\bDO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE\b.*`), + } +) diff --git a/vendor/go.opencensus.io/plugin/ocgrpc/doc.go b/vendor/github.com/google/licenseclassifier/internal/sets/sets.go similarity index 66% rename from vendor/go.opencensus.io/plugin/ocgrpc/doc.go rename to vendor/github.com/google/licenseclassifier/internal/sets/sets.go index 1370323fb71..f34ae5bf862 100644 --- a/vendor/go.opencensus.io/plugin/ocgrpc/doc.go +++ b/vendor/github.com/google/licenseclassifier/internal/sets/sets.go @@ -1,4 +1,4 @@ -// Copyright 2017, OpenCensus Authors +// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,8 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Package ocgrpc contains OpenCensus stats and trace -// integrations for gRPC. -// -// Use ServerHandler for servers and ClientHandler for clients. -package ocgrpc // import "go.opencensus.io/plugin/ocgrpc" +// Package sets provides sets for storing collections of unique elements. +package sets + +// present is an empty struct used as the "value" in the map[int], since +// empty structs consume zero bytes (unlike 1 unnecessary byte per bool). +type present struct{} diff --git a/vendor/github.com/google/licenseclassifier/internal/sets/stringset.go b/vendor/github.com/google/licenseclassifier/internal/sets/stringset.go new file mode 100644 index 00000000000..54edbd4bfde --- /dev/null +++ b/vendor/github.com/google/licenseclassifier/internal/sets/stringset.go @@ -0,0 +1,228 @@ +// Copyright 2017 Google Inc. +// +// 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 sets + +import ( + "fmt" + "sort" + "strings" +) + +// StringSet stores a set of unique string elements. +type StringSet struct { + set map[string]present +} + +// NewStringSet creates a StringSet containing the supplied initial string elements. +func NewStringSet(elements ...string) *StringSet { + s := &StringSet{} + s.set = make(map[string]present) + s.Insert(elements...) + return s +} + +// Copy returns a newly allocated copy of the supplied StringSet. +func (s *StringSet) Copy() *StringSet { + c := NewStringSet() + if s != nil { + for e := range s.set { + c.set[e] = present{} + } + } + return c +} + +// Insert zero or more string elements into the StringSet. +// As expected for a Set, elements already present in the StringSet are +// simply ignored. +func (s *StringSet) Insert(elements ...string) { + for _, e := range elements { + s.set[e] = present{} + } +} + +// Delete zero or more string elements from the StringSet. +// Any elements not present in the StringSet are simply ignored. +func (s *StringSet) Delete(elements ...string) { + for _, e := range elements { + delete(s.set, e) + } +} + +// Intersect returns a new StringSet containing the intersection of the +// receiver and argument StringSets. Returns an empty set if the argument is nil. +func (s *StringSet) Intersect(other *StringSet) *StringSet { + if other == nil { + return NewStringSet() + } + + // Point a and b to the maps, setting a to the smaller of the two. + a, b := s.set, other.set + if len(b) < len(a) { + a, b = b, a + } + + // Perform the intersection. + intersect := NewStringSet() + for e := range a { + if _, ok := b[e]; ok { + intersect.set[e] = present{} + } + } + return intersect +} + +// Disjoint returns true if the intersection of the receiver and the argument +// StringSets is the empty set. Returns true if the argument is nil or either +// StringSet is the empty set. +func (s *StringSet) Disjoint(other *StringSet) bool { + if other == nil || len(other.set) == 0 || len(s.set) == 0 { + return true + } + + // Point a and b to the maps, setting a to the smaller of the two. + a, b := s.set, other.set + if len(b) < len(a) { + a, b = b, a + } + + // Check for non-empty intersection. + for e := range a { + if _, ok := b[e]; ok { + return false // Early-exit because intersecting. + } + } + return true +} + +// Difference returns a new StringSet containing the elements in the receiver +// that are not present in the argument StringSet. Returns a copy of the +// receiver if the argument is nil. +func (s *StringSet) Difference(other *StringSet) *StringSet { + if other == nil { + return s.Copy() + } + + // Insert only the elements in the receiver that are not present in the + // argument StringSet. + diff := NewStringSet() + for e := range s.set { + if _, ok := other.set[e]; !ok { + diff.set[e] = present{} + } + } + return diff +} + +// Unique returns a new StringSet containing the elements in the receiver +// that are not present in the argument StringSet *and* the elements in the +// argument StringSet that are not in the receiver (which is the union of two +// disjoint sets). Returns a copy of the +// receiver if the argument is nil. +func (s *StringSet) Unique(other *StringSet) *StringSet { + if other == nil { + return s.Copy() + } + + sNotInOther := s.Difference(other) + otherNotInS := other.Difference(s) + + // Duplicate Union implementation here to avoid extra Copy, since both + // sNotInOther and otherNotInS are already copies. + unique := sNotInOther + for e := range otherNotInS.set { + unique.set[e] = present{} + } + return unique +} + +// Equal returns true if the receiver and the argument StringSet contain +// exactly the same elements. +func (s *StringSet) Equal(other *StringSet) bool { + if s == nil || other == nil { + return s == nil && other == nil + } + + // Two sets of different length cannot have the exact same unique elements. + if len(s.set) != len(other.set) { + return false + } + + // Only one loop is needed. If the two sets are known to be of equal + // length, then the two sets are equal only if exactly all of the elements + // in the first set are found in the second. + for e := range s.set { + if _, ok := other.set[e]; !ok { + return false + } + } + + return true +} + +// Union returns a new StringSet containing the union of the receiver and +// argument StringSets. Returns a copy of the receiver if the argument is nil. +func (s *StringSet) Union(other *StringSet) *StringSet { + union := s.Copy() + if other != nil { + for e := range other.set { + union.set[e] = present{} + } + } + return union +} + +// Contains returns true if element is in the StringSet. +func (s *StringSet) Contains(element string) bool { + _, in := s.set[element] + return in +} + +// Len returns the number of unique elements in the StringSet. +func (s *StringSet) Len() int { + return len(s.set) +} + +// Empty returns true if the receiver is the empty set. +func (s *StringSet) Empty() bool { + return len(s.set) == 0 +} + +// Elements returns a []string of the elements in the StringSet, in no +// particular (or consistent) order. +func (s *StringSet) Elements() []string { + elements := []string{} // Return at least an empty slice rather than nil. + for e := range s.set { + elements = append(elements, e) + } + return elements +} + +// Sorted returns a sorted []string of the elements in the StringSet. +func (s *StringSet) Sorted() []string { + elements := s.Elements() + sort.Strings(elements) + return elements +} + +// String formats the StringSet elements as sorted strings, representing them +// in "array initializer" syntax. +func (s *StringSet) String() string { + elements := s.Sorted() + var quoted []string + for _, e := range elements { + quoted = append(quoted, fmt.Sprintf("%q", e)) + } + return fmt.Sprintf("{%s}", strings.Join(quoted, ", ")) +} diff --git a/vendor/github.com/google/licenseclassifier/license_type.go b/vendor/github.com/google/licenseclassifier/license_type.go new file mode 100644 index 00000000000..431e61a2275 --- /dev/null +++ b/vendor/github.com/google/licenseclassifier/license_type.go @@ -0,0 +1,375 @@ +// Copyright 2017 Google Inc. +// +// 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 licenseclassifier + +// *** NOTE: Update this file when adding a new license. You need to: +// +// 1. Add the canonical name to the list, and +// 2. Categorize the license. + +import "github.com/google/licenseclassifier/internal/sets" + +// Canonical names of the licenses. +const ( + // The names come from the https://spdx.org/licenses website, and are + // also the filenames of the licenses in licenseclassifier/licenses. + AFL11 = "AFL-1.1" + AFL12 = "AFL-1.2" + AFL20 = "AFL-2.0" + AFL21 = "AFL-2.1" + AFL30 = "AFL-3.0" + AGPL10 = "AGPL-1.0" + AGPL30 = "AGPL-3.0" + Apache10 = "Apache-1.0" + Apache11 = "Apache-1.1" + Apache20 = "Apache-2.0" + APSL10 = "APSL-1.0" + APSL11 = "APSL-1.1" + APSL12 = "APSL-1.2" + APSL20 = "APSL-2.0" + Artistic10cl8 = "Artistic-1.0-cl8" + Artistic10Perl = "Artistic-1.0-Perl" + Artistic10 = "Artistic-1.0" + Artistic20 = "Artistic-2.0" + BCL = "BCL" + Beerware = "Beerware" + BSD2ClauseFreeBSD = "BSD-2-Clause-FreeBSD" + BSD2ClauseNetBSD = "BSD-2-Clause-NetBSD" + BSD2Clause = "BSD-2-Clause" + BSD3ClauseAttribution = "BSD-3-Clause-Attribution" + BSD3ClauseClear = "BSD-3-Clause-Clear" + BSD3ClauseLBNL = "BSD-3-Clause-LBNL" + BSD3Clause = "BSD-3-Clause" + BSD4Clause = "BSD-4-Clause" + BSD4ClauseUC = "BSD-4-Clause-UC" + BSDProtection = "BSD-Protection" + BSL10 = "BSL-1.0" + CC010 = "CC0-1.0" + CCBY10 = "CC-BY-1.0" + CCBY20 = "CC-BY-2.0" + CCBY25 = "CC-BY-2.5" + CCBY30 = "CC-BY-3.0" + CCBY40 = "CC-BY-4.0" + CCBYNC10 = "CC-BY-NC-1.0" + CCBYNC20 = "CC-BY-NC-2.0" + CCBYNC25 = "CC-BY-NC-2.5" + CCBYNC30 = "CC-BY-NC-3.0" + CCBYNC40 = "CC-BY-NC-4.0" + CCBYNCND10 = "CC-BY-NC-ND-1.0" + CCBYNCND20 = "CC-BY-NC-ND-2.0" + CCBYNCND25 = "CC-BY-NC-ND-2.5" + CCBYNCND30 = "CC-BY-NC-ND-3.0" + CCBYNCND40 = "CC-BY-NC-ND-4.0" + CCBYNCSA10 = "CC-BY-NC-SA-1.0" + CCBYNCSA20 = "CC-BY-NC-SA-2.0" + CCBYNCSA25 = "CC-BY-NC-SA-2.5" + CCBYNCSA30 = "CC-BY-NC-SA-3.0" + CCBYNCSA40 = "CC-BY-NC-SA-4.0" + CCBYND10 = "CC-BY-ND-1.0" + CCBYND20 = "CC-BY-ND-2.0" + CCBYND25 = "CC-BY-ND-2.5" + CCBYND30 = "CC-BY-ND-3.0" + CCBYND40 = "CC-BY-ND-4.0" + CCBYSA10 = "CC-BY-SA-1.0" + CCBYSA20 = "CC-BY-SA-2.0" + CCBYSA25 = "CC-BY-SA-2.5" + CCBYSA30 = "CC-BY-SA-3.0" + CCBYSA40 = "CC-BY-SA-4.0" + CDDL10 = "CDDL-1.0" + CDDL11 = "CDDL-1.1" + CommonsClause = "Commons-Clause" + CPAL10 = "CPAL-1.0" + CPL10 = "CPL-1.0" + eGenix = "eGenix" + EPL10 = "EPL-1.0" + EUPL10 = "EUPL-1.0" + EUPL11 = "EUPL-1.1" + Facebook2Clause = "Facebook-2-Clause" + Facebook3Clause = "Facebook-3-Clause" + FacebookExamples = "Facebook-Examples" + FreeImage = "FreeImage" + FTL = "FTL" + GPL10 = "GPL-1.0" + GPL20 = "GPL-2.0" + GPL20withautoconfexception = "GPL-2.0-with-autoconf-exception" + GPL20withbisonexception = "GPL-2.0-with-bison-exception" + GPL20withclasspathexception = "GPL-2.0-with-classpath-exception" + GPL20withfontexception = "GPL-2.0-with-font-exception" + GPL20withGCCexception = "GPL-2.0-with-GCC-exception" + GPL30 = "GPL-3.0" + GPL30withautoconfexception = "GPL-3.0-with-autoconf-exception" + GPL30withGCCexception = "GPL-3.0-with-GCC-exception" + GUSTFont = "GUST-Font-License" + ImageMagick = "ImageMagick" + IPL10 = "IPL-1.0" + ISC = "ISC" + LGPL20 = "LGPL-2.0" + LGPL21 = "LGPL-2.1" + LGPL30 = "LGPL-3.0" + LGPLLR = "LGPLLR" + Libpng = "Libpng" + Lil10 = "Lil-1.0" + LPL102 = "LPL-1.02" + LPL10 = "LPL-1.0" + LPPL13c = "LPPL-1.3c" + MIT = "MIT" + MPL10 = "MPL-1.0" + MPL11 = "MPL-1.1" + MPL20 = "MPL-2.0" + MSPL = "MS-PL" + NCSA = "NCSA" + NPL10 = "NPL-1.0" + NPL11 = "NPL-1.1" + OFL = "OFL" + OpenSSL = "OpenSSL" + OSL10 = "OSL-1.0" + OSL11 = "OSL-1.1" + OSL20 = "OSL-2.0" + OSL21 = "OSL-2.1" + OSL30 = "OSL-3.0" + PHP301 = "PHP-3.01" + PHP30 = "PHP-3.0" + PIL = "PIL" + Python20complete = "Python-2.0-complete" + Python20 = "Python-2.0" + QPL10 = "QPL-1.0" + Ruby = "Ruby" + SGIB10 = "SGI-B-1.0" + SGIB11 = "SGI-B-1.1" + SGIB20 = "SGI-B-2.0" + SISSL12 = "SISSL-1.2" + SISSL = "SISSL" + Sleepycat = "Sleepycat" + UnicodeTOU = "Unicode-TOU" + Unlicense = "Unlicense" + W3C19980720 = "W3C-19980720" + W3C = "W3C" + WTFPL = "WTFPL" + X11 = "X11" + Xnet = "Xnet" + Zend20 = "Zend-2.0" + ZlibAcknowledgement = "zlib-acknowledgement" + Zlib = "Zlib" + ZPL11 = "ZPL-1.1" + ZPL20 = "ZPL-2.0" + ZPL21 = "ZPL-2.1" +) + +var ( + // Licenses Categorized by Type + + // restricted - Licenses in this category require mandatory source + // distribution if we ships a product that includes third-party code + // protected by such a license. + restrictedType = sets.NewStringSet( + BCL, + CCBYND10, + CCBYND20, + CCBYND25, + CCBYND30, + CCBYND40, + CCBYSA10, + CCBYSA20, + CCBYSA25, + CCBYSA30, + CCBYSA40, + GPL10, + GPL20, + GPL20withautoconfexception, + GPL20withbisonexception, + GPL20withclasspathexception, + GPL20withfontexception, + GPL20withGCCexception, + GPL30, + GPL30withautoconfexception, + GPL30withGCCexception, + LGPL20, + LGPL21, + LGPL30, + NPL10, + NPL11, + OSL10, + OSL11, + OSL20, + OSL21, + OSL30, + QPL10, + Sleepycat, + ) + + // reciprocal - These licenses allow usage of software made available + // under such licenses freely in *unmodified* form. If the third-party + // source code is modified in any way these modifications to the + // original third-party source code must be made available. + reciprocalType = sets.NewStringSet( + APSL10, + APSL11, + APSL12, + APSL20, + CDDL10, + CDDL11, + CPL10, + EPL10, + FreeImage, + IPL10, + MPL10, + MPL11, + MPL20, + Ruby, + ) + + // notice - These licenses contain few restrictions, allowing original + // or modified third-party software to be shipped in any product + // without endangering or encumbering our source code. All of the + // licenses in this category do, however, have an "original Copyright + // notice" or "advertising clause", wherein any external distributions + // must include the notice or clause specified in the license. + noticeType = sets.NewStringSet( + AFL11, + AFL12, + AFL20, + AFL21, + AFL30, + Apache10, + Apache11, + Apache20, + Artistic10cl8, + Artistic10Perl, + Artistic10, + Artistic20, + BSL10, + BSD2ClauseFreeBSD, + BSD2ClauseNetBSD, + BSD2Clause, + BSD3ClauseAttribution, + BSD3ClauseClear, + BSD3ClauseLBNL, + BSD3Clause, + BSD4Clause, + BSD4ClauseUC, + BSDProtection, + CCBY10, + CCBY20, + CCBY25, + CCBY30, + CCBY40, + FTL, + ISC, + ImageMagick, + Libpng, + Lil10, + LPL102, + LPL10, + MSPL, + MIT, + NCSA, + OpenSSL, + PHP301, + PHP30, + PIL, + Python20, + Python20complete, + SGIB10, + SGIB11, + SGIB20, + UnicodeTOU, + W3C19980720, + W3C, + X11, + Xnet, + Zend20, + ZlibAcknowledgement, + Zlib, + ZPL11, + ZPL20, + ZPL21, + ) + + // permissive - These licenses can be used in (relatively rare) cases + // where third-party software is under a license (not "Public Domain" + // or "free for any use" like 'unencumbered') that is even more lenient + // than a 'notice' license. Use the 'permissive' license type when even + // a copyright notice is not required for license compliance. + permissiveType = sets.NewStringSet() + + // unencumbered - Licenses that basically declare that the code is "free for any use". + unencumberedType = sets.NewStringSet( + CC010, + Unlicense, + ) + + // byexceptiononly - Licenses that are incompatible with all (or most) + // uses in combination with our source code. Commercial third-party + // packages that are purchased and licensed only for a specific use + // fall into this category. + byExceptionOnlyType = sets.NewStringSet( + Beerware, + ) + + // forbidden - Licenses that are forbidden to be used. + forbiddenType = sets.NewStringSet( + AGPL10, + AGPL30, + CCBYNC10, + CCBYNC20, + CCBYNC25, + CCBYNC30, + CCBYNC40, + CCBYNCND10, + CCBYNCND20, + CCBYNCND25, + CCBYNCND30, + CCBYNCND40, + CCBYNCSA10, + CCBYNCSA20, + CCBYNCSA25, + CCBYNCSA30, + CCBYNCSA40, + CommonsClause, + Facebook2Clause, + Facebook3Clause, + FacebookExamples, + WTFPL, + ) + + // LicenseTypes is a set of the types of licenses Google recognizes. + LicenseTypes = sets.NewStringSet( + "restricted", + "reciprocal", + "notice", + "permissive", + "unencumbered", + "by_exception_only", + ) +) + +// LicenseType returns the type the license has. +func LicenseType(name string) string { + switch { + case restrictedType.Contains(name): + return "restricted" + case reciprocalType.Contains(name): + return "reciprocal" + case noticeType.Contains(name): + return "notice" + case permissiveType.Contains(name): + return "permissive" + case unencumberedType.Contains(name): + return "unencumbered" + case forbiddenType.Contains(name): + return "FORBIDDEN" + } + return "" +} diff --git a/vendor/github.com/google/licenseclassifier/licenses/Unlicense.txt b/vendor/github.com/google/licenseclassifier/licenses/Unlicense.txt new file mode 100644 index 00000000000..ac8f5f5f15b --- /dev/null +++ b/vendor/github.com/google/licenseclassifier/licenses/Unlicense.txt @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or distribute +this software, either in source code form or as a compiled binary, for any +purpose, commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and + +successors. We intend this dedication to be an overt act of relinquishment in +perpetuity of all present and future rights to this software under copyright +law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to + diff --git a/vendor/github.com/google/licenseclassifier/licenses/licenses.db b/vendor/github.com/google/licenseclassifier/licenses/licenses.db new file mode 100644 index 00000000000..dc66125cd98 Binary files /dev/null and b/vendor/github.com/google/licenseclassifier/licenses/licenses.db differ diff --git a/vendor/google.golang.org/grpc/LICENSE b/vendor/github.com/google/licenseclassifier/stringclassifier/LICENSE similarity index 100% rename from vendor/google.golang.org/grpc/LICENSE rename to vendor/github.com/google/licenseclassifier/stringclassifier/LICENSE diff --git a/vendor/github.com/google/licenseclassifier/stringclassifier/classifier.go b/vendor/github.com/google/licenseclassifier/stringclassifier/classifier.go new file mode 100644 index 00000000000..1bf01e26388 --- /dev/null +++ b/vendor/github.com/google/licenseclassifier/stringclassifier/classifier.go @@ -0,0 +1,560 @@ +// Copyright 2017 Google Inc. +// +// 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 stringclassifier finds the nearest match between a string and a set of known values. It +// uses the Levenshtein Distance (LD) algorithm to determine this. A match with a large LD is less +// likely to be correct than one with a small LD. A confidence percentage is returned, which +// indicates how confident the algorithm is that the match is correct. The higher the percentage, +// the greater the confidence that the match is correct. +// +// Example Usage: +// +// type Text struct { +// Name string +// Text string +// } +// +// func NewClassifier(knownTexts []Text) (*stringclassifier.Classifier, error) { +// sc := stringclassifier.New(stringclassifier.FlattenWhitespace) +// for _, known := range knownTexts { +// if err := sc.AddValue(known.Name, known.Text); err != nil { +// return nil, err +// } +// } +// return sc, nil +// } +// +// func IdentifyTexts(sc *stringclassifier.Classifier, unknownTexts []*Text) { +// for _, unknown := range unknownTexts { +// m := sc.NearestMatch(unknown.Text) +// log.Printf("The nearest match to %q is %q (confidence: %v)", +// unknown.Name, m.Name, m.Confidence) +// } +// } +package stringclassifier + +import ( + "fmt" + "log" + "math" + "regexp" + "sort" + "sync" + + "github.com/google/licenseclassifier/stringclassifier/internal/pq" + "github.com/google/licenseclassifier/stringclassifier/searchset" + "github.com/sergi/go-diff/diffmatchpatch" +) + +// The diff/match/patch algorithm. +var dmp = diffmatchpatch.New() + +const ( + // DefaultConfidenceThreshold is the minimum ratio threshold between + // the matching range and the full source range that we're willing to + // accept in order to say that the matching range will produce a + // sufficiently good edit distance. I.e., if the matching range is + // below this threshold we won't run the Levenshtein Distance algorithm + // on it. + DefaultConfidenceThreshold float64 = 0.80 + + defaultMinDiffRatio float64 = 0.75 +) + +// A Classifier matches a string to a set of known values. +type Classifier struct { + muValues sync.RWMutex + values map[string]*knownValue + normalizers []NormalizeFunc + threshold float64 + + // MinDiffRatio defines the minimum ratio of the length difference + // allowed to consider a known value a possible match. This is used as + // a performance optimization to eliminate values that are unlikely to + // be a match. + // + // For example, a value of 0.75 means that the shorter string must be + // at least 75% the length of the longer string to consider it a + // possible match. + // + // Setting this to 1.0 will require that strings are identical length. + // Setting this to 0 will consider all known values as possible + // matches. + MinDiffRatio float64 +} + +// NormalizeFunc is a function that is used to normalize a string prior to comparison. +type NormalizeFunc func(string) string + +// New creates a new Classifier with the provided NormalizeFuncs. Each +// NormalizeFunc is applied in order to a string before comparison. +func New(threshold float64, funcs ...NormalizeFunc) *Classifier { + return &Classifier{ + values: make(map[string]*knownValue), + normalizers: append([]NormalizeFunc(nil), funcs...), + threshold: threshold, + MinDiffRatio: defaultMinDiffRatio, + } +} + +// knownValue identifies a value in the corpus to match against. +type knownValue struct { + key string + normalizedValue string + reValue *regexp.Regexp + set *searchset.SearchSet +} + +// AddValue adds a known value to be matched against. If a value already exists +// for key, an error is returned. +func (c *Classifier) AddValue(key, value string) error { + c.muValues.Lock() + defer c.muValues.Unlock() + if _, ok := c.values[key]; ok { + return fmt.Errorf("value already registered with key %q", key) + } + norm := c.normalize(value) + c.values[key] = &knownValue{ + key: key, + normalizedValue: norm, + reValue: regexp.MustCompile(norm), + } + return nil +} + +// AddPrecomputedValue adds a known value to be matched against. The value has +// already been normalized and the SearchSet object deserialized, so no +// processing is necessary. +func (c *Classifier) AddPrecomputedValue(key, value string, set *searchset.SearchSet) error { + c.muValues.Lock() + defer c.muValues.Unlock() + if _, ok := c.values[key]; ok { + return fmt.Errorf("value already registered with key %q", key) + } + set.GenerateNodeList() + c.values[key] = &knownValue{ + key: key, + normalizedValue: value, + reValue: regexp.MustCompile(value), + set: set, + } + return nil +} + +// normalize a string by applying each of the registered NormalizeFuncs. +func (c *Classifier) normalize(s string) string { + for _, fn := range c.normalizers { + s = fn(s) + } + return s +} + +// Match identifies the result of matching a string against a knownValue. +type Match struct { + Name string // Name of knownValue that was matched + Confidence float64 // Confidence percentage + Offset int // The offset into the unknown string the match was made + Extent int // The length from the offset into the unknown string +} + +// Matches is a list of Match-es. This is here mainly so that the list can be +// sorted. +type Matches []*Match + +func (m Matches) Len() int { return len(m) } +func (m Matches) Swap(i, j int) { m[i], m[j] = m[j], m[i] } +func (m Matches) Less(i, j int) bool { + if math.Abs(m[j].Confidence-m[i].Confidence) < math.SmallestNonzeroFloat64 { + if m[i].Name == m[j].Name { + if m[i].Offset > m[j].Offset { + return false + } + if m[i].Offset == m[j].Offset { + return m[i].Extent > m[j].Extent + } + return true + } + return m[i].Name < m[j].Name + } + return m[i].Confidence > m[j].Confidence +} + +// Names returns an unsorted slice of the names of the matched licenses. +func (m Matches) Names() []string { + var names []string + for _, n := range m { + names = append(names, n.Name) + } + return names +} + +// uniquify goes through the matches and removes any that are contained within +// one with a higher confidence. This assumes that Matches is sorted. +func (m Matches) uniquify() Matches { + type matchedRange struct { + offset, extent int + } + + var matched []matchedRange + var matches Matches +OUTER: + for _, match := range m { + for _, mr := range matched { + if match.Offset >= mr.offset && match.Offset <= mr.offset+mr.extent { + continue OUTER + } + } + matched = append(matched, matchedRange{match.Offset, match.Extent}) + matches = append(matches, match) + } + + return matches +} + +// NearestMatch returns the name of the known value that most closely matches +// the unknown string and a confidence percentage is returned indicating how +// confident the classifier is in the result. A percentage of "1.0" indicates +// an exact match, while a percentage of "0.0" indicates a complete mismatch. +// +// If the string is equidistant from multiple known values, it is undefined +// which will be returned. +func (c *Classifier) NearestMatch(s string) *Match { + pq := c.nearestMatch(s) + if pq.Len() == 0 { + return &Match{} + } + return pq.Pop().(*Match) +} + +// MultipleMatch tries to determine which known strings are found within an +// unknown string. This differs from "NearestMatch" in that it looks only at +// those areas within the unknown string that are likely to match. A list of +// potential matches are returned. It's up to the caller to determine which +// ones are acceptable. +func (c *Classifier) MultipleMatch(s string) (matches Matches) { + pq := c.multipleMatch(s) + if pq == nil { + return matches + } + + // A map to remove duplicate entries. + m := make(map[Match]bool) + + for pq.Len() != 0 { + v := pq.Pop().(*Match) + if _, ok := m[*v]; !ok { + m[*v] = true + matches = append(matches, v) + } + } + + sort.Sort(matches) + return matches.uniquify() +} + +// possibleMatch identifies a known value and it's diffRatio to a given string. +type possibleMatch struct { + value *knownValue + diffRatio float64 +} + +// likelyMatches is a slice of possibleMatches that can be sorted by their +// diffRatio to a given string, such that the most likely matches (based on +// length) are at the beginning. +type likelyMatches []possibleMatch + +func (m likelyMatches) Len() int { return len(m) } +func (m likelyMatches) Less(i, j int) bool { return m[i].diffRatio > m[j].diffRatio } +func (m likelyMatches) Swap(i, j int) { m[i], m[j] = m[j], m[i] } + +// nearestMatch returns a Queue of values that the unknown string may be. The +// values are compared via their Levenshtein Distance and ranked with the +// nearest match at the beginning. +func (c *Classifier) nearestMatch(unknown string) *pq.Queue { + var mu sync.Mutex // Protect the priority queue. + pq := pq.NewQueue(func(x, y interface{}) bool { + return x.(*Match).Confidence > y.(*Match).Confidence + }, nil) + + unknown = c.normalize(unknown) + if len(unknown) == 0 { + return pq + } + + c.muValues.RLock() + var likely likelyMatches + for _, v := range c.values { + dr := diffRatio(unknown, v.normalizedValue) + if dr < c.MinDiffRatio { + continue + } + if unknown == v.normalizedValue { + // We found an exact match. + pq.Push(&Match{Name: v.key, Confidence: 1.0, Offset: 0, Extent: len(unknown)}) + c.muValues.RUnlock() + return pq + } + likely = append(likely, possibleMatch{value: v, diffRatio: dr}) + } + c.muValues.RUnlock() + sort.Sort(likely) + + var wg sync.WaitGroup + classifyString := func(name, unknown, known string) { + defer wg.Done() + + diffs := dmp.DiffMain(unknown, known, true) + distance := dmp.DiffLevenshtein(diffs) + confidence := confidencePercentage(len(unknown), len(known), distance) + if confidence > 0.0 { + mu.Lock() + pq.Push(&Match{Name: name, Confidence: confidence, Offset: 0, Extent: len(unknown)}) + mu.Unlock() + } + } + + wg.Add(len(likely)) + for _, known := range likely { + go classifyString(known.value.key, unknown, known.value.normalizedValue) + } + wg.Wait() + return pq +} + +// matcher finds all potential matches of "known" in "unknown". The results are +// placed in "queue". +type matcher struct { + unknown *searchset.SearchSet + normUnknown string + threshold float64 + + mu sync.Mutex + queue *pq.Queue +} + +// newMatcher creates a "matcher" object. +func newMatcher(unknown string, threshold float64) *matcher { + return &matcher{ + unknown: searchset.New(unknown, searchset.DefaultGranularity), + normUnknown: unknown, + threshold: threshold, + queue: pq.NewQueue(func(x, y interface{}) bool { + return x.(*Match).Confidence > y.(*Match).Confidence + }, nil), + } +} + +// findMatches takes a known text and finds all potential instances of it in +// the unknown text. The resulting matches can then filtered to determine which +// are the best matches. +func (m *matcher) findMatches(known *knownValue) { + var mrs []searchset.MatchRanges + if all := known.reValue.FindAllStringIndex(m.normUnknown, -1); all != nil { + // We found exact matches. Just use those! + for _, a := range all { + var start, end int + for i, tok := range m.unknown.Tokens { + if tok.Offset == a[0] { + start = i + } else if tok.Offset >= a[len(a)-1]-len(tok.Text) { + end = i + break + } + } + + mrs = append(mrs, searchset.MatchRanges{{ + SrcStart: 0, + SrcEnd: len(known.set.Tokens), + TargetStart: start, + TargetEnd: end + 1, + }}) + } + } else { + // No exact match. Perform a more thorough match. + mrs = searchset.FindPotentialMatches(known.set, m.unknown) + } + + var wg sync.WaitGroup + for _, mr := range mrs { + if !m.withinConfidenceThreshold(known.set, mr) { + continue + } + + wg.Add(1) + go func(mr searchset.MatchRanges) { + start, end := mr.TargetRange(m.unknown) + conf := levDist(m.normUnknown[start:end], known.normalizedValue) + if conf > 0.0 { + m.mu.Lock() + m.queue.Push(&Match{Name: known.key, Confidence: conf, Offset: start, Extent: end - start}) + m.mu.Unlock() + } + wg.Done() + }(mr) + } + wg.Wait() +} + +// withinConfidenceThreshold returns the Confidence we have in the potential +// match. It does this by calculating the ratio of what's matching to the +// original known text. +func (m *matcher) withinConfidenceThreshold(known *searchset.SearchSet, mr searchset.MatchRanges) bool { + return float64(mr.Size())/float64(len(known.Tokens)) >= m.threshold +} + +// multipleMatch returns a Queue of values that might be within the unknown +// string. The values are compared via their Levenshtein Distance and ranked +// with the nearest match at the beginning. +func (c *Classifier) multipleMatch(unknown string) *pq.Queue { + normUnknown := c.normalize(unknown) + if normUnknown == "" { + return nil + } + + m := newMatcher(normUnknown, c.threshold) + + c.muValues.RLock() + var kvals []*knownValue + for _, known := range c.values { + kvals = append(kvals, known) + } + c.muValues.RUnlock() + + var wg sync.WaitGroup + wg.Add(len(kvals)) + for _, known := range kvals { + go func(known *knownValue) { + if known.set == nil { + k := searchset.New(known.normalizedValue, searchset.DefaultGranularity) + c.muValues.Lock() + c.values[known.key].set = k + c.muValues.Unlock() + } + m.findMatches(known) + wg.Done() + }(known) + } + wg.Wait() + return m.queue +} + +// levDist runs the Levenshtein Distance algorithm on the known and unknown +// texts to measure how well they match. +func levDist(unknown, known string) float64 { + if len(known) == 0 || len(unknown) == 0 { + log.Printf("Zero-sized texts in Levenshtein Distance algorithm: known==%d, unknown==%d", len(known), len(unknown)) + return 0.0 + } + + // Calculate the differences between the potentially matching known + // text and the unknown text. + diffs := dmp.DiffMain(unknown, known, false) + end := diffRangeEnd(known, diffs) + + // Now execute the Levenshtein Distance algorithm to see how much it + // does match. + distance := dmp.DiffLevenshtein(diffs[:end]) + return confidencePercentage(unknownTextLength(unknown, diffs), len(known), distance) +} + +// unknownTextLength returns the length of the unknown text based on the diff range. +func unknownTextLength(unknown string, diffs []diffmatchpatch.Diff) int { + last := len(diffs) - 1 + for ; last >= 0; last-- { + if diffs[last].Type == diffmatchpatch.DiffEqual { + break + } + } + ulen := 0 + for i := 0; i < last+1; i++ { + switch diffs[i].Type { + case diffmatchpatch.DiffEqual, diffmatchpatch.DiffDelete: + ulen += len(diffs[i].Text) + } + } + return ulen +} + +// diffRangeEnd returns the end index for the "Diff" objects that constructs +// (or nearly constructs) the "known" value. +func diffRangeEnd(known string, diffs []diffmatchpatch.Diff) (end int) { + var seen string + for end = 0; end < len(diffs); end++ { + if seen == known { + // Once we've constructed the "known" value, then we've + // reached the point in the diff list where more + // "Diff"s would just make the Levenshtein Distance + // less valid. There shouldn't be further "DiffEqual" + // nodes, because there's nothing further to match in + // the "known" text. + break + } + switch diffs[end].Type { + case diffmatchpatch.DiffEqual, diffmatchpatch.DiffInsert: + seen += diffs[end].Text + } + } + return end +} + +// confidencePercentage calculates how confident we are in the result of the +// match. A percentage of "1.0" means an identical match. A confidence of "0.0" +// means a complete mismatch. +func confidencePercentage(ulen, klen, distance int) float64 { + if ulen == 0 && klen == 0 { + return 1.0 + } + if ulen == 0 || klen == 0 || (distance > ulen && distance > klen) { + return 0.0 + } + return 1.0 - float64(distance)/float64(max(ulen, klen)) +} + +// diffRatio calculates the ratio of the length of s1 and s2, returned as a +// percentage of the length of the longer string. E.g., diffLength("abcd", "e") +// would return 0.25 because "e" is 25% of the size of "abcd". Comparing +// strings of equal length will return 1. +func diffRatio(s1, s2 string) float64 { + x, y := len(s1), len(s2) + if x == 0 && y == 0 { + // Both strings are zero length + return 1.0 + } + if x < y { + return float64(x) / float64(y) + } + return float64(y) / float64(x) +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} + +// wsRegexp is a regexp used to identify blocks of whitespace. +var wsRegexp = regexp.MustCompile(`\s+`) + +// FlattenWhitespace will flatten contiguous blocks of whitespace down to a single space. +var FlattenWhitespace NormalizeFunc = func(s string) string { + return wsRegexp.ReplaceAllString(s, " ") +} diff --git a/vendor/github.com/google/licenseclassifier/stringclassifier/internal/pq/priority.go b/vendor/github.com/google/licenseclassifier/stringclassifier/internal/pq/priority.go new file mode 100644 index 00000000000..d1797c7aa77 --- /dev/null +++ b/vendor/github.com/google/licenseclassifier/stringclassifier/internal/pq/priority.go @@ -0,0 +1,111 @@ +// Copyright 2017 Google Inc. +// +// 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 pq provides a priority queue. +package pq + +import "container/heap" + +// NewQueue returns an unbounded priority queue that compares elements using +// less; the minimal element is at the top of the queue. +// +// If setIndex is not nil, the queue calls setIndex to inform each element of +// its position in the queue. If an element's priority changes, its position in +// the queue may be incorrect. Call Fix on the element's index to update the +// queue. Call Remove on the element's index to remove it from the queue. +func NewQueue(less func(x, y interface{}) bool, setIndex func(x interface{}, idx int)) *Queue { + return &Queue{ + heap: pqHeap{ + less: less, + setIndex: setIndex, + }, + } +} + +// Queue is a priority queue that supports updating the priority of an element. +// A Queue must be created with NewQueue. +type Queue struct { + heap pqHeap +} + +// Len returns the number of elements in the queue. +func (pq *Queue) Len() int { + return pq.heap.Len() +} + +// Push adds x to the queue. +func (pq *Queue) Push(x interface{}) { + heap.Push(&pq.heap, x) +} + +// Min returns the minimal element. +// Min panics if the queue is empty. +func (pq *Queue) Min() interface{} { + return pq.heap.a[0] +} + +// Pop removes and returns the minimal element. +// Pop panics if the queue is empty. +func (pq *Queue) Pop() interface{} { + return heap.Pop(&pq.heap) +} + +// Fix adjusts the heap to reflect that the element at index has changed priority. +func (pq *Queue) Fix(index int) { + heap.Fix(&pq.heap, index) +} + +// Remove removes the element at index i from the heap. +func (pq *Queue) Remove(index int) { + heap.Remove(&pq.heap, index) +} + +// pqHeap implements heap.Interface. +type pqHeap struct { + a []interface{} + less func(x, y interface{}) bool + setIndex func(x interface{}, idx int) +} + +func (h pqHeap) Len() int { + return len(h.a) +} + +func (h pqHeap) Less(i, j int) bool { + return h.less(h.a[i], h.a[j]) +} + +func (h pqHeap) Swap(i, j int) { + h.a[i], h.a[j] = h.a[j], h.a[i] + if h.setIndex != nil { + h.setIndex(h.a[i], i) + h.setIndex(h.a[j], j) + } +} + +func (h *pqHeap) Push(x interface{}) { + n := len(h.a) + if h.setIndex != nil { + h.setIndex(x, n) + } + h.a = append(h.a, x) +} + +func (h *pqHeap) Pop() interface{} { + old := h.a + n := len(old) + x := old[n-1] + h.a = old[:n-1] + return x +} diff --git a/vendor/github.com/google/licenseclassifier/stringclassifier/searchset/searchset.go b/vendor/github.com/google/licenseclassifier/stringclassifier/searchset/searchset.go new file mode 100644 index 00000000000..2f443e5e101 --- /dev/null +++ b/vendor/github.com/google/licenseclassifier/stringclassifier/searchset/searchset.go @@ -0,0 +1,491 @@ +// Copyright 2017 Google Inc. +// +// 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 searchset generates hashes for all substrings of a text. Potential +// matches between two SearchSet objects can then be determined quickly. +// Generating the hashes can be expensive, so it's best to perform it once. If +// the text is part of a known corpus, then the SearchSet can be serialized and +// kept in an archive. +// +// Matching occurs by "mapping" ranges from the source text into the target +// text but still retaining the source order: +// +// SOURCE: |-----------------------------| +// +// TARGET: |*****************************************| +// +// MAP SOURCE SECTIONS ONTO TARGET IN SOURCE ORDER: +// +// S: |-[--]-----[---]------[----]------| +// / | \ +// |---| |---------| |-------------| +// T: |*****************************************| +// +// Note that a single source range may match many different ranges in the +// target. The matching algorithm untangles these so that all matched ranges +// are in order with respect to the source ranges. This is especially important +// since the source text may occur more than once in the target text. The +// algorithm finds each potential occurrence of S in T and returns all as +// potential matched ranges. +package searchset + +import ( + "encoding/gob" + "fmt" + "io" + "sort" + + "github.com/google/licenseclassifier/stringclassifier/searchset/tokenizer" +) + +// DefaultGranularity is the minimum size (in words) of the hash chunks. +const DefaultGranularity = 3 + +// SearchSet is a set of substrings that have hashes associated with them, +// making it fast to search for potential matches. +type SearchSet struct { + // Tokens is a tokenized list of the original input string. + Tokens tokenizer.Tokens + // Hashes is a map of checksums to a range of tokens. + Hashes tokenizer.Hash + // Checksums is a list of checksums ordered from longest range to + // shortest. + Checksums []uint32 + // ChecksumRanges are the token ranges for the above checksums. + ChecksumRanges tokenizer.TokenRanges + + nodes []*node +} + +// node consists of a range of tokens along with the checksum for those tokens. +type node struct { + checksum uint32 + tokens *tokenizer.TokenRange +} + +func (n *node) String() string { + return fmt.Sprintf("[%d:%d]", n.tokens.Start, n.tokens.End) +} + +// New creates a new SearchSet object. It generates a hash for each substring of "s". +func New(s string, granularity int) *SearchSet { + toks := tokenizer.Tokenize(s) + + // Start generating hash values for all substrings within the text. + h := make(tokenizer.Hash) + checksums, tokenRanges := toks.GenerateHashes(h, func(a, b int) int { + if a < b { + return a + } + return b + }(len(toks), granularity)) + sset := &SearchSet{ + Tokens: toks, + Hashes: h, + Checksums: checksums, + ChecksumRanges: tokenRanges, + } + sset.GenerateNodeList() + return sset +} + +// GenerateNodeList creates a node list out of the search set. +func (s *SearchSet) GenerateNodeList() { + if len(s.Tokens) == 0 { + return + } + + for i := 0; i < len(s.Checksums); i++ { + s.nodes = append(s.nodes, &node{ + checksum: s.Checksums[i], + tokens: s.ChecksumRanges[i], + }) + } +} + +// Serialize emits the SearchSet out so that it can be recreated at a later +// time. +func (s *SearchSet) Serialize(w io.Writer) error { + return gob.NewEncoder(w).Encode(s) +} + +// Deserialize reads a file with a serialized SearchSet in it and reconstructs it. +func Deserialize(r io.Reader, s *SearchSet) error { + if err := gob.NewDecoder(r).Decode(&s); err != nil { + return err + } + s.GenerateNodeList() + return nil +} + +// MatchRange is the range within the source text that is a match to the range +// in the target text. +type MatchRange struct { + // Offsets into the source tokens. + SrcStart, SrcEnd int + // Offsets into the target tokens. + TargetStart, TargetEnd int +} + +// in returns true if the start and end are enclosed in the match range. +func (m *MatchRange) in(start, end int) bool { + return start >= m.TargetStart && end <= m.TargetEnd +} + +func (m *MatchRange) String() string { + return fmt.Sprintf("[%v, %v)->[%v, %v)", m.SrcStart, m.SrcEnd, m.TargetStart, m.TargetEnd) +} + +// MatchRanges is a list of "MatchRange"s. The ranges are monotonically +// increasing in value and indicate a single potential occurrence of the source +// text in the target text. +type MatchRanges []*MatchRange + +func (m MatchRanges) Len() int { return len(m) } +func (m MatchRanges) Swap(i, j int) { m[i], m[j] = m[j], m[i] } +func (m MatchRanges) Less(i, j int) bool { + if m[i].TargetStart < m[j].TargetStart { + return true + } + return m[i].TargetStart == m[j].TargetStart && m[i].SrcStart < m[j].SrcStart +} + +// TargetRange is the start and stop token offsets into the target text. +func (m MatchRanges) TargetRange(target *SearchSet) (start, end int) { + start = target.Tokens[m[0].TargetStart].Offset + end = target.Tokens[m[len(m)-1].TargetEnd-1].Offset + len(target.Tokens[m[len(m)-1].TargetEnd-1].Text) + return start, end +} + +// Size is the number of source tokens that were matched. +func (m MatchRanges) Size() int { + sum := 0 + for _, mr := range m { + sum += mr.SrcEnd - mr.SrcStart + } + return sum +} + +// FindPotentialMatches returns the ranges in the target (unknown) text that +// are best potential matches to the source (known) text. +func FindPotentialMatches(src, target *SearchSet) []MatchRanges { + matchedRanges := getMatchedRanges(src, target) + if len(matchedRanges) == 0 { + return nil + } + + // Cleanup the matching ranges so that we get the longest contiguous ranges. + for i := 0; i < len(matchedRanges); i++ { + matchedRanges[i] = coalesceMatchRanges(matchedRanges[i]) + } + return matchedRanges +} + +// getMatchedRanges finds the ranges in the target text that match the source +// text. There can be multiple occurrences of the source text within the target +// text. Each separate occurrence is an entry in the returned slice. +func getMatchedRanges(src, target *SearchSet) []MatchRanges { + matched := targetMatchedRanges(src, target) + if len(matched) == 0 { + return nil + } + sort.Sort(matched) + matched = untangleSourceRanges(matched) + matchedRanges := splitRanges(matched) + return mergeConsecutiveRanges(matchedRanges) +} + +func extendsAny(tr tokenizer.TokenRanges, mr []MatchRanges) bool { + if len(mr) == 0 { + return false + } + for _, tv := range tr { + for _, mv := range mr { + if tv.Start >= mv[0].TargetStart && tv.Start <= mv[len(mv)-1].TargetEnd { + return true + } + } + } + return false +} + +// targetMatchedRanges finds matching sequences in target and src ordered by target position +func targetMatchedRanges(src, target *SearchSet) MatchRanges { + if src.nodes == nil { + return nil + } + + var matched MatchRanges + var previous *node + var possible []MatchRanges + for _, tgtNode := range target.nodes { + sr, ok := src.Hashes[tgtNode.checksum] + if !ok || (previous != nil && tgtNode.tokens.Start > previous.tokens.End) || !extendsAny(sr, possible) { + for _, r := range possible { + matched = append(matched, r...) + } + possible = possible[:0] + previous = nil + } + if !ok { + // There isn't a match in the source. + continue + } + + // Maps index within `possible` to the slice of ranges extended by a new range + extended := make(map[int]*MatchRanges) + // Go over the set of source ranges growing lists of `possible` match ranges. + tv := tgtNode.tokens + for _, sv := range sr { + r := &MatchRange{ + SrcStart: sv.Start, + SrcEnd: sv.End, + TargetStart: tv.Start, + TargetEnd: tv.End, + } + found := false + // Grow or extend each abutting `possible` match range. + for i, p := range possible { + last := p[len(p)-1] + if sv.Start >= last.SrcStart && sv.Start <= last.SrcEnd && tv.Start >= last.TargetStart && tv.Start <= last.TargetEnd { + found = true + possible[i] = append(possible[i], r) + extended[i] = &possible[i] + } + } + if !found { + // Did not abut any existing ranges, start a new `possible` match range. + mrs := make(MatchRanges, 0, 2) + mrs = append(mrs, r) + possible = append(possible, mrs) + extended[len(possible)-1] = &possible[len(possible)-1] + } + } + if len(extended) < len(possible) { + // Ranges not extended--add to `matched` if not included in other range. + for i := 0; i < len(possible); { + _, updated := extended[i] + if updated { + i++ // Keep in `possible` and advance to next index. + continue + } + p1 := possible[i] + found := false // whether found as subrange of another `possible` match. + for _, p2 := range extended { + if p1[0].SrcStart >= (*p2)[0].SrcStart && p1[0].TargetStart >= (*p2)[0].TargetStart { + found = true + break + } + } + if !found { + matched = append(matched, p1...) + } // else included in other match. + // Finished -- delete from `possible` and continue from same index. + possible = append(possible[:i], possible[i+1:]...) + } + } + previous = tgtNode + } + // At end of file, terminate all `possible` match ranges. + for i := 0; i < len(possible); i++ { + p1 := possible[i] + found := false // whether found as subrange of another `possible` match. + for j := i + 1; j < len(possible); { + p2 := possible[j] + if p1[0].SrcStart <= p2[0].SrcStart && p1[0].TargetStart <= p2[0].TargetStart { + // Delete later sub-ranges included in this range. + possible = append(possible[:j], possible[j+1:]...) + continue + } + // Skip if subrange of a later range + if p1[0].SrcStart >= p2[0].SrcStart && p1[0].TargetStart >= p2[0].TargetStart { + found = true + } + j++ + } + if !found { + matched = append(matched, p1...) + } + } + return matched +} + +// untangleSourceRanges goes through the ranges and removes any whose source +// ranges are "out of order". A source range is "out of order" if the source +// range is out of sequence with the source ranges before and after it. This +// happens when more than one source range maps to the same target range. +// E.g.: +// +// SrcStart: 20, SrcEnd: 30, TargetStart: 127, TargetEnd: 137 +// 1: SrcStart: 12, SrcEnd: 17, TargetStart: 138, TargetEnd: 143 +// 2: SrcStart: 32, SrcEnd: 37, TargetStart: 138, TargetEnd: 143 +// SrcStart: 38, SrcEnd: 40, TargetStart: 144, TargetEnd: 146 +// +// Here (1) is out of order, because the source range [12, 17) is out of +// sequence with the surrounding source sequences, but [32, 37) is. +func untangleSourceRanges(matched MatchRanges) MatchRanges { + mr := MatchRanges{matched[0]} +NEXT: + for i := 1; i < len(matched); i++ { + if mr[len(mr)-1].TargetStart == matched[i].TargetStart && mr[len(mr)-1].TargetEnd == matched[i].TargetEnd { + // The matched range has already been added. + continue + } + + if i+1 < len(matched) && equalTargetRange(matched[i], matched[i+1]) { + // A sequence of ranges match the same target range. + // Find the first one that has a source range greater + // than the currently matched range. Omit all others. + if matched[i].SrcStart > mr[len(mr)-1].SrcStart { + mr = append(mr, matched[i]) + continue + } + + for j := i + 1; j < len(matched) && equalTargetRange(matched[i], matched[j]); j++ { + // Check subsequent ranges to see if we can + // find one that matches in the correct order. + if matched[j].SrcStart > mr[len(mr)-1].SrcStart { + mr = append(mr, matched[j]) + i = j + continue NEXT + } + } + } + + mr = append(mr, matched[i]) + } + return mr +} + +// equalTargetRange returns true if the two MatchRange's cover the same target range. +func equalTargetRange(this, that *MatchRange) bool { + return this.TargetStart == that.TargetStart && this.TargetEnd == that.TargetEnd +} + +// splitRanges splits the matched ranges so that a single match range has a +// monotonically increasing source range (indicating a single, potential +// instance of the source in the target). +func splitRanges(matched MatchRanges) []MatchRanges { + var matchedRanges []MatchRanges + mr := MatchRanges{matched[0]} + for i := 1; i < len(matched); i++ { + if mr[len(mr)-1].SrcStart > matched[i].SrcStart { + matchedRanges = append(matchedRanges, mr) + mr = MatchRanges{matched[i]} + } else { + mr = append(mr, matched[i]) + } + } + matchedRanges = append(matchedRanges, mr) + return matchedRanges +} + +// mergeConsecutiveRanges goes through the matched ranges and merges +// consecutive ranges. Two ranges are consecutive if the end of the previous +// matched range and beginning of the next matched range overlap. "matched" +// should have 1 or more MatchRanges, each with one or more MatchRange objects. +func mergeConsecutiveRanges(matched []MatchRanges) []MatchRanges { + mr := []MatchRanges{matched[0]} + + // Convenience functions. + prevMatchedRange := func() MatchRanges { + return mr[len(mr)-1] + } + prevMatchedRangeLastElem := func() *MatchRange { + return prevMatchedRange()[len(prevMatchedRange())-1] + } + + // This algorithm compares the start of each MatchRanges object to the + // end of the previous MatchRanges object. If they overlap, then it + // tries to combine them. Note that a 0 offset into a MatchRanges + // object (e.g., matched[i][0]) is its first MatchRange, which + // indicates the start of the whole matched range. +NEXT: + for i := 1; i < len(matched); i++ { + if prevMatchedRangeLastElem().TargetEnd > matched[i][0].TargetStart { + // Consecutive matched ranges overlap. Merge them. + if prevMatchedRangeLastElem().TargetStart < matched[i][0].TargetStart { + // The last element of the previous matched + // range overlaps with the first element of the + // current matched range. Concatenate them. + if prevMatchedRangeLastElem().TargetEnd < matched[i][0].TargetEnd { + prevMatchedRangeLastElem().SrcEnd += matched[i][0].TargetEnd - prevMatchedRangeLastElem().TargetEnd + prevMatchedRangeLastElem().TargetEnd = matched[i][0].TargetEnd + } + mr[len(mr)-1] = append(prevMatchedRange(), matched[i][1:]...) + continue + } + + for j := 1; j < len(matched[i]); j++ { + // Find the positions in the ranges where the + // tail end of the previous matched range + // overlaps with the start of the next matched + // range. + for k := len(prevMatchedRange()) - 1; k > 0; k-- { + if prevMatchedRange()[k].SrcStart < matched[i][j].SrcStart && + prevMatchedRange()[k].TargetStart < matched[i][j].TargetStart { + // Append the next range to the previous range. + if prevMatchedRange()[k].TargetEnd < matched[i][j].TargetStart { + // Coalesce the ranges. + prevMatchedRange()[k].SrcEnd += matched[i][j-1].TargetEnd - prevMatchedRange()[k].TargetEnd + prevMatchedRange()[k].TargetEnd = matched[i][j-1].TargetEnd + } + mr[len(mr)-1] = append(prevMatchedRange()[:k+1], matched[i][j:]...) + continue NEXT + } + } + } + } + mr = append(mr, matched[i]) + } + return mr +} + +// coalesceMatchRanges coalesces overlapping match ranges into a single +// contiguous match range. +func coalesceMatchRanges(matchedRanges MatchRanges) MatchRanges { + coalesced := MatchRanges{matchedRanges[0]} + for i := 1; i < len(matchedRanges); i++ { + c := coalesced[len(coalesced)-1] + mr := matchedRanges[i] + + if mr.SrcStart <= c.SrcEnd && mr.SrcStart >= c.SrcStart { + var se, ts, te int + if mr.SrcEnd > c.SrcEnd { + se = mr.SrcEnd + } else { + se = c.SrcEnd + } + if mr.TargetStart < c.TargetStart { + ts = mr.TargetStart + } else { + ts = c.TargetStart + } + if mr.TargetEnd > c.TargetEnd { + te = mr.TargetEnd + } else { + te = c.TargetEnd + } + coalesced[len(coalesced)-1] = &MatchRange{ + SrcStart: c.SrcStart, + SrcEnd: se, + TargetStart: ts, + TargetEnd: te, + } + } else { + coalesced = append(coalesced, mr) + } + } + return coalesced +} diff --git a/vendor/github.com/google/licenseclassifier/stringclassifier/searchset/tokenizer/tokenizer.go b/vendor/github.com/google/licenseclassifier/stringclassifier/searchset/tokenizer/tokenizer.go new file mode 100644 index 00000000000..0f842d866ef --- /dev/null +++ b/vendor/github.com/google/licenseclassifier/stringclassifier/searchset/tokenizer/tokenizer.go @@ -0,0 +1,175 @@ +// Copyright 2017 Google Inc. +// +// 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 tokenizer converts a text into a stream of tokens. +package tokenizer + +import ( + "bytes" + "fmt" + "hash/crc32" + "sort" + "unicode" + "unicode/utf8" +) + +// Token is a non-whitespace sequence (i.e., word or punctuation) in the +// original string. This is not meant for use outside of this package. +type token struct { + Text string + Offset int +} + +// Tokens is a list of Token objects. +type Tokens []*token + +// newToken creates a new token object with an invalid (negative) offset, which +// will be set before the token's used. +func newToken() *token { + return &token{Offset: -1} +} + +// Tokenize converts a string into a stream of tokens. +func Tokenize(s string) (toks Tokens) { + tok := newToken() + for i := 0; i < len(s); { + r, size := utf8.DecodeRuneInString(s[i:]) + switch { + case unicode.IsSpace(r): + if tok.Offset >= 0 { + toks = append(toks, tok) + tok = newToken() + } + case unicode.IsPunct(r): + if tok.Offset >= 0 { + toks = append(toks, tok) + tok = newToken() + } + toks = append(toks, &token{ + Text: string(r), + Offset: i, + }) + default: + if tok.Offset == -1 { + tok.Offset = i + } + tok.Text += string(r) + } + i += size + } + if tok.Offset != -1 { + // Add any remaining token that wasn't yet included in the list. + toks = append(toks, tok) + } + return toks +} + +// GenerateHashes generates hashes for "size" length substrings. The +// "stringifyTokens" call takes a long time to run, so not all substrings have +// hashes, i.e. we skip some of the smaller substrings. +func (t Tokens) GenerateHashes(h Hash, size int) ([]uint32, TokenRanges) { + if size == 0 { + return nil, nil + } + + var css []uint32 + var tr TokenRanges + for offset := 0; offset+size <= len(t); offset += size / 2 { + var b bytes.Buffer + t.stringifyTokens(&b, offset, size) + cs := crc32.ChecksumIEEE(b.Bytes()) + css = append(css, cs) + tr = append(tr, &TokenRange{offset, offset + size}) + h.add(cs, offset, offset+size) + if size <= 1 { + break + } + } + + return css, tr +} + +// stringifyTokens serializes a sublist of tokens into a bytes buffer. +func (t Tokens) stringifyTokens(b *bytes.Buffer, offset, size int) { + for j := offset; j < offset+size; j++ { + if j != offset { + b.WriteRune(' ') + } + b.WriteString(t[j].Text) + } +} + +// TokenRange indicates the range of tokens that map to a particular checksum. +type TokenRange struct { + Start int + End int +} + +func (t *TokenRange) String() string { + return fmt.Sprintf("[%v, %v)", t.Start, t.End) +} + +// TokenRanges is a list of TokenRange objects. The chance that two different +// strings map to the same checksum is very small, but unfortunately isn't +// zero, so we use this instead of making the assumption that they will all be +// unique. +type TokenRanges []*TokenRange + +func (t TokenRanges) Len() int { return len(t) } +func (t TokenRanges) Swap(i, j int) { t[i], t[j] = t[j], t[i] } +func (t TokenRanges) Less(i, j int) bool { return t[i].Start < t[j].Start } + +// CombineUnique returns the combination of both token ranges with no duplicates. +func (t TokenRanges) CombineUnique(other TokenRanges) TokenRanges { + if len(other) == 0 { + return t + } + if len(t) == 0 { + return other + } + + cu := append(t, other...) + sort.Sort(cu) + + if len(cu) == 0 { + return nil + } + + res := TokenRanges{cu[0]} + for prev, i := cu[0], 1; i < len(cu); i++ { + if prev.Start != cu[i].Start || prev.End != cu[i].End { + res = append(res, cu[i]) + prev = cu[i] + } + } + return res +} + +// Hash is a map of the hashes of a section of text to the token range covering that text. +type Hash map[uint32]TokenRanges + +// add associates a token range, [start, end], to a checksum. +func (h Hash) add(checksum uint32, start, end int) { + ntr := &TokenRange{Start: start, End: end} + if r, ok := h[checksum]; ok { + for _, tr := range r { + if tr.Start == ntr.Start && tr.End == ntr.End { + // The token range already exists at this + // checksum. No need to re-add it. + return + } + } + } + h[checksum] = append(h[checksum], ntr) +} diff --git a/vendor/github.com/googleapis/gax-go/LICENSE b/vendor/github.com/googleapis/gax-go/LICENSE deleted file mode 100644 index 6d16b6578a2..00000000000 --- a/vendor/github.com/googleapis/gax-go/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright 2016, Google Inc. -All rights reserved. -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. diff --git a/vendor/github.com/googleapis/gax-go/call_option.go b/vendor/github.com/googleapis/gax-go/call_option.go deleted file mode 100644 index 7b621643e94..00000000000 --- a/vendor/github.com/googleapis/gax-go/call_option.go +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright 2016, Google Inc. -// All rights reserved. -// -// 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. - -package gax - -import ( - "math/rand" - "time" - - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -// CallOption is an option used by Invoke to control behaviors of RPC calls. -// CallOption works by modifying relevant fields of CallSettings. -type CallOption interface { - // Resolve applies the option by modifying cs. - Resolve(cs *CallSettings) -} - -// Retryer is used by Invoke to determine retry behavior. -type Retryer interface { - // Retry reports whether a request should be retriedand how long to pause before retrying - // if the previous attempt returned with err. Invoke never calls Retry with nil error. - Retry(err error) (pause time.Duration, shouldRetry bool) -} - -type retryerOption func() Retryer - -func (o retryerOption) Resolve(s *CallSettings) { - s.Retry = o -} - -// WithRetry sets CallSettings.Retry to fn. -func WithRetry(fn func() Retryer) CallOption { - return retryerOption(fn) -} - -// OnCodes returns a Retryer that retries if and only if -// the previous attempt returns a GRPC error whose error code is stored in cc. -// Pause times between retries are specified by bo. -// -// bo is only used for its parameters; each Retryer has its own copy. -func OnCodes(cc []codes.Code, bo Backoff) Retryer { - return &boRetryer{ - backoff: bo, - codes: append([]codes.Code(nil), cc...), - } -} - -type boRetryer struct { - backoff Backoff - codes []codes.Code -} - -func (r *boRetryer) Retry(err error) (time.Duration, bool) { - st, ok := status.FromError(err) - if !ok { - return 0, false - } - c := st.Code() - for _, rc := range r.codes { - if c == rc { - return r.backoff.Pause(), true - } - } - return 0, false -} - -// Backoff implements exponential backoff. -// The wait time between retries is a random value between 0 and the "retry envelope". -// The envelope starts at Initial and increases by the factor of Multiplier every retry, -// but is capped at Max. -type Backoff struct { - // Initial is the initial value of the retry envelope, defaults to 1 second. - Initial time.Duration - - // Max is the maximum value of the retry envelope, defaults to 30 seconds. - Max time.Duration - - // Multiplier is the factor by which the retry envelope increases. - // It should be greater than 1 and defaults to 2. - Multiplier float64 - - // cur is the current retry envelope - cur time.Duration -} - -func (bo *Backoff) Pause() time.Duration { - if bo.Initial == 0 { - bo.Initial = time.Second - } - if bo.cur == 0 { - bo.cur = bo.Initial - } - if bo.Max == 0 { - bo.Max = 30 * time.Second - } - if bo.Multiplier < 1 { - bo.Multiplier = 2 - } - // Select a duration between zero and the current max. It might seem counterintuitive to - // have so much jitter, but https://www.awsarchitectureblog.com/2015/03/backoff.html - // argues that that is the best strategy. - d := time.Duration(rand.Int63n(int64(bo.cur))) - bo.cur = time.Duration(float64(bo.cur) * bo.Multiplier) - if bo.cur > bo.Max { - bo.cur = bo.Max - } - return d -} - -type grpcOpt []grpc.CallOption - -func (o grpcOpt) Resolve(s *CallSettings) { - s.GRPC = o -} - -func WithGRPCOptions(opt ...grpc.CallOption) CallOption { - return grpcOpt(append([]grpc.CallOption(nil), opt...)) -} - -type CallSettings struct { - // Retry returns a Retryer to be used to control retry logic of a method call. - // If Retry is nil or the returned Retryer is nil, the call will not be retried. - Retry func() Retryer - - // CallOptions to be forwarded to GRPC. - GRPC []grpc.CallOption -} diff --git a/vendor/github.com/googleapis/gax-go/gax.go b/vendor/github.com/googleapis/gax-go/gax.go deleted file mode 100644 index 5ebedff0d02..00000000000 --- a/vendor/github.com/googleapis/gax-go/gax.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2016, Google Inc. -// All rights reserved. -// -// 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. - -// Package gax contains a set of modules which aid the development of APIs -// for clients and servers based on gRPC and Google API conventions. -// -// Application code will rarely need to use this library directly. -// However, code generated automatically from API definition files can use it -// to simplify code generation and to provide more convenient and idiomatic API surfaces. -// -// This project is currently experimental and not supported. -package gax - -const Version = "0.1.0" diff --git a/vendor/github.com/googleapis/gax-go/header.go b/vendor/github.com/googleapis/gax-go/header.go deleted file mode 100644 index d81455eccd9..00000000000 --- a/vendor/github.com/googleapis/gax-go/header.go +++ /dev/null @@ -1,24 +0,0 @@ -package gax - -import "bytes" - -// XGoogHeader is for use by the Google Cloud Libraries only. -// -// XGoogHeader formats key-value pairs. -// The resulting string is suitable for x-goog-api-client header. -func XGoogHeader(keyval ...string) string { - if len(keyval) == 0 { - return "" - } - if len(keyval)%2 != 0 { - panic("gax.Header: odd argument count") - } - var buf bytes.Buffer - for i := 0; i < len(keyval); i += 2 { - buf.WriteByte(' ') - buf.WriteString(keyval[i]) - buf.WriteByte('/') - buf.WriteString(keyval[i+1]) - } - return buf.String()[1:] -} diff --git a/vendor/github.com/googleapis/gax-go/invoke.go b/vendor/github.com/googleapis/gax-go/invoke.go deleted file mode 100644 index 86049d826f8..00000000000 --- a/vendor/github.com/googleapis/gax-go/invoke.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2016, Google Inc. -// All rights reserved. -// -// 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. - -package gax - -import ( - "time" - - "golang.org/x/net/context" -) - -// A user defined call stub. -type APICall func(context.Context, CallSettings) error - -// Invoke calls the given APICall, -// performing retries as specified by opts, if any. -func Invoke(ctx context.Context, call APICall, opts ...CallOption) error { - var settings CallSettings - for _, opt := range opts { - opt.Resolve(&settings) - } - return invoke(ctx, call, settings, Sleep) -} - -// Sleep is similar to time.Sleep, but it can be interrupted by ctx.Done() closing. -// If interrupted, Sleep returns ctx.Err(). -func Sleep(ctx context.Context, d time.Duration) error { - t := time.NewTimer(d) - select { - case <-ctx.Done(): - t.Stop() - return ctx.Err() - case <-t.C: - return nil - } -} - -type sleeper func(ctx context.Context, d time.Duration) error - -// invoke implements Invoke, taking an additional sleeper argument for testing. -func invoke(ctx context.Context, call APICall, settings CallSettings, sp sleeper) error { - var retryer Retryer - for { - err := call(ctx, settings) - if err == nil { - return nil - } - if settings.Retry == nil { - return err - } - if retryer == nil { - if r := settings.Retry(); r != nil { - retryer = r - } else { - return err - } - } - if d, ok := retryer.Retry(err); !ok { - return err - } else if err = sp(ctx, d); err != nil { - return err - } - } -} diff --git a/vendor/github.com/joho/godotenv/LICENCE b/vendor/github.com/joho/godotenv/LICENCE new file mode 100644 index 00000000000..e7ddd51be90 --- /dev/null +++ b/vendor/github.com/joho/godotenv/LICENCE @@ -0,0 +1,23 @@ +Copyright (c) 2013 John Barton + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/vendor/github.com/joho/godotenv/godotenv.go b/vendor/github.com/joho/godotenv/godotenv.go new file mode 100644 index 00000000000..29b436c77c0 --- /dev/null +++ b/vendor/github.com/joho/godotenv/godotenv.go @@ -0,0 +1,346 @@ +// Package godotenv is a go port of the ruby dotenv library (https://github.com/bkeepers/dotenv) +// +// Examples/readme can be found on the github page at https://github.com/joho/godotenv +// +// The TL;DR is that you make a .env file that looks something like +// +// SOME_ENV_VAR=somevalue +// +// and then in your go code you can call +// +// godotenv.Load() +// +// and all the env vars declared in .env will be available through os.Getenv("SOME_ENV_VAR") +package godotenv + +import ( + "bufio" + "errors" + "fmt" + "io" + "os" + "os/exec" + "regexp" + "sort" + "strings" +) + +const doubleQuoteSpecialChars = "\\\n\r\"!$`" + +// Load will read your env file(s) and load them into ENV for this process. +// +// Call this function as close as possible to the start of your program (ideally in main) +// +// If you call Load without any args it will default to loading .env in the current path +// +// You can otherwise tell it which files to load (there can be more than one) like +// +// godotenv.Load("fileone", "filetwo") +// +// It's important to note that it WILL NOT OVERRIDE an env variable that already exists - consider the .env file to set dev vars or sensible defaults +func Load(filenames ...string) (err error) { + filenames = filenamesOrDefault(filenames) + + for _, filename := range filenames { + err = loadFile(filename, false) + if err != nil { + return // return early on a spazout + } + } + return +} + +// Overload will read your env file(s) and load them into ENV for this process. +// +// Call this function as close as possible to the start of your program (ideally in main) +// +// If you call Overload without any args it will default to loading .env in the current path +// +// You can otherwise tell it which files to load (there can be more than one) like +// +// godotenv.Overload("fileone", "filetwo") +// +// It's important to note this WILL OVERRIDE an env variable that already exists - consider the .env file to forcefilly set all vars. +func Overload(filenames ...string) (err error) { + filenames = filenamesOrDefault(filenames) + + for _, filename := range filenames { + err = loadFile(filename, true) + if err != nil { + return // return early on a spazout + } + } + return +} + +// Read all env (with same file loading semantics as Load) but return values as +// a map rather than automatically writing values into env +func Read(filenames ...string) (envMap map[string]string, err error) { + filenames = filenamesOrDefault(filenames) + envMap = make(map[string]string) + + for _, filename := range filenames { + individualEnvMap, individualErr := readFile(filename) + + if individualErr != nil { + err = individualErr + return // return early on a spazout + } + + for key, value := range individualEnvMap { + envMap[key] = value + } + } + + return +} + +// Parse reads an env file from io.Reader, returning a map of keys and values. +func Parse(r io.Reader) (envMap map[string]string, err error) { + envMap = make(map[string]string) + + var lines []string + scanner := bufio.NewScanner(r) + for scanner.Scan() { + lines = append(lines, scanner.Text()) + } + + if err = scanner.Err(); err != nil { + return + } + + for _, fullLine := range lines { + if !isIgnoredLine(fullLine) { + var key, value string + key, value, err = parseLine(fullLine, envMap) + + if err != nil { + return + } + envMap[key] = value + } + } + return +} + +//Unmarshal reads an env file from a string, returning a map of keys and values. +func Unmarshal(str string) (envMap map[string]string, err error) { + return Parse(strings.NewReader(str)) +} + +// Exec loads env vars from the specified filenames (empty map falls back to default) +// then executes the cmd specified. +// +// Simply hooks up os.Stdin/err/out to the command and calls Run() +// +// If you want more fine grained control over your command it's recommended +// that you use `Load()` or `Read()` and the `os/exec` package yourself. +func Exec(filenames []string, cmd string, cmdArgs []string) error { + Load(filenames...) + + command := exec.Command(cmd, cmdArgs...) + command.Stdin = os.Stdin + command.Stdout = os.Stdout + command.Stderr = os.Stderr + return command.Run() +} + +// Write serializes the given environment and writes it to a file +func Write(envMap map[string]string, filename string) error { + content, error := Marshal(envMap) + if error != nil { + return error + } + file, error := os.Create(filename) + if error != nil { + return error + } + _, err := file.WriteString(content) + return err +} + +// Marshal outputs the given environment as a dotenv-formatted environment file. +// Each line is in the format: KEY="VALUE" where VALUE is backslash-escaped. +func Marshal(envMap map[string]string) (string, error) { + lines := make([]string, 0, len(envMap)) + for k, v := range envMap { + lines = append(lines, fmt.Sprintf(`%s="%s"`, k, doubleQuoteEscape(v))) + } + sort.Strings(lines) + return strings.Join(lines, "\n"), nil +} + +func filenamesOrDefault(filenames []string) []string { + if len(filenames) == 0 { + return []string{".env"} + } + return filenames +} + +func loadFile(filename string, overload bool) error { + envMap, err := readFile(filename) + if err != nil { + return err + } + + currentEnv := map[string]bool{} + rawEnv := os.Environ() + for _, rawEnvLine := range rawEnv { + key := strings.Split(rawEnvLine, "=")[0] + currentEnv[key] = true + } + + for key, value := range envMap { + if !currentEnv[key] || overload { + os.Setenv(key, value) + } + } + + return nil +} + +func readFile(filename string) (envMap map[string]string, err error) { + file, err := os.Open(filename) + if err != nil { + return + } + defer file.Close() + + return Parse(file) +} + +func parseLine(line string, envMap map[string]string) (key string, value string, err error) { + if len(line) == 0 { + err = errors.New("zero length string") + return + } + + // ditch the comments (but keep quoted hashes) + if strings.Contains(line, "#") { + segmentsBetweenHashes := strings.Split(line, "#") + quotesAreOpen := false + var segmentsToKeep []string + for _, segment := range segmentsBetweenHashes { + if strings.Count(segment, "\"") == 1 || strings.Count(segment, "'") == 1 { + if quotesAreOpen { + quotesAreOpen = false + segmentsToKeep = append(segmentsToKeep, segment) + } else { + quotesAreOpen = true + } + } + + if len(segmentsToKeep) == 0 || quotesAreOpen { + segmentsToKeep = append(segmentsToKeep, segment) + } + } + + line = strings.Join(segmentsToKeep, "#") + } + + firstEquals := strings.Index(line, "=") + firstColon := strings.Index(line, ":") + splitString := strings.SplitN(line, "=", 2) + if firstColon != -1 && (firstColon < firstEquals || firstEquals == -1) { + //this is a yaml-style line + splitString = strings.SplitN(line, ":", 2) + } + + if len(splitString) != 2 { + err = errors.New("Can't separate key from value") + return + } + + // Parse the key + key = splitString[0] + if strings.HasPrefix(key, "export") { + key = strings.TrimPrefix(key, "export") + } + key = strings.Trim(key, " ") + + // Parse the value + value = parseValue(splitString[1], envMap) + return +} + +func parseValue(value string, envMap map[string]string) string { + + // trim + value = strings.Trim(value, " ") + + // check if we've got quoted values or possible escapes + if len(value) > 1 { + rs := regexp.MustCompile(`\A'(.*)'\z`) + singleQuotes := rs.FindStringSubmatch(value) + + rd := regexp.MustCompile(`\A"(.*)"\z`) + doubleQuotes := rd.FindStringSubmatch(value) + + if singleQuotes != nil || doubleQuotes != nil { + // pull the quotes off the edges + value = value[1 : len(value)-1] + } + + if doubleQuotes != nil { + // expand newlines + escapeRegex := regexp.MustCompile(`\\.`) + value = escapeRegex.ReplaceAllStringFunc(value, func(match string) string { + c := strings.TrimPrefix(match, `\`) + switch c { + case "n": + return "\n" + case "r": + return "\r" + default: + return match + } + }) + // unescape characters + e := regexp.MustCompile(`\\([^$])`) + value = e.ReplaceAllString(value, "$1") + } + + if singleQuotes == nil { + value = expandVariables(value, envMap) + } + } + + return value +} + +func expandVariables(v string, m map[string]string) string { + r := regexp.MustCompile(`(\\)?(\$)(\()?\{?([A-Z0-9_]+)?\}?`) + + return r.ReplaceAllStringFunc(v, func(s string) string { + submatch := r.FindStringSubmatch(s) + + if submatch == nil { + return s + } + if submatch[1] == "\\" || submatch[2] == "(" { + return submatch[0][1:] + } else if submatch[4] != "" { + return m[submatch[4]] + } + return s + }) +} + +func isIgnoredLine(line string) bool { + trimmedLine := strings.Trim(line, " \n\t") + return len(trimmedLine) == 0 || strings.HasPrefix(trimmedLine, "#") +} + +func doubleQuoteEscape(line string) string { + for _, c := range doubleQuoteSpecialChars { + toReplace := "\\" + string(c) + if c == '\n' { + toReplace = `\n` + } + if c == '\r' { + toReplace = `\r` + } + line = strings.Replace(line, string(c), toReplace, -1) + } + return line +} diff --git a/vendor/github.com/knative/build/AUTHORS b/vendor/github.com/knative/build/AUTHORS index ab85282788a..9c2b57e2ca4 100644 --- a/vendor/github.com/knative/build/AUTHORS +++ b/vendor/github.com/knative/build/AUTHORS @@ -5,3 +5,4 @@ # of contributors, see the revision history in source control. Google LLC Pivotal Software, Inc. +Red Hat, Inc. \ No newline at end of file diff --git a/vendor/github.com/knative/build/cmd/controller/kodata/LICENSE b/vendor/github.com/knative/build/cmd/controller/kodata/LICENSE new file mode 120000 index 00000000000..5853aaea53b --- /dev/null +++ b/vendor/github.com/knative/build/cmd/controller/kodata/LICENSE @@ -0,0 +1 @@ +../../../LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/build/cmd/controller/kodata/VENDOR-LICENSE b/vendor/github.com/knative/build/cmd/controller/kodata/VENDOR-LICENSE new file mode 120000 index 00000000000..3cc89764519 --- /dev/null +++ b/vendor/github.com/knative/build/cmd/controller/kodata/VENDOR-LICENSE @@ -0,0 +1 @@ +../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/build/cmd/creds-init/kodata/LICENSE b/vendor/github.com/knative/build/cmd/creds-init/kodata/LICENSE new file mode 120000 index 00000000000..5853aaea53b --- /dev/null +++ b/vendor/github.com/knative/build/cmd/creds-init/kodata/LICENSE @@ -0,0 +1 @@ +../../../LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/build/cmd/creds-init/kodata/VENDOR-LICENSE b/vendor/github.com/knative/build/cmd/creds-init/kodata/VENDOR-LICENSE new file mode 120000 index 00000000000..3cc89764519 --- /dev/null +++ b/vendor/github.com/knative/build/cmd/creds-init/kodata/VENDOR-LICENSE @@ -0,0 +1 @@ +../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/build/cmd/git-init/kodata/LICENSE b/vendor/github.com/knative/build/cmd/git-init/kodata/LICENSE new file mode 120000 index 00000000000..5853aaea53b --- /dev/null +++ b/vendor/github.com/knative/build/cmd/git-init/kodata/LICENSE @@ -0,0 +1 @@ +../../../LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/build/cmd/git-init/kodata/VENDOR-LICENSE b/vendor/github.com/knative/build/cmd/git-init/kodata/VENDOR-LICENSE new file mode 120000 index 00000000000..3cc89764519 --- /dev/null +++ b/vendor/github.com/knative/build/cmd/git-init/kodata/VENDOR-LICENSE @@ -0,0 +1 @@ +../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/build/cmd/logs/kodata/LICENSE b/vendor/github.com/knative/build/cmd/logs/kodata/LICENSE new file mode 120000 index 00000000000..5853aaea53b --- /dev/null +++ b/vendor/github.com/knative/build/cmd/logs/kodata/LICENSE @@ -0,0 +1 @@ +../../../LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/build/cmd/logs/kodata/VENDOR-LICENSE b/vendor/github.com/knative/build/cmd/logs/kodata/VENDOR-LICENSE new file mode 120000 index 00000000000..3cc89764519 --- /dev/null +++ b/vendor/github.com/knative/build/cmd/logs/kodata/VENDOR-LICENSE @@ -0,0 +1 @@ +../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/build/cmd/nop/kodata/LICENSE b/vendor/github.com/knative/build/cmd/nop/kodata/LICENSE new file mode 120000 index 00000000000..5853aaea53b --- /dev/null +++ b/vendor/github.com/knative/build/cmd/nop/kodata/LICENSE @@ -0,0 +1 @@ +../../../LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/build/cmd/nop/kodata/VENDOR-LICENSE b/vendor/github.com/knative/build/cmd/nop/kodata/VENDOR-LICENSE new file mode 120000 index 00000000000..3cc89764519 --- /dev/null +++ b/vendor/github.com/knative/build/cmd/nop/kodata/VENDOR-LICENSE @@ -0,0 +1 @@ +../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/build/cmd/webhook/kodata/LICENSE b/vendor/github.com/knative/build/cmd/webhook/kodata/LICENSE new file mode 120000 index 00000000000..5853aaea53b --- /dev/null +++ b/vendor/github.com/knative/build/cmd/webhook/kodata/LICENSE @@ -0,0 +1 @@ +../../../LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/build/cmd/webhook/kodata/VENDOR-LICENSE b/vendor/github.com/knative/build/cmd/webhook/kodata/VENDOR-LICENSE new file mode 120000 index 00000000000..3cc89764519 --- /dev/null +++ b/vendor/github.com/knative/build/cmd/webhook/kodata/VENDOR-LICENSE @@ -0,0 +1 @@ +../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/build/config/300-imagecache.yaml b/vendor/github.com/knative/build/config/300-imagecache.yaml new file mode 120000 index 00000000000..f10d6dacf6a --- /dev/null +++ b/vendor/github.com/knative/build/config/300-imagecache.yaml @@ -0,0 +1 @@ +../vendor/github.com/knative/caching/config/image.yaml \ No newline at end of file diff --git a/vendor/github.com/knative/build/pkg/apis/build/register.go b/vendor/github.com/knative/build/pkg/apis/build/register.go index ec8299fe8c2..379817b13ca 100644 --- a/vendor/github.com/knative/build/pkg/apis/build/register.go +++ b/vendor/github.com/knative/build/pkg/apis/build/register.go @@ -16,4 +16,5 @@ limitations under the License. package build +// GroupName is the Kubernetes resource group name for Build types. const GroupName = "build.knative.dev" diff --git a/pkg/apis/feeds/v1alpha1/common_event_source_validation.go b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_defaults.go similarity index 55% rename from pkg/apis/feeds/v1alpha1/common_event_source_validation.go rename to vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_defaults.go index 8499e9f879c..fafe21989ae 100644 --- a/pkg/apis/feeds/v1alpha1/common_event_source_validation.go +++ b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_defaults.go @@ -17,10 +17,26 @@ limitations under the License. package v1alpha1 import ( - "github.com/knative/pkg/apis" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -func (cess *CommonEventSourceSpec) Validate() *apis.FieldError { - // nothing to validate - return nil +// DefaultTimeout is 10min +const DefaultTimeout = 10 * time.Minute + +// SetDefaults for build +func (b *Build) SetDefaults() { + if b == nil { + return + } + if b.Spec.ServiceAccountName == "" { + b.Spec.ServiceAccountName = "default" + } + if b.Spec.Timeout == nil { + b.Spec.Timeout = &metav1.Duration{Duration: DefaultTimeout} + } + if b.Spec.Template != nil && b.Spec.Template.Kind == "" { + b.Spec.Template.Kind = BuildTemplateKind + } } diff --git a/pkg/apis/channels/v1alpha1/subscription_defaults.go b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_template_interface.go similarity index 75% rename from pkg/apis/channels/v1alpha1/subscription_defaults.go rename to vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_template_interface.go index ed8fdf5b16f..a14dba3b734 100644 --- a/pkg/apis/channels/v1alpha1/subscription_defaults.go +++ b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_template_interface.go @@ -16,10 +16,8 @@ limitations under the License. package v1alpha1 -func (s *Subscription) SetDefaults() { - s.Spec.SetDefaults() -} - -func (ss *SubscriptionSpec) SetDefaults() { - // TODO anything? +// BuildTemplateInterface is implemented by BuildTemplate and ClusterBuildTemplate +type BuildTemplateInterface interface { + TemplateSpec() BuildTemplateSpec + Copy() BuildTemplateInterface } diff --git a/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_template_types.go b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_template_types.go index 7d63ea4b722..20d78c03077 100644 --- a/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_template_types.go +++ b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_template_types.go @@ -17,12 +17,20 @@ limitations under the License. package v1alpha1 import ( - "encoding/json" - + "github.com/knative/pkg/apis" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + + "github.com/knative/pkg/kmeta" ) +// Template is an interface for accessing the BuildTemplateSpec +// from various forms of template (namespace-/cluster-scoped). +type Template interface { + TemplateSpec() BuildTemplateSpec +} + // +genclient // +genclient:noStatus // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object @@ -35,6 +43,15 @@ type BuildTemplate struct { Spec BuildTemplateSpec `json:"spec"` } +// Check that our resource implements several interfaces. +var _ kmeta.OwnerRefable = (*BuildTemplate)(nil) +var _ Template = (*BuildTemplate)(nil) +var _ BuildTemplateInterface = (*BuildTemplate)(nil) + +// Check that BuildTemplate may be validated and defaulted. +var _ apis.Validatable = (*BuildTemplate)(nil) +var _ apis.Defaultable = (*BuildTemplate)(nil) + // BuildTemplateSpec is the spec for a BuildTemplate. type BuildTemplateSpec struct { // TODO: Generation does not work correctly with CRD. They are scrubbed @@ -80,6 +97,20 @@ type BuildTemplateList struct { Items []BuildTemplate `json:"items"` } -func (bt *BuildTemplate) GetGeneration() int64 { return bt.Spec.Generation } -func (bt *BuildTemplate) SetGeneration(generation int64) { bt.Spec.Generation = generation } -func (bt *BuildTemplate) GetSpecJSON() ([]byte, error) { return json.Marshal(bt.Spec) } +// TemplateSpec returnes the Spec used by the template +func (bt *BuildTemplate) TemplateSpec() BuildTemplateSpec { + return bt.Spec +} + +// Copy performes a deep copy +func (bt *BuildTemplate) Copy() BuildTemplateInterface { + return bt.DeepCopy() +} + +// GetGroupVersionKind gives kind +func (bt *BuildTemplate) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("BuildTemplate") +} + +// SetDefaults for build template +func (bt *BuildTemplate) SetDefaults() {} diff --git a/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_template_validation.go b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_template_validation.go new file mode 100644 index 00000000000..cd3464c1fbe --- /dev/null +++ b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_template_validation.go @@ -0,0 +1,86 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha1 + +import ( + "github.com/knative/pkg/apis" + corev1 "k8s.io/api/core/v1" +) + +// Validate build template +func (b *BuildTemplate) Validate() *apis.FieldError { + return validateObjectMetadata(b.GetObjectMeta()).ViaField("metadata").Also(b.Spec.Validate().ViaField("spec")) +} + +// Validate Build Template +func (b *BuildTemplateSpec) Validate() *apis.FieldError { + if err := validateSteps(b.Steps); err != nil { + return err + } + if err := ValidateVolumes(b.Volumes); err != nil { + return err + } + if err := validateParameters(b.Parameters); err != nil { + return err + } + return nil +} + +//ValidateVolumes validates collection of volumes that are available to mount into the +// steps of the build ot build template. +func ValidateVolumes(volumes []corev1.Volume) *apis.FieldError { + // Build must not duplicate volume names. + vols := map[string]struct{}{} + for _, v := range volumes { + if _, ok := vols[v.Name]; ok { + return apis.ErrMultipleOneOf("volumeName") + } + vols[v.Name] = struct{}{} + } + return nil +} + +func validateSteps(steps []corev1.Container) *apis.FieldError { + // Build must not duplicate step names. + names := map[string]struct{}{} + for _, s := range steps { + if s.Image == "" { + return apis.ErrMissingField("Image") + } + + if s.Name == "" { + continue + } + if _, ok := names[s.Name]; ok { + return apis.ErrMultipleOneOf("stepName") + } + names[s.Name] = struct{}{} + } + return nil +} + +func validateParameters(params []ParameterSpec) *apis.FieldError { + // Template must not duplicate parameter names. + seen := map[string]struct{}{} + for _, p := range params { + if _, ok := seen[p.Name]; ok { + return apis.ErrInvalidKeyName("ParamName", "b.spec.params") + } + seen[p.Name] = struct{}{} + } + return nil +} diff --git a/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_types.go b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_types.go index 9a2640db1bf..2d484b877ef 100644 --- a/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_types.go +++ b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_types.go @@ -17,10 +17,13 @@ limitations under the License. package v1alpha1 import ( - "encoding/json" - corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + + "github.com/knative/pkg/apis" + duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" + "github.com/knative/pkg/kmeta" ) // +genclient @@ -38,6 +41,13 @@ type Build struct { Status BuildStatus `json:"status"` } +// Check that our resource implements several interfaces. +var _ kmeta.OwnerRefable = (*Build)(nil) + +// Check that Build may be validated and defaulted. +var _ apis.Validatable = (*Build)(nil) +var _ apis.Defaultable = (*Build)(nil) + // BuildSpec is the spec for a Build resource. type BuildSpec struct { // TODO: Generation does not work correctly with CRD. They are scrubbed @@ -63,10 +73,36 @@ type BuildSpec struct { // Template, if specified, references a BuildTemplate resource to use to // populate fields in the build, and optional Arguments to pass to the - // template. + // template. The default Kind of template is BuildTemplate Template *TemplateInstantiationSpec `json:"template,omitempty"` + + // NodeSelector is a selector which must be true for the pod to fit on a node. + // Selector which must match a node's labels for the pod to be scheduled on that node. + // More info: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/ + // +optional + NodeSelector map[string]string `json:"nodeSelector,omitempty"` + + // Time after which the build times out. Defaults to 10 minutes. + // Specified build timeout should be less than 24h. + // Refer Go's ParseDuration documentation for expected format: https://golang.org/pkg/time/#ParseDuration + // +optional + Timeout *metav1.Duration `json:"timeout,omitempty"` + + // If specified, the pod's scheduling constraints + // +optional + Affinity *corev1.Affinity `json:"affinity,omitempty"` } +// TemplateKind defines the type of BuildTemplate used by the build. +type TemplateKind string + +const ( + // BuildTemplateKind indicates that the template type has a namepace scope. + BuildTemplateKind TemplateKind = "BuildTemplate" + // ClusterBuildTemplateKind indicates that template type has a cluster scope. + ClusterBuildTemplateKind TemplateKind = "ClusterBuildTemplate" +) + // TemplateInstantiationSpec specifies how a BuildTemplate is instantiated into // a Build. type TemplateInstantiationSpec struct { @@ -75,6 +111,10 @@ type TemplateInstantiationSpec struct { // The template is assumed to exist in the Build's namespace. Name string `json:"name"` + // The Kind of the template to be used, possible values are BuildTemplate + // or ClusterBuildTemplate. If nothing is specified, the default if is BuildTemplate + Kind TemplateKind `json:"kind,omitempty"` + // Arguments, if specified, lists values that should be applied to the // parameters specified by the template. Arguments []ArgumentSpec `json:"arguments,omitempty"` @@ -87,16 +127,30 @@ type TemplateInstantiationSpec struct { // ArgumentSpec defines the actual values to use to populate a template's // parameters. type ArgumentSpec struct { - Name string `json:"name"` + // Name is the name of the argument. + Name string `json:"name"` + // Value is the value of the argument. Value string `json:"value"` // TODO(jasonhall): ValueFrom? } // SourceSpec defines the input to the Build type SourceSpec struct { - Git *GitSourceSpec `json:"git,omitempty"` - GCS *GCSSourceSpec `json:"gcs,omitempty"` + // Git represents source in a Git repository. + Git *GitSourceSpec `json:"git,omitempty"` + + // GCS represents source in Google Cloud Storage. + GCS *GCSSourceSpec `json:"gcs,omitempty"` + + // Custom indicates that source should be retrieved using a custom + // process defined in a container invocation. Custom *corev1.Container `json:"custom,omitempty"` + + // SubPath specifies a path within the fetched source which should be + // built. This option makes parent directories *inaccessible* to the + // build steps. (The specific source type may, in fact, not even fetch + // files not in the SubPath.) + SubPath string `json:"subPath,omitempty"` } // GitSourceSpec describes a Git repo source input to the Build. @@ -113,21 +167,30 @@ type GitSourceSpec struct { // GCSSourceSpec describes source input to the Build in the form of an archive, // or a source manifest describing files to fetch. type GCSSourceSpec struct { - Type GCSSourceType `json:"type,omitempty"` - Location string `json:"location,omitempty"` + // Type declares the style of source to fetch. + Type GCSSourceType `json:"type,omitempty"` + + // Location specifies the location of the source archive or manifest file. + Location string `json:"location,omitempty"` } +// GCSSourceType defines a type of GCS source fetch. type GCSSourceType string const ( - GCSArchive GCSSourceType = "Archive" + // GCSArchive indicates that source should be fetched from a typical archive file. + GCSArchive GCSSourceType = "Archive" + + // GCSManifest indicates that source should be fetched using a + // manifest-based protocol which enables incremental source upload. GCSManifest GCSSourceType = "Manifest" ) +// BuildProvider defines a build execution implementation. type BuildProvider string const ( - // GoogleBuildProvider indicates that this build was performed with Google Container Builder. + // GoogleBuildProvider indicates that this build was performed with Google Cloud Build. GoogleBuildProvider BuildProvider = "Google" // ClusterBuildProvider indicates that this build was performed on-cluster. ClusterBuildProvider BuildProvider = "Cluster" @@ -137,51 +200,51 @@ const ( type BuildStatus struct { Builder BuildProvider `json:"builder,omitempty"` - // Additional information based on the Builder executing this build. + // Cluster provides additional information if the builder is Cluster. Cluster *ClusterSpec `json:"cluster,omitempty"` - Google *GoogleSpec `json:"google,omitempty"` + // Google provides additional information if the builder is Google. + Google *GoogleSpec `json:"google,omitempty"` - // Information about the execution of the build. - StartTime metav1.Time `json:"startTime,omitEmpty"` + // StartTime is the time the build is actually started. + StartTime metav1.Time `json:"startTime,omitEmpty"` + // CompletionTime is the time the build completed. CompletionTime metav1.Time `json:"completionTime,omitEmpty"` - // Parallel list to spec.Containers + // StepStates describes the state of each build step container. StepStates []corev1.ContainerState `json:"stepStates,omitEmpty"` - Conditions []BuildCondition `json:"conditions,omitempty"` + + // StepsCompleted lists the name of build steps completed. + StepsCompleted []string `json:"stepsCompleted"` + + // Conditions describes the set of conditions of this build. + Conditions duckv1alpha1.Conditions `json:"conditions,omitempty"` } +// Check that BuildStatus may have its conditions managed. +var _ duckv1alpha1.ConditionsAccessor = (*BuildStatus)(nil) + +// ClusterSpec provides information about the on-cluster build, if applicable. type ClusterSpec struct { + // Namespace is the namespace in which the pod is running. Namespace string `json:"namespace"` - PodName string `json:"podName"` + // PodName is the name of the pod responsible for executing this build's steps. + PodName string `json:"podName"` } +// GoogleSpec provides information about the GCB build, if applicable. type GoogleSpec struct { + // Operation is the unique name of the GCB API Operation for the build. Operation string `json:"operation"` } -type BuildConditionType string - -const ( - // BuildSucceeded is set when the build is running, and becomes True - // when the build finishes successfully. - // - // If the build is ongoing, its status will be Unknown. If it fails, - // its status will be False. - BuildSucceeded BuildConditionType = "Succeeded" -) - -// BuildCondition defines a readiness condition for a Build. -// See: https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#typical-status-properties -type BuildCondition struct { - Type BuildConditionType `json:"state"` +// BuildSucceeded is set when the build is running, and becomes True when the +// build finishes successfully. +// +// If the build is ongoing, its status will be Unknown. If it fails, its status +// will be False. +const BuildSucceeded = duckv1alpha1.ConditionSucceeded - Status corev1.ConditionStatus `json:"status" description:"status of the condition, one of True, False, Unknown"` - - // +optional - Reason string `json:"reason,omitempty" description:"one-word CamelCase reason for the condition's last transition"` - // +optional - Message string `json:"message,omitempty" description:"human-readable message indicating details about last transition"` -} +var buildCondSet = duckv1alpha1.NewBatchConditionSet() // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object @@ -190,44 +253,35 @@ type BuildList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata"` + // Items is the list of Build items in this list. Items []Build `json:"items"` } -func (bs *BuildStatus) GetCondition(t BuildConditionType) *BuildCondition { - for _, cond := range bs.Conditions { - if cond.Type == t { - return &cond - } - } - return nil +// GetCondition returns the Condition matching the given type. +func (bs *BuildStatus) GetCondition(t duckv1alpha1.ConditionType) *duckv1alpha1.Condition { + return buildCondSet.Manage(bs).GetCondition(t) } -func (b *BuildStatus) SetCondition(newCond *BuildCondition) { - if newCond == nil { - return +// SetCondition sets the condition, unsetting previous conditions with the same +// type as necessary. +func (bs *BuildStatus) SetCondition(newCond *duckv1alpha1.Condition) { + if newCond != nil { + buildCondSet.Manage(bs).SetCondition(*newCond) } +} - t := newCond.Type - var conditions []BuildCondition - for _, cond := range b.Conditions { - if cond.Type != t { - conditions = append(conditions, cond) - } - } - conditions = append(conditions, *newCond) - b.Conditions = conditions +// GetConditions returns the Conditions array. This enables generic handling of +// conditions by implementing the duckv1alpha1.Conditions interface. +func (bs *BuildStatus) GetConditions() duckv1alpha1.Conditions { + return bs.Conditions } -func (b *BuildStatus) RemoveCondition(t BuildConditionType) { - var conditions []BuildCondition - for _, cond := range b.Conditions { - if cond.Type != t { - conditions = append(conditions, cond) - } - } - b.Conditions = conditions +// SetConditions sets the Conditions array. This enables generic handling of +// conditions by implementing the duckv1alpha1.Conditions interface. +func (bs *BuildStatus) SetConditions(conditions duckv1alpha1.Conditions) { + bs.Conditions = conditions } -func (b *Build) GetGeneration() int64 { return b.Spec.Generation } -func (b *Build) SetGeneration(generation int64) { b.Spec.Generation = generation } -func (b *Build) GetSpecJSON() ([]byte, error) { return json.Marshal(b.Spec) } +func (b *Build) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("Build") +} diff --git a/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_validation.go b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_validation.go new file mode 100644 index 00000000000..04792a42f6d --- /dev/null +++ b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/build_validation.go @@ -0,0 +1,94 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha1 + +import ( + "fmt" + "time" + + "github.com/knative/pkg/apis" +) + +// Validate Build +func (b *Build) Validate() *apis.FieldError { + return validateObjectMetadata(b.GetObjectMeta()).ViaField("metadata").Also(b.Spec.Validate().ViaField("spec")) +} + +// Validate for build spec +func (bs *BuildSpec) Validate() *apis.FieldError { + if bs.Template == nil && len(bs.Steps) == 0 { + return apis.ErrMissingField("b.spec.template").Also(apis.ErrMissingField("b.spec.steps")) + } + if bs.Template != nil && len(bs.Steps) > 0 { + return apis.ErrMissingField("b.spec.template").Also(apis.ErrMissingField("b.spec.steps")) + } + + if bs.Template != nil && bs.Template.Name == "" { + apis.ErrMissingField("build.spec.template.name") + } + + // If a build specifies a template, all the template's parameters without + // defaults must be satisfied by the build's parameters. + if bs.Template != nil { + return bs.Template.Validate() + } + if err := ValidateVolumes(bs.Volumes); err != nil { + return err + } + if err := bs.validateTimeout(); err != nil { + return err + } + + if err := validateSteps(bs.Steps); err != nil { + return err + } + return nil +} + +// Validate templateKind +func (b *TemplateInstantiationSpec) Validate() *apis.FieldError { + if b == nil { + return nil + } + if b.Name == "" { + return apis.ErrMissingField("build.spec.template.name") + } + if b.Kind != "" { + switch b.Kind { + case ClusterBuildTemplateKind, + BuildTemplateKind: + return nil + default: + return apis.ErrInvalidValue(string(b.Kind), apis.CurrentField) + } + } + return nil +} + +func (bt *BuildSpec) validateTimeout() *apis.FieldError { + if bt.Timeout == nil { + return nil + } + maxTimeout := time.Duration(24 * time.Hour) + + if bt.Timeout.Duration > maxTimeout { + return apis.ErrInvalidValue(fmt.Sprintf("%s should be < 24h", bt.Timeout), "b.spec.timeout") + } else if bt.Timeout.Duration < 0 { + return apis.ErrInvalidValue(fmt.Sprintf("%s should be > 0", bt.Timeout), "b.spec.timeout") + } + return nil +} diff --git a/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/cluster_build_template_types.go b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/cluster_build_template_types.go new file mode 100644 index 00000000000..604b13371de --- /dev/null +++ b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/cluster_build_template_types.go @@ -0,0 +1,74 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + + "github.com/knative/pkg/apis" + "github.com/knative/pkg/kmeta" +) + +// +genclient +// +genclient:noStatus +// +genclient:nonNamespaced +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ClusterBuildTemplate is a template that can used to easily create Builds. +type ClusterBuildTemplate struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec BuildTemplateSpec `json:"spec"` +} + +// Check that our resource implements several interfaces. +var _ kmeta.OwnerRefable = (*ClusterBuildTemplate)(nil) +var _ Template = (*ClusterBuildTemplate)(nil) +var _ BuildTemplateInterface = (*ClusterBuildTemplate)(nil) + +// Check that ClusterBuildTemplate may be validated and defaulted. +var _ apis.Validatable = (*ClusterBuildTemplate)(nil) +var _ apis.Defaultable = (*ClusterBuildTemplate)(nil) + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ClusterBuildTemplateList is a list of BuildTemplate resources. +type ClusterBuildTemplateList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata"` + + Items []ClusterBuildTemplate `json:"items"` +} + +// TemplateSpec returnes the Spec used by the template +func (bt *ClusterBuildTemplate) TemplateSpec() BuildTemplateSpec { + return bt.Spec +} + +// Copy performes a deep copy +func (bt *ClusterBuildTemplate) Copy() BuildTemplateInterface { + return bt.DeepCopy() +} + +func (bt *ClusterBuildTemplate) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("ClusterBuildTemplate") +} + +// SetDefaults +func (b *ClusterBuildTemplate) SetDefaults() {} diff --git a/pkg/apis/channels/v1alpha1/channel_defaults.go b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/cluster_build_template_validation.go similarity index 70% rename from pkg/apis/channels/v1alpha1/channel_defaults.go rename to vendor/github.com/knative/build/pkg/apis/build/v1alpha1/cluster_build_template_validation.go index 262ffca487d..111c8d5cc68 100644 --- a/pkg/apis/channels/v1alpha1/channel_defaults.go +++ b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/cluster_build_template_validation.go @@ -16,10 +16,9 @@ limitations under the License. package v1alpha1 -func (c *Channel) SetDefaults() { - c.Spec.SetDefaults() -} +import "github.com/knative/pkg/apis" -func (fs *ChannelSpec) SetDefaults() { - // TODO anything? +// Validate ClusterBuildTemplate +func (b *ClusterBuildTemplate) Validate() *apis.FieldError { + return validateObjectMetadata(b.GetObjectMeta()).ViaField("metadata").Also(b.Spec.Validate().ViaField("spec")) } diff --git a/pkg/apis/feeds/v1alpha1/common_event_type_validation.go b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/metadata_validation.go similarity index 54% rename from pkg/apis/feeds/v1alpha1/common_event_type_validation.go rename to vendor/github.com/knative/build/pkg/apis/build/v1alpha1/metadata_validation.go index 9457e14a422..8801c3fca6f 100644 --- a/pkg/apis/feeds/v1alpha1/common_event_type_validation.go +++ b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/metadata_validation.go @@ -17,10 +17,31 @@ limitations under the License. package v1alpha1 import ( + "strings" + "github.com/knative/pkg/apis" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +const ( + maxLength = 63 ) -func (cess *CommonEventTypeSpec) Validate() *apis.FieldError { - // nothing to validate. +func validateObjectMetadata(meta metav1.Object) *apis.FieldError { + name := meta.GetName() + + if strings.Contains(name, ".") { + return &apis.FieldError{ + Message: "Invalid resource name: special character . must not be present", + Paths: []string{"name"}, + } + } + + if len(name) > maxLength { + return &apis.FieldError{ + Message: "Invalid resource name: length must be no more than 63 characters", + Paths: []string{"name"}, + } + } return nil } diff --git a/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/register.go b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/register.go index 95c900c26ee..c2b2c6512c7 100644 --- a/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/register.go +++ b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/register.go @@ -38,8 +38,10 @@ func Resource(resource string) schema.GroupResource { } var ( - SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) - AddToScheme = SchemeBuilder.AddToScheme + schemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) + + // AddToScheme adds Build types to the scheme. + AddToScheme = schemeBuilder.AddToScheme ) // Adds the list of known types to Scheme. @@ -49,6 +51,8 @@ func addKnownTypes(scheme *runtime.Scheme) error { &BuildList{}, &BuildTemplate{}, &BuildTemplateList{}, + &ClusterBuildTemplate{}, + &ClusterBuildTemplateList{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil diff --git a/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/zz_generated.deepcopy.go b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/zz_generated.deepcopy.go index a73da3e46ac..0880074fb1b 100644 --- a/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/zz_generated.deepcopy.go +++ b/vendor/github.com/knative/build/pkg/apis/build/v1alpha1/zz_generated.deepcopy.go @@ -21,7 +21,9 @@ limitations under the License. package v1alpha1 import ( + duck_v1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" v1 "k8s.io/api/core/v1" + meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) @@ -69,22 +71,6 @@ func (in *Build) DeepCopyObject() runtime.Object { return nil } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BuildCondition) DeepCopyInto(out *BuildCondition) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BuildCondition. -func (in *BuildCondition) DeepCopy() *BuildCondition { - if in == nil { - return nil - } - out := new(BuildCondition) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *BuildList) DeepCopyInto(out *BuildList) { *out = *in @@ -153,6 +139,31 @@ func (in *BuildSpec) DeepCopyInto(out *BuildSpec) { (*in).DeepCopyInto(*out) } } + if in.NodeSelector != nil { + in, out := &in.NodeSelector, &out.NodeSelector + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + if in.Timeout != nil { + in, out := &in.Timeout, &out.Timeout + if *in == nil { + *out = nil + } else { + *out = new(meta_v1.Duration) + **out = **in + } + } + if in.Affinity != nil { + in, out := &in.Affinity, &out.Affinity + if *in == nil { + *out = nil + } else { + *out = new(v1.Affinity) + (*in).DeepCopyInto(*out) + } + } return } @@ -196,10 +207,17 @@ func (in *BuildStatus) DeepCopyInto(out *BuildStatus) { (*in)[i].DeepCopyInto(&(*out)[i]) } } + if in.StepsCompleted != nil { + in, out := &in.StepsCompleted, &out.StepsCompleted + *out = make([]string, len(*in)) + copy(*out, *in) + } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make([]BuildCondition, len(*in)) - copy(*out, *in) + *out = make(duck_v1alpha1.Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } } return } @@ -311,6 +329,66 @@ func (in *BuildTemplateSpec) DeepCopy() *BuildTemplateSpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterBuildTemplate) DeepCopyInto(out *ClusterBuildTemplate) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterBuildTemplate. +func (in *ClusterBuildTemplate) DeepCopy() *ClusterBuildTemplate { + if in == nil { + return nil + } + out := new(ClusterBuildTemplate) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClusterBuildTemplate) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterBuildTemplateList) DeepCopyInto(out *ClusterBuildTemplateList) { + *out = *in + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ClusterBuildTemplate, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterBuildTemplateList. +func (in *ClusterBuildTemplateList) DeepCopy() *ClusterBuildTemplateList { + if in == nil { + return nil + } + out := new(ClusterBuildTemplateList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClusterBuildTemplateList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ClusterSpec) DeepCopyInto(out *ClusterSpec) { *out = *in diff --git a/vendor/github.com/knative/build/test/panic/kodata/LICENSE b/vendor/github.com/knative/build/test/panic/kodata/LICENSE new file mode 120000 index 00000000000..5853aaea53b --- /dev/null +++ b/vendor/github.com/knative/build/test/panic/kodata/LICENSE @@ -0,0 +1 @@ +../../../LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/build/test/panic/kodata/VENDOR-LICENSE b/vendor/github.com/knative/build/test/panic/kodata/VENDOR-LICENSE new file mode 120000 index 00000000000..3cc89764519 --- /dev/null +++ b/vendor/github.com/knative/build/test/panic/kodata/VENDOR-LICENSE @@ -0,0 +1 @@ +../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/build/test/workingdir/kodata/LICENSE b/vendor/github.com/knative/build/test/workingdir/kodata/LICENSE new file mode 120000 index 00000000000..5853aaea53b --- /dev/null +++ b/vendor/github.com/knative/build/test/workingdir/kodata/LICENSE @@ -0,0 +1 @@ +../../../LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/build/test/workingdir/kodata/VENDOR-LICENSE b/vendor/github.com/knative/build/test/workingdir/kodata/VENDOR-LICENSE new file mode 120000 index 00000000000..3cc89764519 --- /dev/null +++ b/vendor/github.com/knative/build/test/workingdir/kodata/VENDOR-LICENSE @@ -0,0 +1 @@ +../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/eventing-sources/AUTHORS b/vendor/github.com/knative/eventing-sources/AUTHORS new file mode 100644 index 00000000000..9a8f2f769f4 --- /dev/null +++ b/vendor/github.com/knative/eventing-sources/AUTHORS @@ -0,0 +1,6 @@ +# This is the list of Knative authors for copyright purposes. +# +# This does not necessarily list everyone who has contributed code, since in +# some cases, their employer may be the copyright holder. To see the full list +# of contributors, see the revision history in source control. +Google LLC diff --git a/vendor/github.com/knative/eventing-sources/LICENSE b/vendor/github.com/knative/eventing-sources/LICENSE new file mode 100644 index 00000000000..261eeb9e9f8 --- /dev/null +++ b/vendor/github.com/knative/eventing-sources/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/containersource_types.go b/vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/containersource_types.go new file mode 100644 index 00000000000..a04e21e73fc --- /dev/null +++ b/vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/containersource_types.go @@ -0,0 +1,160 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha1 + +import ( + "github.com/knative/pkg/apis/duck" + duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +// Important: Run "make" to regenerate code after modifying this file +// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. + +// Check that ContainerSource can be validated and can be defaulted. +var _ runtime.Object = (*ContainerSource)(nil) + +// Check that ContainerSource implements the Conditions duck type. +var _ = duck.VerifyType(&ContainerSource{}, &duckv1alpha1.Conditions{}) + +// ContainerSourceSpec defines the desired state of ContainerSource +type ContainerSourceSpec struct { + // Image is the image to run inside of the container. + // +kubebuilder:validation:MinLength=1 + Image string `json:"image,omitempty"` + + // Args are passed to the ContainerSpec as they are. + Args []string `json:"args,omitempty"` + + // Env is the list of environment variables to set in the container. + // Cannot be updated. + // +optional + // +patchMergeKey=name + // +patchStrategy=merge + Env []corev1.EnvVar `json:"env,omitempty" patchStrategy:"merge" patchMergeKey:"name"` + + // ServiceAccountName is the name of the ServiceAccount to use to run this + // source. + // +optional + ServiceAccountName string `json:"serviceAccountName,omitempty"` + + // Sink is a reference to an object that will resolve to a domain name to use as the sink. + // +optional + Sink *corev1.ObjectReference `json:"sink,omitempty"` +} + +const ( + // ContainerSourceConditionReady has status True when the ContainerSource is ready to send events. + ContainerConditionReady = duckv1alpha1.ConditionReady + + // ContainerConditionSinkProvided has status True when the ContainerSource has been configured with a sink target. + ContainerConditionSinkProvided duckv1alpha1.ConditionType = "SinkProvided" + + // ContainerConditionDeployed has status True when the ContainerSource has had it's deployment created. + ContainerConditionDeployed duckv1alpha1.ConditionType = "Deployed" +) + +var containerCondSet = duckv1alpha1.NewLivingConditionSet( + ContainerConditionSinkProvided, + ContainerConditionDeployed) + +// ContainerSourceStatus defines the observed state of ContainerSource +type ContainerSourceStatus struct { + // Conditions holds the state of a source at a point in time. + // +optional + // +patchMergeKey=type + // +patchStrategy=merge + Conditions duckv1alpha1.Conditions `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` + + // SinkURI is the current active sink URI that has been configured for the ContainerSource. + // +optional + SinkURI string `json:"sinkUri,omitempty"` +} + +// GetCondition returns the condition currently associated with the given type, or nil. +func (s *ContainerSourceStatus) GetCondition(t duckv1alpha1.ConditionType) *duckv1alpha1.Condition { + return containerCondSet.Manage(s).GetCondition(t) +} + +// IsReady returns true if the resource is ready overall. +func (s *ContainerSourceStatus) IsReady() bool { + return containerCondSet.Manage(s).IsHappy() +} + +// InitializeConditions sets relevant unset conditions to Unknown state. +func (s *ContainerSourceStatus) InitializeConditions() { + containerCondSet.Manage(s).InitializeConditions() +} + +// MarSink sets the condition that the source has a sink configured. +func (s *ContainerSourceStatus) MarkSink(uri string) { + s.SinkURI = uri + if len(uri) > 0 { + containerCondSet.Manage(s).MarkTrue(ContainerConditionSinkProvided) + } else { + containerCondSet.Manage(s).MarkUnknown(ContainerConditionSinkProvided, "SinkEmpty", "Sink has resolved to empty.%s", "") + } +} + +// MarkNoSink sets the condition that the source does not have a sink configured. +func (s *ContainerSourceStatus) MarkNoSink(reason, messageFormat string, messageA ...interface{}) { + containerCondSet.Manage(s).MarkFalse(ContainerConditionSinkProvided, reason, messageFormat, messageA...) +} + +// MarkDeployed sets the condition that the source has been deployed. +func (s *ContainerSourceStatus) MarkDeployed() { + containerCondSet.Manage(s).MarkTrue(ContainerConditionDeployed) +} + +// MarkDeploying sets the condition that the source is deploying. +func (s *ContainerSourceStatus) MarkDeploying(reason, messageFormat string, messageA ...interface{}) { + containerCondSet.Manage(s).MarkUnknown(ContainerConditionDeployed, reason, messageFormat, messageA...) +} + +// MarkNotDeployed sets the condition that the source has not been deployed. +func (s *ContainerSourceStatus) MarkNotDeployed(reason, messageFormat string, messageA ...interface{}) { + containerCondSet.Manage(s).MarkFalse(ContainerConditionDeployed, reason, messageFormat, messageA...) +} + +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ContainerSource is the Schema for the containersources API +// +k8s:openapi-gen=true +// +kubebuilder:categories=all,knative,eventing,sources +type ContainerSource struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec ContainerSourceSpec `json:"spec,omitempty"` + Status ContainerSourceStatus `json:"status,omitempty"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ContainerSourceList contains a list of ContainerSource +type ContainerSourceList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []ContainerSource `json:"items"` +} + +func init() { + SchemeBuilder.Register(&ContainerSource{}, &ContainerSourceList{}) +} diff --git a/pkg/client/clientset/versioned/typed/flows/v1alpha1/doc.go b/vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/doc.go similarity index 66% rename from pkg/client/clientset/versioned/typed/flows/v1alpha1/doc.go rename to vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/doc.go index 75445c17900..258a98c9176 100644 --- a/pkg/client/clientset/versioned/typed/flows/v1alpha1/doc.go +++ b/vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/doc.go @@ -14,7 +14,10 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Code generated by client-gen. DO NOT EDIT. - -// This package has the automatically generated typed clients. +// Package v1alpha1 contains API Schema definitions for the sources v1alpha1 API group +// +k8s:openapi-gen=true +// +k8s:deepcopy-gen=package,register +// +k8s:conversion-gen=github.com/knative/eventing-sources/pkg/apis/sources +// +k8s:defaulter-gen=TypeMeta +// +groupName=sources.eventing.knative.dev package v1alpha1 diff --git a/vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/gcp_pubsub_types.go b/vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/gcp_pubsub_types.go new file mode 100644 index 00000000000..1a641bd961b --- /dev/null +++ b/vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/gcp_pubsub_types.go @@ -0,0 +1,168 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha1 + +import ( + "github.com/knative/pkg/apis" + "github.com/knative/pkg/apis/duck" + duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// GcpPubSubSource is the Schema for the gcppubsubsources API. +// +k8s:openapi-gen=true +// +kubebuilder:categories=all,knative,eventing,sources +type GcpPubSubSource struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec GcpPubSubSourceSpec `json:"spec,omitempty"` + Status GcpPubSubSourceStatus `json:"status,omitempty"` +} + +// Check that GcpPubSubSource can be validated and can be defaulted. +var _ runtime.Object = (*GcpPubSubSource)(nil) + +// Check that GcpPubSubSource will be checked for immutable fields. +var _ apis.Immutable = (*GcpPubSubSource)(nil) + +// Check that GcpPubSubSource implements the Conditions duck type. +var _ = duck.VerifyType(&GcpPubSubSource{}, &duckv1alpha1.Conditions{}) + +// GcpPubSubSourceSpec defines the desired state of the GcpPubSubSource. +type GcpPubSubSourceSpec struct { + // GcpCredsSecret is the credential to use to poll the GCP PubSub Subscription. It is not used + // to create or delete the Subscription, only to poll it. The value of the secret entry must be + // a service account key in the JSON format (see + // https://cloud.google.com/iam/docs/creating-managing-service-account-keys). + GcpCredsSecret corev1.SecretKeySelector `json:"gcpCredsSecret,omitempty"` + + // GoogleCloudProject is the ID of the Google Cloud Project that the PubSub Topic exists in. + GoogleCloudProject string `json:"googleCloudProject,omitempty"` + + // Topic is the ID of the GCP PubSub Topic to Subscribe to. It must be in the form of the + // unique identifier within the project, not the entire name. E.g. it must be 'laconia', not + // 'projects/my-gcp-project/topics/laconia'. + Topic string `json:"topic,omitempty"` + + // Sink is a reference to an object that will resolve to a domain name to use as the sink. + // +optional + Sink *corev1.ObjectReference `json:"sink,omitempty"` + + // ServiceAccoutName is the name of the ServiceAccount that will be used to run the Receive + // Adapter Deployment. + ServiceAccountName string `json:"serviceAccountName,omitempty"` +} + +const ( + // GcpPubSubConditionReady has status True when the GcpPubSubSource is ready to send events. + GcpPubSubConditionReady = duckv1alpha1.ConditionReady + + // GcpPubSubConditionSinkProvided has status True when the GcpPubSubSource has been configured with a sink target. + GcpPubSubConditionSinkProvided duckv1alpha1.ConditionType = "SinkProvided" + + // GcpPubSubConditionDeployed has status True when the GcpPubSubSource has had it's receive adapter deployment created. + GcpPubSubConditionDeployed duckv1alpha1.ConditionType = "Deployed" + + // GcpPubSubConditionSubscribed has status True when a GCP PubSub Subscription has been created pointing at the created receive adapter deployment. + GcpPubSubConditionSubscribed duckv1alpha1.ConditionType = "Subscribed" +) + +var gcpPubSubSourceCondSet = duckv1alpha1.NewLivingConditionSet( + GcpPubSubConditionSinkProvided, + GcpPubSubConditionDeployed, + GcpPubSubConditionSubscribed) + +// GcpPubSubSourceStatus defines the observed state of GcpPubSubSource. +type GcpPubSubSourceStatus struct { + // Conditions holds the state of a source at a point in time. + // +optional + // +patchMergeKey=type + // +patchStrategy=merge + Conditions duckv1alpha1.Conditions `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` + + // SinkURI is the current active sink URI that has been configured for the GcpPubSubSource. + // +optional + SinkURI string `json:"sinkUri,omitempty"` +} + +// GetCondition returns the condition currently associated with the given type, or nil. +func (s *GcpPubSubSourceStatus) GetCondition(t duckv1alpha1.ConditionType) *duckv1alpha1.Condition { + return gcpPubSubSourceCondSet.Manage(s).GetCondition(t) +} + +// IsReady returns true if the resource is ready overall. +func (s *GcpPubSubSourceStatus) IsReady() bool { + return gcpPubSubSourceCondSet.Manage(s).IsHappy() +} + +// InitializeConditions sets relevant unset conditions to Unknown state. +func (s *GcpPubSubSourceStatus) InitializeConditions() { + gcpPubSubSourceCondSet.Manage(s).InitializeConditions() +} + +// MarkSink sets the condition that the source has a sink configured. +func (s *GcpPubSubSourceStatus) MarkSink(uri string) { + s.SinkURI = uri + if len(uri) > 0 { + gcpPubSubSourceCondSet.Manage(s).MarkTrue(GcpPubSubConditionSinkProvided) + } else { + gcpPubSubSourceCondSet.Manage(s).MarkUnknown(GcpPubSubConditionSinkProvided, "SinkEmpty", "Sink has resolved to empty.%s", "") + } +} + +// MarkNoSink sets the condition that the source does not have a sink configured. +func (s *GcpPubSubSourceStatus) MarkNoSink(reason, messageFormat string, messageA ...interface{}) { + gcpPubSubSourceCondSet.Manage(s).MarkFalse(GcpPubSubConditionSinkProvided, reason, messageFormat, messageA...) +} + +// MarkDeployed sets the condition that the source has been deployed. +func (s *GcpPubSubSourceStatus) MarkDeployed() { + gcpPubSubSourceCondSet.Manage(s).MarkTrue(GcpPubSubConditionDeployed) +} + +// MarkDeploying sets the condition that the source is deploying. +func (s *GcpPubSubSourceStatus) MarkDeploying(reason, messageFormat string, messageA ...interface{}) { + gcpPubSubSourceCondSet.Manage(s).MarkUnknown(GcpPubSubConditionDeployed, reason, messageFormat, messageA...) +} + +// MarkNotDeployed sets the condition that the source has not been deployed. +func (s *GcpPubSubSourceStatus) MarkNotDeployed(reason, messageFormat string, messageA ...interface{}) { + gcpPubSubSourceCondSet.Manage(s).MarkFalse(GcpPubSubConditionDeployed, reason, messageFormat, messageA...) +} + +func (s *GcpPubSubSourceStatus) MarkSubscribed() { + gcpPubSubSourceCondSet.Manage(s).MarkTrue(GcpPubSubConditionSubscribed) +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// GcpPubSubSourceList contains a list of GcpPubSubSources. +type GcpPubSubSourceList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []GcpPubSubSource `json:"items"` +} + +func init() { + SchemeBuilder.Register(&GcpPubSubSource{}, &GcpPubSubSourceList{}) +} diff --git a/pkg/apis/channels/v1alpha1/subscription_validation.go b/vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/gcp_pubsub_validation.go similarity index 53% rename from pkg/apis/channels/v1alpha1/subscription_validation.go rename to vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/gcp_pubsub_validation.go index c2f7ae8ab91..fc563c8bc82 100644 --- a/pkg/apis/channels/v1alpha1/subscription_validation.go +++ b/vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/gcp_pubsub_validation.go @@ -18,39 +18,22 @@ package v1alpha1 import ( "github.com/google/go-cmp/cmp" - "github.com/google/go-cmp/cmp/cmpopts" "github.com/knative/pkg/apis" ) -func (s *Subscription) Validate() *apis.FieldError { - return s.Spec.Validate().ViaField("spec") -} - -func (ss *SubscriptionSpec) Validate() *apis.FieldError { - if ss.Channel == "" { - fe := apis.ErrMissingField("channel") - fe.Details = "the Subscription must reference a Channel" - return fe - } - if ss.Subscriber == "" { - fe := apis.ErrMissingField("subscriber") - fe.Details = "the Subscription must reference a Subscriber" - return fe - } - return nil -} - -func (current *Subscription) CheckImmutableFields(og apis.Immutable) *apis.FieldError { - original, ok := og.(*Subscription) +func (current *GcpPubSubSource) CheckImmutableFields(og apis.Immutable) *apis.FieldError { + original, ok := og.(*GcpPubSubSource) if !ok { - return &apis.FieldError{Message: "The provided original was not a Subscription"} + return &apis.FieldError{Message: "The provided original was not a GcpPubSubSource"} } if original == nil { return nil } - ignoreArguments := cmpopts.IgnoreFields(SubscriptionSpec{}, "Subscriber", "Arguments") - if diff := cmp.Diff(original.Spec, current.Spec, ignoreArguments); diff != "" { + // All of the fields are immutable because the controller doesn't understand when it would need + // to delete and create a new Receive Adapter with updated arguments. We could relax it slightly + // to allow a nil Sink -> non-nil Sink, but I don't think it is needed yet. + if diff := cmp.Diff(original.Spec, current.Spec); diff != "" { return &apis.FieldError{ Message: "Immutable fields changed (-old +new)", Paths: []string{"spec"}, diff --git a/vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/kuberneteseventsource_types.go b/vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/kuberneteseventsource_types.go new file mode 100644 index 00000000000..f4281723397 --- /dev/null +++ b/vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/kuberneteseventsource_types.go @@ -0,0 +1,121 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha1 + +import ( + "github.com/knative/pkg/apis/duck" + duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +// Check that KubernetesEventSource can be validated and can be defaulted. +var _ runtime.Object = (*KubernetesEventSource)(nil) + +// Check that KubernetesEventSource implements the Conditions duck type. +var _ = duck.VerifyType(&KubernetesEventSource{}, &duckv1alpha1.Conditions{}) + +// KubernetesEventSourceSpec defines the desired state of the source. +type KubernetesEventSourceSpec struct { + // Namespace that we watch kubernetes events in. + Namespace string `json:"namespace"` + + // ServiceAccountName is the name of the ServiceAccount to use to run this + // source. + // +optional + ServiceAccountName string `json:"serviceAccountName,omitempty"` + + // Sink is a reference to an object that will resolve to a domain name to use + // as the sink. + // +optional + Sink *corev1.ObjectReference `json:"sink,omitempty"` +} + +const ( + // KubernetesEventSourceConditionReady has status True when the + // source is ready to send events. + KubernetesEventSourceConditionReady = duckv1alpha1.ConditionReady +) + +var kubernetesEventSourceCondSet = duckv1alpha1.NewLivingConditionSet() + +// KubernetesEventSourceStatus defines the observed state of the source. +type KubernetesEventSourceStatus struct { + // Conditions holds the state of a source at a point in time. + // +optional + // +patchMergeKey=type + // +patchStrategy=merge + Conditions duckv1alpha1.Conditions `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` + + // SinkURI is the current active sink URI that has been configured for the source. + // +optional + SinkURI string `json:"sinkUri,omitempty"` +} + +// GetCondition returns the condition currently associated with the given type, or nil. +func (s *KubernetesEventSourceStatus) GetCondition(t duckv1alpha1.ConditionType) *duckv1alpha1.Condition { + return kubernetesEventSourceCondSet.Manage(s).GetCondition(t) +} + +// IsReady returns true if the resource is ready overall. +func (s *KubernetesEventSourceStatus) IsReady() bool { + return kubernetesEventSourceCondSet.Manage(s).IsHappy() +} + +// InitializeConditions sets relevant unset conditions to Unknown state. +func (s *KubernetesEventSourceStatus) InitializeConditions() { + kubernetesEventSourceCondSet.Manage(s).InitializeConditions() +} + +// MarkReady sets the condition that the ContainerSource owned by +// the source has Ready status True. +func (s *KubernetesEventSourceStatus) MarkReady() { + kubernetesEventSourceCondSet.Manage(s).MarkTrue(KubernetesEventSourceConditionReady) +} + +// MarkUnready sets the condition that the ContainerSource owned by +// the source does not have Ready status True. +func (s *KubernetesEventSourceStatus) MarkUnready(reason, messageFormat string, messageA ...interface{}) { + kubernetesEventSourceCondSet.Manage(s).MarkFalse(KubernetesEventSourceConditionReady, reason, messageFormat, messageA...) +} + +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// KubernetesEventSource is the Schema for the kuberneteseventsources API +// +k8s:openapi-gen=true +type KubernetesEventSource struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec KubernetesEventSourceSpec `json:"spec,omitempty"` + Status KubernetesEventSourceStatus `json:"status,omitempty"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// KubernetesEventSourceList contains a list of KubernetesEventSource +type KubernetesEventSourceList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []KubernetesEventSource `json:"items"` +} + +func init() { + SchemeBuilder.Register(&KubernetesEventSource{}, &KubernetesEventSourceList{}) +} diff --git a/vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/register.go b/vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/register.go new file mode 100644 index 00000000000..fa5f80118ce --- /dev/null +++ b/vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/register.go @@ -0,0 +1,45 @@ +/* +Copyright 2018 The Knative 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. +*/ + +// NOTE: Boilerplate only. Ignore this file. + +// Package v1alpha1 contains API Schema definitions for the sources v1alpha1 API group +// +k8s:openapi-gen=true +// +k8s:deepcopy-gen=package,register +// +k8s:conversion-gen=github.com/knative/eventing-sources/pkg/apis/sources +// +k8s:defaulter-gen=TypeMeta +// +groupName=sources.eventing.knative.dev +package v1alpha1 + +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/runtime/scheme" +) + +var ( + // SchemeGroupVersion is group version used to register these objects + SchemeGroupVersion = schema.GroupVersion{Group: "sources.eventing.knative.dev", Version: "v1alpha1"} + + // SchemeBuilder is used to add go types to the GroupVersionKind scheme + SchemeBuilder = &scheme.Builder{GroupVersion: SchemeGroupVersion} + + AddToScheme = SchemeBuilder.AddToScheme +) + +// Resource takes an unqualified resource and returns a Group qualified GroupResource +func Resource(resource string) schema.GroupResource { + return SchemeGroupVersion.WithResource(resource).GroupResource() +} diff --git a/vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/zz_generated.deepcopy.go b/vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 00000000000..d6feb2f7022 --- /dev/null +++ b/vendor/github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,355 @@ +// +build !ignore_autogenerated + +/* +Copyright 2018 The Knative 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. +*/ + +// Code generated by deepcopy-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" + v1 "k8s.io/api/core/v1" + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ContainerSource) DeepCopyInto(out *ContainerSource) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContainerSource. +func (in *ContainerSource) DeepCopy() *ContainerSource { + if in == nil { + return nil + } + out := new(ContainerSource) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ContainerSource) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ContainerSourceList) DeepCopyInto(out *ContainerSourceList) { + *out = *in + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ContainerSource, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContainerSourceList. +func (in *ContainerSourceList) DeepCopy() *ContainerSourceList { + if in == nil { + return nil + } + out := new(ContainerSourceList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ContainerSourceList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ContainerSourceSpec) DeepCopyInto(out *ContainerSourceSpec) { + *out = *in + if in.Args != nil { + in, out := &in.Args, &out.Args + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.Env != nil { + in, out := &in.Env, &out.Env + *out = make([]v1.EnvVar, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Sink != nil { + in, out := &in.Sink, &out.Sink + *out = new(v1.ObjectReference) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContainerSourceSpec. +func (in *ContainerSourceSpec) DeepCopy() *ContainerSourceSpec { + if in == nil { + return nil + } + out := new(ContainerSourceSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ContainerSourceStatus) DeepCopyInto(out *ContainerSourceStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(duckv1alpha1.Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContainerSourceStatus. +func (in *ContainerSourceStatus) DeepCopy() *ContainerSourceStatus { + if in == nil { + return nil + } + out := new(ContainerSourceStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *GcpPubSubSource) DeepCopyInto(out *GcpPubSubSource) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GcpPubSubSource. +func (in *GcpPubSubSource) DeepCopy() *GcpPubSubSource { + if in == nil { + return nil + } + out := new(GcpPubSubSource) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *GcpPubSubSource) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *GcpPubSubSourceList) DeepCopyInto(out *GcpPubSubSourceList) { + *out = *in + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]GcpPubSubSource, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GcpPubSubSourceList. +func (in *GcpPubSubSourceList) DeepCopy() *GcpPubSubSourceList { + if in == nil { + return nil + } + out := new(GcpPubSubSourceList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *GcpPubSubSourceList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *GcpPubSubSourceSpec) DeepCopyInto(out *GcpPubSubSourceSpec) { + *out = *in + in.GcpCredsSecret.DeepCopyInto(&out.GcpCredsSecret) + if in.Sink != nil { + in, out := &in.Sink, &out.Sink + *out = new(v1.ObjectReference) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GcpPubSubSourceSpec. +func (in *GcpPubSubSourceSpec) DeepCopy() *GcpPubSubSourceSpec { + if in == nil { + return nil + } + out := new(GcpPubSubSourceSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *GcpPubSubSourceStatus) DeepCopyInto(out *GcpPubSubSourceStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(duckv1alpha1.Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GcpPubSubSourceStatus. +func (in *GcpPubSubSourceStatus) DeepCopy() *GcpPubSubSourceStatus { + if in == nil { + return nil + } + out := new(GcpPubSubSourceStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *KubernetesEventSource) DeepCopyInto(out *KubernetesEventSource) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KubernetesEventSource. +func (in *KubernetesEventSource) DeepCopy() *KubernetesEventSource { + if in == nil { + return nil + } + out := new(KubernetesEventSource) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *KubernetesEventSource) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *KubernetesEventSourceList) DeepCopyInto(out *KubernetesEventSourceList) { + *out = *in + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]KubernetesEventSource, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KubernetesEventSourceList. +func (in *KubernetesEventSourceList) DeepCopy() *KubernetesEventSourceList { + if in == nil { + return nil + } + out := new(KubernetesEventSourceList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *KubernetesEventSourceList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *KubernetesEventSourceSpec) DeepCopyInto(out *KubernetesEventSourceSpec) { + *out = *in + if in.Sink != nil { + in, out := &in.Sink, &out.Sink + *out = new(v1.ObjectReference) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KubernetesEventSourceSpec. +func (in *KubernetesEventSourceSpec) DeepCopy() *KubernetesEventSourceSpec { + if in == nil { + return nil + } + out := new(KubernetesEventSourceSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *KubernetesEventSourceStatus) DeepCopyInto(out *KubernetesEventSourceStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(duckv1alpha1.Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KubernetesEventSourceStatus. +func (in *KubernetesEventSourceStatus) DeepCopy() *KubernetesEventSourceStatus { + if in == nil { + return nil + } + out := new(KubernetesEventSourceStatus) + in.DeepCopyInto(out) + return out +} diff --git a/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/clientset.go b/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/clientset.go new file mode 100644 index 00000000000..b87bad6733d --- /dev/null +++ b/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/clientset.go @@ -0,0 +1,98 @@ +/* +Copyright 2018 The Knative 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. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package versioned + +import ( + sourcesv1alpha1 "github.com/knative/eventing-sources/pkg/client/clientset/versioned/typed/sources/v1alpha1" + discovery "k8s.io/client-go/discovery" + rest "k8s.io/client-go/rest" + flowcontrol "k8s.io/client-go/util/flowcontrol" +) + +type Interface interface { + Discovery() discovery.DiscoveryInterface + SourcesV1alpha1() sourcesv1alpha1.SourcesV1alpha1Interface + // Deprecated: please explicitly pick a version if possible. + Sources() sourcesv1alpha1.SourcesV1alpha1Interface +} + +// Clientset contains the clients for groups. Each group has exactly one +// version included in a Clientset. +type Clientset struct { + *discovery.DiscoveryClient + sourcesV1alpha1 *sourcesv1alpha1.SourcesV1alpha1Client +} + +// SourcesV1alpha1 retrieves the SourcesV1alpha1Client +func (c *Clientset) SourcesV1alpha1() sourcesv1alpha1.SourcesV1alpha1Interface { + return c.sourcesV1alpha1 +} + +// Deprecated: Sources retrieves the default version of SourcesClient. +// Please explicitly pick a version. +func (c *Clientset) Sources() sourcesv1alpha1.SourcesV1alpha1Interface { + return c.sourcesV1alpha1 +} + +// Discovery retrieves the DiscoveryClient +func (c *Clientset) Discovery() discovery.DiscoveryInterface { + if c == nil { + return nil + } + return c.DiscoveryClient +} + +// NewForConfig creates a new Clientset for the given config. +func NewForConfig(c *rest.Config) (*Clientset, error) { + configShallowCopy := *c + if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 { + configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst) + } + var cs Clientset + var err error + cs.sourcesV1alpha1, err = sourcesv1alpha1.NewForConfig(&configShallowCopy) + if err != nil { + return nil, err + } + + cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy) + if err != nil { + return nil, err + } + return &cs, nil +} + +// NewForConfigOrDie creates a new Clientset for the given config and +// panics if there is an error in the config. +func NewForConfigOrDie(c *rest.Config) *Clientset { + var cs Clientset + cs.sourcesV1alpha1 = sourcesv1alpha1.NewForConfigOrDie(c) + + cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c) + return &cs +} + +// New creates a new Clientset for the given RESTClient. +func New(c rest.Interface) *Clientset { + var cs Clientset + cs.sourcesV1alpha1 = sourcesv1alpha1.New(c) + + cs.DiscoveryClient = discovery.NewDiscoveryClient(c) + return &cs +} diff --git a/pkg/client/clientset/versioned/typed/channels/v1alpha1/fake/doc.go b/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/doc.go similarity index 88% rename from pkg/client/clientset/versioned/typed/channels/v1alpha1/fake/doc.go rename to vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/doc.go index 128aa183a91..3fe4685848a 100644 --- a/pkg/client/clientset/versioned/typed/channels/v1alpha1/fake/doc.go +++ b/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/doc.go @@ -16,5 +16,5 @@ limitations under the License. // Code generated by client-gen. DO NOT EDIT. -// Package fake has the automatically generated clients. -package fake +// This package has the automatically generated clientset. +package versioned diff --git a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/doc.go b/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/scheme/doc.go similarity index 86% rename from pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/doc.go rename to vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/scheme/doc.go index 128aa183a91..60ea8ba90eb 100644 --- a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/fake/doc.go +++ b/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/scheme/doc.go @@ -16,5 +16,5 @@ limitations under the License. // Code generated by client-gen. DO NOT EDIT. -// Package fake has the automatically generated clients. -package fake +// This package contains the scheme of the automatically generated clientset. +package scheme diff --git a/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/scheme/register.go b/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/scheme/register.go new file mode 100644 index 00000000000..41e5040d2f7 --- /dev/null +++ b/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/scheme/register.go @@ -0,0 +1,54 @@ +/* +Copyright 2018 The Knative 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. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package scheme + +import ( + sourcesv1alpha1 "github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + schema "k8s.io/apimachinery/pkg/runtime/schema" + serializer "k8s.io/apimachinery/pkg/runtime/serializer" +) + +var Scheme = runtime.NewScheme() +var Codecs = serializer.NewCodecFactory(Scheme) +var ParameterCodec = runtime.NewParameterCodec(Scheme) + +func init() { + v1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"}) + AddToScheme(Scheme) +} + +// AddToScheme adds all types of this clientset into the given scheme. This allows composition +// of clientsets, like in: +// +// import ( +// "k8s.io/client-go/kubernetes" +// clientsetscheme "k8s.io/client-go/kubernetes/scheme" +// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" +// ) +// +// kclientset, _ := kubernetes.NewForConfig(c) +// aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) +// +// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types +// correctly. +func AddToScheme(scheme *runtime.Scheme) { + sourcesv1alpha1.AddToScheme(scheme) +} diff --git a/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/typed/sources/v1alpha1/containersource.go b/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/typed/sources/v1alpha1/containersource.go new file mode 100644 index 00000000000..7bb99182b62 --- /dev/null +++ b/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/typed/sources/v1alpha1/containersource.go @@ -0,0 +1,174 @@ +/* +Copyright 2018 The Knative 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. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + v1alpha1 "github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1" + scheme "github.com/knative/eventing-sources/pkg/client/clientset/versioned/scheme" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" +) + +// ContainerSourcesGetter has a method to return a ContainerSourceInterface. +// A group's client should implement this interface. +type ContainerSourcesGetter interface { + ContainerSources(namespace string) ContainerSourceInterface +} + +// ContainerSourceInterface has methods to work with ContainerSource resources. +type ContainerSourceInterface interface { + Create(*v1alpha1.ContainerSource) (*v1alpha1.ContainerSource, error) + Update(*v1alpha1.ContainerSource) (*v1alpha1.ContainerSource, error) + UpdateStatus(*v1alpha1.ContainerSource) (*v1alpha1.ContainerSource, error) + Delete(name string, options *v1.DeleteOptions) error + DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error + Get(name string, options v1.GetOptions) (*v1alpha1.ContainerSource, error) + List(opts v1.ListOptions) (*v1alpha1.ContainerSourceList, error) + Watch(opts v1.ListOptions) (watch.Interface, error) + Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ContainerSource, err error) + ContainerSourceExpansion +} + +// containerSources implements ContainerSourceInterface +type containerSources struct { + client rest.Interface + ns string +} + +// newContainerSources returns a ContainerSources +func newContainerSources(c *SourcesV1alpha1Client, namespace string) *containerSources { + return &containerSources{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the containerSource, and returns the corresponding containerSource object, and an error if there is any. +func (c *containerSources) Get(name string, options v1.GetOptions) (result *v1alpha1.ContainerSource, err error) { + result = &v1alpha1.ContainerSource{} + err = c.client.Get(). + Namespace(c.ns). + Resource("containersources"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of ContainerSources that match those selectors. +func (c *containerSources) List(opts v1.ListOptions) (result *v1alpha1.ContainerSourceList, err error) { + result = &v1alpha1.ContainerSourceList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("containersources"). + VersionedParams(&opts, scheme.ParameterCodec). + Do(). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested containerSources. +func (c *containerSources) Watch(opts v1.ListOptions) (watch.Interface, error) { + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("containersources"). + VersionedParams(&opts, scheme.ParameterCodec). + Watch() +} + +// Create takes the representation of a containerSource and creates it. Returns the server's representation of the containerSource, and an error, if there is any. +func (c *containerSources) Create(containerSource *v1alpha1.ContainerSource) (result *v1alpha1.ContainerSource, err error) { + result = &v1alpha1.ContainerSource{} + err = c.client.Post(). + Namespace(c.ns). + Resource("containersources"). + Body(containerSource). + Do(). + Into(result) + return +} + +// Update takes the representation of a containerSource and updates it. Returns the server's representation of the containerSource, and an error, if there is any. +func (c *containerSources) Update(containerSource *v1alpha1.ContainerSource) (result *v1alpha1.ContainerSource, err error) { + result = &v1alpha1.ContainerSource{} + err = c.client.Put(). + Namespace(c.ns). + Resource("containersources"). + Name(containerSource.Name). + Body(containerSource). + Do(). + Into(result) + return +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + +func (c *containerSources) UpdateStatus(containerSource *v1alpha1.ContainerSource) (result *v1alpha1.ContainerSource, err error) { + result = &v1alpha1.ContainerSource{} + err = c.client.Put(). + Namespace(c.ns). + Resource("containersources"). + Name(containerSource.Name). + SubResource("status"). + Body(containerSource). + Do(). + Into(result) + return +} + +// Delete takes name of the containerSource and deletes it. Returns an error if one occurs. +func (c *containerSources) Delete(name string, options *v1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("containersources"). + Name(name). + Body(options). + Do(). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *containerSources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("containersources"). + VersionedParams(&listOptions, scheme.ParameterCodec). + Body(options). + Do(). + Error() +} + +// Patch applies the patch and returns the patched containerSource. +func (c *containerSources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ContainerSource, err error) { + result = &v1alpha1.ContainerSource{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("containersources"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/pkg/client/clientset/versioned/typed/channels/v1alpha1/doc.go b/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/typed/sources/v1alpha1/doc.go similarity index 100% rename from pkg/client/clientset/versioned/typed/channels/v1alpha1/doc.go rename to vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/typed/sources/v1alpha1/doc.go diff --git a/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/typed/sources/v1alpha1/gcppubsubsource.go b/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/typed/sources/v1alpha1/gcppubsubsource.go new file mode 100644 index 00000000000..af8d095207e --- /dev/null +++ b/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/typed/sources/v1alpha1/gcppubsubsource.go @@ -0,0 +1,174 @@ +/* +Copyright 2018 The Knative 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. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + v1alpha1 "github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1" + scheme "github.com/knative/eventing-sources/pkg/client/clientset/versioned/scheme" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" +) + +// GcpPubSubSourcesGetter has a method to return a GcpPubSubSourceInterface. +// A group's client should implement this interface. +type GcpPubSubSourcesGetter interface { + GcpPubSubSources(namespace string) GcpPubSubSourceInterface +} + +// GcpPubSubSourceInterface has methods to work with GcpPubSubSource resources. +type GcpPubSubSourceInterface interface { + Create(*v1alpha1.GcpPubSubSource) (*v1alpha1.GcpPubSubSource, error) + Update(*v1alpha1.GcpPubSubSource) (*v1alpha1.GcpPubSubSource, error) + UpdateStatus(*v1alpha1.GcpPubSubSource) (*v1alpha1.GcpPubSubSource, error) + Delete(name string, options *v1.DeleteOptions) error + DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error + Get(name string, options v1.GetOptions) (*v1alpha1.GcpPubSubSource, error) + List(opts v1.ListOptions) (*v1alpha1.GcpPubSubSourceList, error) + Watch(opts v1.ListOptions) (watch.Interface, error) + Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.GcpPubSubSource, err error) + GcpPubSubSourceExpansion +} + +// gcpPubSubSources implements GcpPubSubSourceInterface +type gcpPubSubSources struct { + client rest.Interface + ns string +} + +// newGcpPubSubSources returns a GcpPubSubSources +func newGcpPubSubSources(c *SourcesV1alpha1Client, namespace string) *gcpPubSubSources { + return &gcpPubSubSources{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the gcpPubSubSource, and returns the corresponding gcpPubSubSource object, and an error if there is any. +func (c *gcpPubSubSources) Get(name string, options v1.GetOptions) (result *v1alpha1.GcpPubSubSource, err error) { + result = &v1alpha1.GcpPubSubSource{} + err = c.client.Get(). + Namespace(c.ns). + Resource("gcppubsubsources"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of GcpPubSubSources that match those selectors. +func (c *gcpPubSubSources) List(opts v1.ListOptions) (result *v1alpha1.GcpPubSubSourceList, err error) { + result = &v1alpha1.GcpPubSubSourceList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("gcppubsubsources"). + VersionedParams(&opts, scheme.ParameterCodec). + Do(). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested gcpPubSubSources. +func (c *gcpPubSubSources) Watch(opts v1.ListOptions) (watch.Interface, error) { + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("gcppubsubsources"). + VersionedParams(&opts, scheme.ParameterCodec). + Watch() +} + +// Create takes the representation of a gcpPubSubSource and creates it. Returns the server's representation of the gcpPubSubSource, and an error, if there is any. +func (c *gcpPubSubSources) Create(gcpPubSubSource *v1alpha1.GcpPubSubSource) (result *v1alpha1.GcpPubSubSource, err error) { + result = &v1alpha1.GcpPubSubSource{} + err = c.client.Post(). + Namespace(c.ns). + Resource("gcppubsubsources"). + Body(gcpPubSubSource). + Do(). + Into(result) + return +} + +// Update takes the representation of a gcpPubSubSource and updates it. Returns the server's representation of the gcpPubSubSource, and an error, if there is any. +func (c *gcpPubSubSources) Update(gcpPubSubSource *v1alpha1.GcpPubSubSource) (result *v1alpha1.GcpPubSubSource, err error) { + result = &v1alpha1.GcpPubSubSource{} + err = c.client.Put(). + Namespace(c.ns). + Resource("gcppubsubsources"). + Name(gcpPubSubSource.Name). + Body(gcpPubSubSource). + Do(). + Into(result) + return +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + +func (c *gcpPubSubSources) UpdateStatus(gcpPubSubSource *v1alpha1.GcpPubSubSource) (result *v1alpha1.GcpPubSubSource, err error) { + result = &v1alpha1.GcpPubSubSource{} + err = c.client.Put(). + Namespace(c.ns). + Resource("gcppubsubsources"). + Name(gcpPubSubSource.Name). + SubResource("status"). + Body(gcpPubSubSource). + Do(). + Into(result) + return +} + +// Delete takes name of the gcpPubSubSource and deletes it. Returns an error if one occurs. +func (c *gcpPubSubSources) Delete(name string, options *v1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("gcppubsubsources"). + Name(name). + Body(options). + Do(). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *gcpPubSubSources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("gcppubsubsources"). + VersionedParams(&listOptions, scheme.ParameterCodec). + Body(options). + Do(). + Error() +} + +// Patch applies the patch and returns the patched gcpPubSubSource. +func (c *gcpPubSubSources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.GcpPubSubSource, err error) { + result = &v1alpha1.GcpPubSubSource{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("gcppubsubsources"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/pkg/client/clientset/versioned/typed/flows/v1alpha1/generated_expansion.go b/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/typed/sources/v1alpha1/generated_expansion.go similarity index 82% rename from pkg/client/clientset/versioned/typed/flows/v1alpha1/generated_expansion.go rename to vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/typed/sources/v1alpha1/generated_expansion.go index 2e4de776975..eeb3f0886d9 100644 --- a/pkg/client/clientset/versioned/typed/flows/v1alpha1/generated_expansion.go +++ b/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/typed/sources/v1alpha1/generated_expansion.go @@ -18,4 +18,8 @@ limitations under the License. package v1alpha1 -type FlowExpansion interface{} +type ContainerSourceExpansion interface{} + +type GcpPubSubSourceExpansion interface{} + +type KubernetesEventSourceExpansion interface{} diff --git a/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/typed/sources/v1alpha1/kuberneteseventsource.go b/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/typed/sources/v1alpha1/kuberneteseventsource.go new file mode 100644 index 00000000000..75743b2e0dd --- /dev/null +++ b/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/typed/sources/v1alpha1/kuberneteseventsource.go @@ -0,0 +1,174 @@ +/* +Copyright 2018 The Knative 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. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + v1alpha1 "github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1" + scheme "github.com/knative/eventing-sources/pkg/client/clientset/versioned/scheme" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" +) + +// KubernetesEventSourcesGetter has a method to return a KubernetesEventSourceInterface. +// A group's client should implement this interface. +type KubernetesEventSourcesGetter interface { + KubernetesEventSources(namespace string) KubernetesEventSourceInterface +} + +// KubernetesEventSourceInterface has methods to work with KubernetesEventSource resources. +type KubernetesEventSourceInterface interface { + Create(*v1alpha1.KubernetesEventSource) (*v1alpha1.KubernetesEventSource, error) + Update(*v1alpha1.KubernetesEventSource) (*v1alpha1.KubernetesEventSource, error) + UpdateStatus(*v1alpha1.KubernetesEventSource) (*v1alpha1.KubernetesEventSource, error) + Delete(name string, options *v1.DeleteOptions) error + DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error + Get(name string, options v1.GetOptions) (*v1alpha1.KubernetesEventSource, error) + List(opts v1.ListOptions) (*v1alpha1.KubernetesEventSourceList, error) + Watch(opts v1.ListOptions) (watch.Interface, error) + Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.KubernetesEventSource, err error) + KubernetesEventSourceExpansion +} + +// kubernetesEventSources implements KubernetesEventSourceInterface +type kubernetesEventSources struct { + client rest.Interface + ns string +} + +// newKubernetesEventSources returns a KubernetesEventSources +func newKubernetesEventSources(c *SourcesV1alpha1Client, namespace string) *kubernetesEventSources { + return &kubernetesEventSources{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the kubernetesEventSource, and returns the corresponding kubernetesEventSource object, and an error if there is any. +func (c *kubernetesEventSources) Get(name string, options v1.GetOptions) (result *v1alpha1.KubernetesEventSource, err error) { + result = &v1alpha1.KubernetesEventSource{} + err = c.client.Get(). + Namespace(c.ns). + Resource("kuberneteseventsources"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of KubernetesEventSources that match those selectors. +func (c *kubernetesEventSources) List(opts v1.ListOptions) (result *v1alpha1.KubernetesEventSourceList, err error) { + result = &v1alpha1.KubernetesEventSourceList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("kuberneteseventsources"). + VersionedParams(&opts, scheme.ParameterCodec). + Do(). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested kubernetesEventSources. +func (c *kubernetesEventSources) Watch(opts v1.ListOptions) (watch.Interface, error) { + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("kuberneteseventsources"). + VersionedParams(&opts, scheme.ParameterCodec). + Watch() +} + +// Create takes the representation of a kubernetesEventSource and creates it. Returns the server's representation of the kubernetesEventSource, and an error, if there is any. +func (c *kubernetesEventSources) Create(kubernetesEventSource *v1alpha1.KubernetesEventSource) (result *v1alpha1.KubernetesEventSource, err error) { + result = &v1alpha1.KubernetesEventSource{} + err = c.client.Post(). + Namespace(c.ns). + Resource("kuberneteseventsources"). + Body(kubernetesEventSource). + Do(). + Into(result) + return +} + +// Update takes the representation of a kubernetesEventSource and updates it. Returns the server's representation of the kubernetesEventSource, and an error, if there is any. +func (c *kubernetesEventSources) Update(kubernetesEventSource *v1alpha1.KubernetesEventSource) (result *v1alpha1.KubernetesEventSource, err error) { + result = &v1alpha1.KubernetesEventSource{} + err = c.client.Put(). + Namespace(c.ns). + Resource("kuberneteseventsources"). + Name(kubernetesEventSource.Name). + Body(kubernetesEventSource). + Do(). + Into(result) + return +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + +func (c *kubernetesEventSources) UpdateStatus(kubernetesEventSource *v1alpha1.KubernetesEventSource) (result *v1alpha1.KubernetesEventSource, err error) { + result = &v1alpha1.KubernetesEventSource{} + err = c.client.Put(). + Namespace(c.ns). + Resource("kuberneteseventsources"). + Name(kubernetesEventSource.Name). + SubResource("status"). + Body(kubernetesEventSource). + Do(). + Into(result) + return +} + +// Delete takes name of the kubernetesEventSource and deletes it. Returns an error if one occurs. +func (c *kubernetesEventSources) Delete(name string, options *v1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("kuberneteseventsources"). + Name(name). + Body(options). + Do(). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *kubernetesEventSources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("kuberneteseventsources"). + VersionedParams(&listOptions, scheme.ParameterCodec). + Body(options). + Do(). + Error() +} + +// Patch applies the patch and returns the patched kubernetesEventSource. +func (c *kubernetesEventSources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.KubernetesEventSource, err error) { + result = &v1alpha1.KubernetesEventSource{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("kuberneteseventsources"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/pkg/client/clientset/versioned/typed/channels/v1alpha1/channels_client.go b/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/typed/sources/v1alpha1/sources_client.go similarity index 53% rename from pkg/client/clientset/versioned/typed/channels/v1alpha1/channels_client.go rename to vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/typed/sources/v1alpha1/sources_client.go index d99d1390cef..94601cf0321 100644 --- a/pkg/client/clientset/versioned/typed/channels/v1alpha1/channels_client.go +++ b/vendor/github.com/knative/eventing-sources/pkg/client/clientset/versioned/typed/sources/v1alpha1/sources_client.go @@ -19,43 +19,38 @@ limitations under the License. package v1alpha1 import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/channels/v1alpha1" - "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" + v1alpha1 "github.com/knative/eventing-sources/pkg/apis/sources/v1alpha1" + "github.com/knative/eventing-sources/pkg/client/clientset/versioned/scheme" serializer "k8s.io/apimachinery/pkg/runtime/serializer" rest "k8s.io/client-go/rest" ) -type ChannelsV1alpha1Interface interface { +type SourcesV1alpha1Interface interface { RESTClient() rest.Interface - BusesGetter - ChannelsGetter - ClusterBusesGetter - SubscriptionsGetter + ContainerSourcesGetter + GcpPubSubSourcesGetter + KubernetesEventSourcesGetter } -// ChannelsV1alpha1Client is used to interact with features provided by the channels.knative.dev group. -type ChannelsV1alpha1Client struct { +// SourcesV1alpha1Client is used to interact with features provided by the sources.eventing.knative.dev group. +type SourcesV1alpha1Client struct { restClient rest.Interface } -func (c *ChannelsV1alpha1Client) Buses(namespace string) BusInterface { - return newBuses(c, namespace) +func (c *SourcesV1alpha1Client) ContainerSources(namespace string) ContainerSourceInterface { + return newContainerSources(c, namespace) } -func (c *ChannelsV1alpha1Client) Channels(namespace string) ChannelInterface { - return newChannels(c, namespace) +func (c *SourcesV1alpha1Client) GcpPubSubSources(namespace string) GcpPubSubSourceInterface { + return newGcpPubSubSources(c, namespace) } -func (c *ChannelsV1alpha1Client) ClusterBuses() ClusterBusInterface { - return newClusterBuses(c) +func (c *SourcesV1alpha1Client) KubernetesEventSources(namespace string) KubernetesEventSourceInterface { + return newKubernetesEventSources(c, namespace) } -func (c *ChannelsV1alpha1Client) Subscriptions(namespace string) SubscriptionInterface { - return newSubscriptions(c, namespace) -} - -// NewForConfig creates a new ChannelsV1alpha1Client for the given config. -func NewForConfig(c *rest.Config) (*ChannelsV1alpha1Client, error) { +// NewForConfig creates a new SourcesV1alpha1Client for the given config. +func NewForConfig(c *rest.Config) (*SourcesV1alpha1Client, error) { config := *c if err := setConfigDefaults(&config); err != nil { return nil, err @@ -64,12 +59,12 @@ func NewForConfig(c *rest.Config) (*ChannelsV1alpha1Client, error) { if err != nil { return nil, err } - return &ChannelsV1alpha1Client{client}, nil + return &SourcesV1alpha1Client{client}, nil } -// NewForConfigOrDie creates a new ChannelsV1alpha1Client for the given config and +// NewForConfigOrDie creates a new SourcesV1alpha1Client for the given config and // panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *ChannelsV1alpha1Client { +func NewForConfigOrDie(c *rest.Config) *SourcesV1alpha1Client { client, err := NewForConfig(c) if err != nil { panic(err) @@ -77,9 +72,9 @@ func NewForConfigOrDie(c *rest.Config) *ChannelsV1alpha1Client { return client } -// New creates a new ChannelsV1alpha1Client for the given RESTClient. -func New(c rest.Interface) *ChannelsV1alpha1Client { - return &ChannelsV1alpha1Client{c} +// New creates a new SourcesV1alpha1Client for the given RESTClient. +func New(c rest.Interface) *SourcesV1alpha1Client { + return &SourcesV1alpha1Client{c} } func setConfigDefaults(config *rest.Config) error { @@ -97,7 +92,7 @@ func setConfigDefaults(config *rest.Config) error { // RESTClient returns a RESTClient that is used to communicate // with API server by this client implementation. -func (c *ChannelsV1alpha1Client) RESTClient() rest.Interface { +func (c *SourcesV1alpha1Client) RESTClient() rest.Interface { if c == nil { return nil } diff --git a/vendor/github.com/knative/pkg/apis/duck/patch.go b/vendor/github.com/knative/pkg/apis/duck/patch.go index ed06d7da7c6..386aa1f32eb 100644 --- a/vendor/github.com/knative/pkg/apis/duck/patch.go +++ b/vendor/github.com/knative/pkg/apis/duck/patch.go @@ -19,21 +19,37 @@ package duck import ( "encoding/json" + jsonmergepatch "github.com/evanphx/json-patch" "github.com/mattbaird/jsonpatch" ) -func CreatePatch(before, after interface{}) (JSONPatch, error) { - // Marshal the before and after. +func marshallBeforeAfter(before, after interface{}) ([]byte, []byte, error) { rawBefore, err := json.Marshal(before) if err != nil { - return nil, err + return nil, nil, err } rawAfter, err := json.Marshal(after) + if err != nil { + return rawBefore, nil, err + } + + return rawBefore, rawAfter, nil +} + +func CreateMergePatch(before, after interface{}) ([]byte, error) { + rawBefore, rawAfter, err := marshallBeforeAfter(before, after) if err != nil { return nil, err } + return jsonmergepatch.CreateMergePatch(rawBefore, rawAfter) +} +func CreatePatch(before, after interface{}) (JSONPatch, error) { + rawBefore, rawAfter, err := marshallBeforeAfter(before, after) + if err != nil { + return nil, err + } return jsonpatch.CreatePatch(rawBefore, rawAfter) } diff --git a/vendor/github.com/knative/pkg/apis/duck/v1alpha1/addressable_types.go b/vendor/github.com/knative/pkg/apis/duck/v1alpha1/addressable_types.go new file mode 100644 index 00000000000..0bf1f986dc0 --- /dev/null +++ b/vendor/github.com/knative/pkg/apis/duck/v1alpha1/addressable_types.go @@ -0,0 +1,96 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + + "github.com/knative/pkg/apis" + "github.com/knative/pkg/apis/duck" +) + +// Addressable provides a generic mechanism for a custom resource +// definition to indicate a destination for message delivery. +// (Currently, only hostname is supported, and HTTP is implied. In the +// future, additional schemes may be supported, and path components +// ala UI may also be supported.) + +// Addressable is the schema for the destination information. This is +// typically stored in the object's `status`, as this information may +// be generated by the controller. +type Addressable struct { + Hostname string `json:"hostname,omitempty"` +} + + +// Addressable is an Implementable "duck type". +var _ duck.Implementable = (*Addressable)(nil) + +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// AddressableType is a skeleton type wrapping Addressable in the manner we expect +// resource writers defining compatible resources to embed it. We will +// typically use this type to deserialize Addressable ObjectReferences and +// access the Addressable data. This is not a real resource. +type AddressableType struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Status AddressStatus `json:"status"` +} + +// AddressStatus shows how we expect folks to embed Addressable in +// their Status field. +type AddressStatus struct { + Address *Addressable `json:"address,omitempty"` +} + +// Verify AddressableType resources meet duck contracts. +var _ duck.Populatable = (*AddressableType)(nil) +var _ apis.Listable = (*AddressableType)(nil) + +// GetFullType implements duck.Implementable +func (_ *Addressable) GetFullType() duck.Populatable { + return &AddressableType{} +} + +// Populate implements duck.Populatable +func (t *AddressableType) Populate() { + t.Status = AddressStatus{ + &Addressable{ + // Populate ALL fields + Hostname: "this is not empty", + }, + } +} + +// GetListType implements apis.Listable +func (r *AddressableType) GetListType() runtime.Object { + return &AddressableTypeList{} +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// AddressableTypeList is a list of AddressableType resources +type AddressableTypeList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata"` + + Items []AddressableType `json:"items"` +} diff --git a/vendor/github.com/knative/pkg/apis/duck/v1alpha1/channelable_types.go b/vendor/github.com/knative/pkg/apis/duck/v1alpha1/channelable_types.go deleted file mode 100644 index 7e7ffd9ada1..00000000000 --- a/vendor/github.com/knative/pkg/apis/duck/v1alpha1/channelable_types.go +++ /dev/null @@ -1,104 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - - "github.com/knative/pkg/apis" - "github.com/knative/pkg/apis/duck" -) - -// Channelable is the schema for the channelable portion of the spec -// section of the resource. -type Channelable struct { - // TODO: What is actually required here for Channel spec. - // This is the list of subscriptions for this channel. - Subscribers []ChannelSubscriberSpec `json:"subscribers,omitempty"` -} - -// ChannelSubscriberSpec defines a single subscriber to a Channel. -// CallableDomain is the endpoint for the call -// SinkableDomain is the endpoint for the result -// One of them must be present -type ChannelSubscriberSpec struct { - // +optional - CallableDomain string `json:"callableDomain,omitempty"` - // +optional - SinkableDomain string `json:"sinkableDomain,omitempty"` -} - - -// Channelable is an Implementable "duck type". -var _ duck.Implementable = (*Channelable)(nil) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// Channel is a skeleton type wrapping Channelable in the manner we expect -// resource writers defining compatible resources to embed it. We will -// typically use this type to deserialize Channelable ObjectReferences and -// access the Channelable data. This is not a real resource. -type Channel struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - // ChannelSpec is the part where Channelable object is - // configured as to be compatible with Channelable contract. - Spec ChannelSpec `json:"spec"` -} - -// ChannelSpec shows how we expect folks to embed Channelable in -// their Spec field. -type ChannelSpec struct { - Channelable *Channelable `json:"channelable,omitempty"` -} - -// In order for Channelable to be Implementable, Channel must be Populatable. -var _ duck.Populatable = (*Channel)(nil) - -// Ensure Channel satisfies apis.Listable -var _ apis.Listable = (*Channel)(nil) - -// GetFullType implements duck.Implementable -func (_ *Channelable) GetFullType() duck.Populatable { - return &Channel{} -} - -// Populate implements duck.Populatable -func (t *Channel) Populate() { - t.Spec.Channelable = &Channelable{ - // Populate ALL fields - Subscribers: []ChannelSubscriberSpec{{"call1", "sink2"}, {"call2", "sink2"}}, - } -} - -// GetListType implements apis.Listable -func (r *Channel) GetListType() runtime.Object { - return &ChannelList{} -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// ChannelList is a list of Channel resources -type ChannelList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []Channel `json:"items"` -} diff --git a/vendor/github.com/knative/pkg/apis/duck/v1alpha1/condition_set.go b/vendor/github.com/knative/pkg/apis/duck/v1alpha1/condition_set.go index 30b76a5f667..e330970bd0b 100644 --- a/vendor/github.com/knative/pkg/apis/duck/v1alpha1/condition_set.go +++ b/vendor/github.com/knative/pkg/apis/duck/v1alpha1/condition_set.go @@ -62,7 +62,7 @@ type ConditionManager interface { SetCondition(new Condition) // MarkTrue sets the status of t to true, and then marks the happy condition to - // true if all other dependents are also true. + // true if all dependents are true. MarkTrue(t ConditionType) // MarkUnknown sets the status of t to Unknown and also sets the happy condition @@ -82,12 +82,14 @@ type ConditionManager interface { // NewLivingConditionSet returns a ConditionSet to hold the conditions for the // living resource. ConditionReady is used as the happy condition. +// The set of condition types provided are those of the terminal subconditions. func NewLivingConditionSet(d ...ConditionType) ConditionSet { return newConditionSet(ConditionReady, d...) } // NewBatchConditionSet returns a ConditionSet to hold the conditions for the // batch resource. ConditionSucceeded is used as the happy condition. +// The set of condition types provided are those of the terminal subconditions. func NewBatchConditionSet(d ...ConditionType) ConditionSet { return newConditionSet(ConditionSucceeded, d...) } @@ -209,13 +211,30 @@ func (r conditionsImpl) SetCondition(new Condition) { r.accessor.SetConditions(conditions) } +func (r conditionsImpl) isTerminal(t ConditionType) bool { + for _, cond := range append(r.dependents, r.happy) { + if cond == t { + return true + } + } + return false +} + +func (r conditionsImpl) severity(t ConditionType) ConditionSeverity { + if r.isTerminal(t) { + return ConditionSeverityError + } + return ConditionSeverityInfo +} + // MarkTrue sets the status of t to true, and then marks the happy condition to // true if all other dependents are also true. func (r conditionsImpl) MarkTrue(t ConditionType) { // set the specified condition r.SetCondition(Condition{ - Type: t, - Status: corev1.ConditionTrue, + Type: t, + Status: corev1.ConditionTrue, + Severity: r.severity(t), }) // check the dependents. @@ -229,8 +248,9 @@ func (r conditionsImpl) MarkTrue(t ConditionType) { // set the happy condition r.SetCondition(Condition{ - Type: r.happy, - Status: corev1.ConditionTrue, + Type: r.happy, + Status: corev1.ConditionTrue, + Severity: r.severity(r.happy), }) } @@ -239,13 +259,15 @@ func (r conditionsImpl) MarkTrue(t ConditionType) { func (r conditionsImpl) MarkUnknown(t ConditionType, reason, messageFormat string, messageA ...interface{}) { // set the specified condition r.SetCondition(Condition{ - Type: t, - Status: corev1.ConditionUnknown, - Reason: reason, - Message: fmt.Sprintf(messageFormat, messageA...), + Type: t, + Status: corev1.ConditionUnknown, + Reason: reason, + Message: fmt.Sprintf(messageFormat, messageA...), + Severity: r.severity(t), }) // check the dependents. + isDependent := false for _, cond := range r.dependents { c := r.GetCondition(cond) // Failed conditions trump Unknown conditions @@ -257,28 +279,39 @@ func (r conditionsImpl) MarkUnknown(t ConditionType, reason, messageFormat strin } return } + if cond == t { + isDependent = true + } } - // set the happy condition - r.SetCondition(Condition{ - Type: r.happy, - Status: corev1.ConditionUnknown, - Reason: reason, - Message: fmt.Sprintf(messageFormat, messageA...), - }) + if isDependent { + // set the happy condition, if it is one of our dependent subconditions. + r.SetCondition(Condition{ + Type: r.happy, + Status: corev1.ConditionUnknown, + Reason: reason, + Message: fmt.Sprintf(messageFormat, messageA...), + Severity: r.severity(r.happy), + }) + } } // MarkFalse sets the status of t and the happy condition to False. func (r conditionsImpl) MarkFalse(t ConditionType, reason, messageFormat string, messageA ...interface{}) { - for _, t := range []ConditionType{ - t, - r.happy, - } { + types := []ConditionType{t} + for _, cond := range r.dependents { + if cond == t { + types = append(types, r.happy) + } + } + + for _, t := range types { r.SetCondition(Condition{ - Type: t, - Status: corev1.ConditionFalse, - Reason: reason, - Message: fmt.Sprintf(messageFormat, messageA...), + Type: t, + Status: corev1.ConditionFalse, + Reason: reason, + Message: fmt.Sprintf(messageFormat, messageA...), + Severity: r.severity(t), }) } } @@ -295,8 +328,9 @@ func (r conditionsImpl) InitializeConditions() { func (r conditionsImpl) InitializeCondition(t ConditionType) { if c := r.GetCondition(t); c == nil { r.SetCondition(Condition{ - Type: t, - Status: corev1.ConditionUnknown, + Type: t, + Status: corev1.ConditionUnknown, + Severity: r.severity(t), }) } } diff --git a/vendor/github.com/knative/pkg/apis/duck/v1alpha1/conditions_types.go b/vendor/github.com/knative/pkg/apis/duck/v1alpha1/conditions_types.go index 44b99921051..0dbad3397e0 100644 --- a/vendor/github.com/knative/pkg/apis/duck/v1alpha1/conditions_types.go +++ b/vendor/github.com/knative/pkg/apis/duck/v1alpha1/conditions_types.go @@ -42,6 +42,21 @@ const ( ConditionSucceeded ConditionType = "Succeeded" ) +// ConditionSeverity expresses the severity of a Condition Type failing. +type ConditionSeverity string + +const ( + // ConditionSeverityError specifies that a failure of a condition type + // should be viewed as an error. + ConditionSeverityError ConditionSeverity = "Error" + // ConditionSeverityWarning specifies that a failure of a condition type + // should be viewed as a warning, but that things could still work. + ConditionSeverityWarning ConditionSeverity = "Warning" + // ConditionSeverityInfo specifies that a failure of a condition type + // should be viewed as purely informational, and that things could still work. + ConditionSeverityInfo ConditionSeverity = "Info" +) + // Conditions defines a readiness condition for a Knative resource. // See: https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#typical-status-properties // +k8s:deepcopy-gen=true @@ -54,6 +69,11 @@ type Condition struct { // +required Status corev1.ConditionStatus `json:"status" description:"status of the condition, one of True, False, Unknown"` + // Severity with which to treat failures of this type of condition. + // When this is not specified, it defaults to Error. + // +optional + Severity ConditionSeverity `json:"severity,omitempty" description:"how to interpret failures of this condition, one of Error, Warning, Info"` + // LastTransitionTime is the last time the condition transitioned from one status to another. // We use VolatileTime in place of metav1.Time to exclude this from creating equality.Semantic // differences (all other things held constant). @@ -93,7 +113,6 @@ func (c *Condition) IsUnknown() bool { return c.Status == corev1.ConditionUnknown } - // Conditions is an Implementable "duck type". var _ duck.Implementable = (*Conditions)(nil) diff --git a/vendor/github.com/knative/pkg/apis/duck/v1alpha1/legacy_targetable_types.go b/vendor/github.com/knative/pkg/apis/duck/v1alpha1/legacy_targetable_types.go index 6bfc0881805..ee50201e83c 100644 --- a/vendor/github.com/knative/pkg/apis/duck/v1alpha1/legacy_targetable_types.go +++ b/vendor/github.com/knative/pkg/apis/duck/v1alpha1/legacy_targetable_types.go @@ -24,19 +24,19 @@ import ( "github.com/knative/pkg/apis/duck" ) -// LegacyTargetable left around until we migrate to Targetable in the -// dependent resources. Targetable has more structure in the way it +// LegacyTargetable left around until we migrate to Addressable in the +// dependent resources. Addressable has more structure in the way it // defines the fields. LegacyTargetable only assumed a single string // in the Status field and we're moving towards defining proper structs // under Status rather than strings. // This is to support existing resources until they migrate. // -// Do not use this for anything new, use Targetable +// Do not use this for anything new, use Addressable -// LegacyTargetable is the old schema for the targetable portion +// LegacyTargetable is the old schema for the addressable portion // of the payload // -// For new resources use Targetable. +// For new resources use Addressable. type LegacyTargetable struct { DomainInternal string `json:"domainInternal,omitempty"` } diff --git a/vendor/github.com/knative/pkg/apis/duck/v1alpha1/register.go b/vendor/github.com/knative/pkg/apis/duck/v1alpha1/register.go index f3bfc5ae1d1..a0264e576e0 100644 --- a/vendor/github.com/knative/pkg/apis/duck/v1alpha1/register.go +++ b/vendor/github.com/knative/pkg/apis/duck/v1alpha1/register.go @@ -45,20 +45,16 @@ var ( func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes( SchemeGroupVersion, - &Channel{}, - (&Channel{}).GetListType(), &KResource{}, (&KResource{}).GetListType(), &Generational{}, (&Generational{}).GetListType(), + &AddressableType{}, + (&AddressableType{}).GetListType(), &Target{}, (&Target{}).GetListType(), &LegacyTarget{}, (&LegacyTarget{}).GetListType(), - &Sink{}, - (&Sink{}).GetListType(), - &Subscription{}, - (&Subscription{}).GetListType(), ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil diff --git a/vendor/github.com/knative/pkg/apis/duck/v1alpha1/targetable_types.go b/vendor/github.com/knative/pkg/apis/duck/v1alpha1/retired_targetable_types.go similarity index 84% rename from vendor/github.com/knative/pkg/apis/duck/v1alpha1/targetable_types.go rename to vendor/github.com/knative/pkg/apis/duck/v1alpha1/retired_targetable_types.go index 5cd454ba52b..695e11c3f65 100644 --- a/vendor/github.com/knative/pkg/apis/duck/v1alpha1/targetable_types.go +++ b/vendor/github.com/knative/pkg/apis/duck/v1alpha1/retired_targetable_types.go @@ -24,11 +24,15 @@ import ( "github.com/knative/pkg/apis/duck" ) -// Targetable is very similar concept as Sinkable. However, at the -// transport level they have different contracts and hence Sinkable -// and Targetable are two distinct resources. - -// Targetable is the schema for the targetable portion of the payload +// Targetable is an earlier version of the Callable interface. +// Callable is a higher-level interface which implements Addressable +// but further promises that the destination may synchronously return +// response messages in reply to a message. +// +// Targetable implementations should instead implement Addressable and +// include an `eventing.knative.dev/returns=any` annotation. + +// Targetable is retired; implement Addressable for now. type Targetable struct { DomainInternal string `json:"domainInternal,omitempty"` } diff --git a/vendor/github.com/knative/pkg/apis/duck/v1alpha1/sinkable_types.go b/vendor/github.com/knative/pkg/apis/duck/v1alpha1/sinkable_types.go deleted file mode 100644 index 2ad0ab5e3e9..00000000000 --- a/vendor/github.com/knative/pkg/apis/duck/v1alpha1/sinkable_types.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - - "github.com/knative/pkg/apis" - "github.com/knative/pkg/apis/duck" -) - -// Sinkable is very similar concept as Targetable. However, at the -// transport level they have different contracts and hence Sinkable -// and Targetable are two distinct resources. - -// Sinkable is the schema for the sinkable portion of the payload -type Sinkable struct { - DomainInternal string `json:"domainInternal,omitempty"` -} - - -// Sinkable is an Implementable "duck type". -var _ duck.Implementable = (*Sinkable)(nil) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// Sink is a skeleton type wrapping Sinkable in the manner we expect -// resource writers defining compatible resources to embed it. We will -// typically use this type to deserialize Sinkable ObjectReferences and -// access the Sinkable data. This is not a real resource. -type Sink struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Status SinkStatus `json:"status"` -} - -// SinkStatus shows how we expect folks to embed Sinkable in -// their Status field. -type SinkStatus struct { - Sinkable *Sinkable `json:"sinkable,omitempty"` -} - -// In order for Sinkable to be Implementable, Sink must be Populatable. -var _ duck.Populatable = (*Sink)(nil) - -// Ensure Sink satisfies apis.Listable -var _ apis.Listable = (*Sink)(nil) - -// GetFullType implements duck.Implementable -func (_ *Sinkable) GetFullType() duck.Populatable { - return &Sink{} -} - -// Populate implements duck.Populatable -func (t *Sink) Populate() { - t.Status = SinkStatus{ - &Sinkable{ - // Populate ALL fields - DomainInternal: "this is not empty", - }, - } -} - -// GetListType implements apis.Listable -func (r *Sink) GetListType() runtime.Object { - return &SinkList{} -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// SinkList is a list of Sink resources -type SinkList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []Sink `json:"items"` -} diff --git a/vendor/github.com/knative/pkg/apis/duck/v1alpha1/subscribable_types.go b/vendor/github.com/knative/pkg/apis/duck/v1alpha1/subscribable_types.go deleted file mode 100644 index e8d03f890d4..00000000000 --- a/vendor/github.com/knative/pkg/apis/duck/v1alpha1/subscribable_types.go +++ /dev/null @@ -1,105 +0,0 @@ -/* -Copyright 2018 The Knative Authors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - - "github.com/knative/pkg/apis" - "github.com/knative/pkg/apis/duck" -) - -// Subscribable is the schema for the subscribable portion of the payload. -// It is a reference to actual object that implements Channelable duck -// type. -type Subscribable struct { - // Channelable is a reference to the actual resource - // that provides the ability to perform Subscription capabilities. - // This may point to object itself (for example Channel) or to another - // object providing the actual capabilities.. - Channelable corev1.ObjectReference `json:"channelable,omitempty"` -} - - -// Subscribable is an Implementable "duck type". -var _ duck.Implementable = (*Subscribable)(nil) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// Subscription is a skeleton type wrapping the notion that this object -// can be subscribed to. SubscriptionStatus provides the reference -// (in a form of Subscribable) to the object that you can actually create -// a subscription to. -// We will typically use this type to deserialize Subscription objects -// to access the Subscripion data. This is not a real resource. -type Subscription struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - // SubscriptionStatus is the part of the Status where a Subscribable - // object points to the underlying Channelable object that fullfills - // the SubscribableSpec contract. Note that this can be a self-link - // for example for concrete Channel implementations. - Status SubscriptionStatus `json:"status"` -} - -// SubscriptionStatus shows how we expect folks to embed Subscribable in -// their Status field. -type SubscriptionStatus struct { - Subscribable *Subscribable `json:"subscribable,omitempty"` -} - -// In order for Subscribable to be Implementable, Subscribable must be Populatable. -var _ duck.Populatable = (*Subscription)(nil) - -// Ensure Subscription satisfies apis.Listable -var _ apis.Listable = (*Subscription)(nil) - -// GetFullType implements duck.Implementable -func (_ *Subscribable) GetFullType() duck.Populatable { - return &Subscription{} -} - -// Populate implements duck.Populatable -func (t *Subscription) Populate() { - t.Status.Subscribable = &Subscribable{ - // Populate ALL fields - Channelable: corev1.ObjectReference{ - Name: "placeholdername", - APIVersion: "apiversionhere", - Kind: "ChannelKindHere", - }, - } -} - -// GetListType implements apis.Listable -func (r *Subscription) GetListType() runtime.Object { - return &SubscriptionList{} -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// SubscribableList is a list of Subscribable resources -type SubscriptionList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []Subscription `json:"items"` -} diff --git a/vendor/github.com/knative/pkg/apis/duck/v1alpha1/zz_generated.deepcopy.go b/vendor/github.com/knative/pkg/apis/duck/v1alpha1/zz_generated.deepcopy.go index 203f1ec5b31..731c7059dc0 100644 --- a/vendor/github.com/knative/pkg/apis/duck/v1alpha1/zz_generated.deepcopy.go +++ b/vendor/github.com/knative/pkg/apis/duck/v1alpha1/zz_generated.deepcopy.go @@ -25,123 +25,102 @@ import ( ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Channel) DeepCopyInto(out *Channel) { +func (in *AddressStatus) DeepCopyInto(out *AddressStatus) { *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) + if in.Address != nil { + in, out := &in.Address, &out.Address + *out = new(Addressable) + **out = **in + } return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Channel. -func (in *Channel) DeepCopy() *Channel { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AddressStatus. +func (in *AddressStatus) DeepCopy() *AddressStatus { if in == nil { return nil } - out := new(Channel) + out := new(AddressStatus) in.DeepCopyInto(out) return out } -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Channel) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ChannelList) DeepCopyInto(out *ChannelList) { +func (in *Addressable) DeepCopyInto(out *Addressable) { *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Channel, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChannelList. -func (in *ChannelList) DeepCopy() *ChannelList { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Addressable. +func (in *Addressable) DeepCopy() *Addressable { if in == nil { return nil } - out := new(ChannelList) + out := new(Addressable) in.DeepCopyInto(out) return out } -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ChannelList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ChannelSpec) DeepCopyInto(out *ChannelSpec) { +func (in *AddressableType) DeepCopyInto(out *AddressableType) { *out = *in - if in.Channelable != nil { - in, out := &in.Channelable, &out.Channelable - *out = new(Channelable) - (*in).DeepCopyInto(*out) - } + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Status.DeepCopyInto(&out.Status) return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChannelSpec. -func (in *ChannelSpec) DeepCopy() *ChannelSpec { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AddressableType. +func (in *AddressableType) DeepCopy() *AddressableType { if in == nil { return nil } - out := new(ChannelSpec) + out := new(AddressableType) in.DeepCopyInto(out) return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ChannelSubscriberSpec) DeepCopyInto(out *ChannelSubscriberSpec) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChannelSubscriberSpec. -func (in *ChannelSubscriberSpec) DeepCopy() *ChannelSubscriberSpec { - if in == nil { - return nil +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *AddressableType) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c } - out := new(ChannelSubscriberSpec) - in.DeepCopyInto(out) - return out + return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Channelable) DeepCopyInto(out *Channelable) { +func (in *AddressableTypeList) DeepCopyInto(out *AddressableTypeList) { *out = *in - if in.Subscribers != nil { - in, out := &in.Subscribers, &out.Subscribers - *out = make([]ChannelSubscriberSpec, len(*in)) - copy(*out, *in) + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]AddressableType, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } } return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Channelable. -func (in *Channelable) DeepCopy() *Channelable { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AddressableTypeList. +func (in *AddressableTypeList) DeepCopy() *AddressableTypeList { if in == nil { return nil } - out := new(Channelable) + out := new(AddressableTypeList) in.DeepCopyInto(out) return out } +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *AddressableTypeList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Condition) DeepCopyInto(out *Condition) { *out = *in @@ -416,201 +395,6 @@ func (in *LegacyTargetable) DeepCopy() *LegacyTargetable { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Sink) DeepCopyInto(out *Sink) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Sink. -func (in *Sink) DeepCopy() *Sink { - if in == nil { - return nil - } - out := new(Sink) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Sink) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SinkList) DeepCopyInto(out *SinkList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Sink, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SinkList. -func (in *SinkList) DeepCopy() *SinkList { - if in == nil { - return nil - } - out := new(SinkList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *SinkList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SinkStatus) DeepCopyInto(out *SinkStatus) { - *out = *in - if in.Sinkable != nil { - in, out := &in.Sinkable, &out.Sinkable - *out = new(Sinkable) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SinkStatus. -func (in *SinkStatus) DeepCopy() *SinkStatus { - if in == nil { - return nil - } - out := new(SinkStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Sinkable) DeepCopyInto(out *Sinkable) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Sinkable. -func (in *Sinkable) DeepCopy() *Sinkable { - if in == nil { - return nil - } - out := new(Sinkable) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Subscribable) DeepCopyInto(out *Subscribable) { - *out = *in - out.Channelable = in.Channelable - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Subscribable. -func (in *Subscribable) DeepCopy() *Subscribable { - if in == nil { - return nil - } - out := new(Subscribable) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Subscription) DeepCopyInto(out *Subscription) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Subscription. -func (in *Subscription) DeepCopy() *Subscription { - if in == nil { - return nil - } - out := new(Subscription) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Subscription) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SubscriptionList) DeepCopyInto(out *SubscriptionList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Subscription, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SubscriptionList. -func (in *SubscriptionList) DeepCopy() *SubscriptionList { - if in == nil { - return nil - } - out := new(SubscriptionList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *SubscriptionList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SubscriptionStatus) DeepCopyInto(out *SubscriptionStatus) { - *out = *in - if in.Subscribable != nil { - in, out := &in.Subscribable, &out.Subscribable - *out = new(Subscribable) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SubscriptionStatus. -func (in *SubscriptionStatus) DeepCopy() *SubscriptionStatus { - if in == nil { - return nil - } - out := new(SubscriptionStatus) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Target) DeepCopyInto(out *Target) { *out = *in diff --git a/vendor/github.com/knative/pkg/apis/duck/verify.go b/vendor/github.com/knative/pkg/apis/duck/verify.go index b55efa09317..d53421b0464 100644 --- a/vendor/github.com/knative/pkg/apis/duck/verify.go +++ b/vendor/github.com/knative/pkg/apis/duck/verify.go @@ -23,7 +23,7 @@ import ( "github.com/google/go-cmp/cmp" ) -// Implementable in implemented by the Fooable duck type that consumers +// Implementable is implemented by the Fooable duck type that consumers // are expected to embed as a `.status.fooable` field. type Implementable interface { // GetFullType returns an instance of a full resource wrapping diff --git a/vendor/github.com/knative/pkg/apis/field_error.go b/vendor/github.com/knative/pkg/apis/field_error.go index 59cd1215a52..023db789efa 100644 --- a/vendor/github.com/knative/pkg/apis/field_error.go +++ b/vendor/github.com/knative/pkg/apis/field_error.go @@ -30,7 +30,7 @@ const CurrentField = "" // specific fields in a manner suitable for use in a recursive walk, so // that errors contain the appropriate field context. // FieldError methods are non-mutating. -// +k8s:deepcopy-gen=false +// +k8s:deepcopy-gen=true type FieldError struct { Message string Paths []string @@ -54,18 +54,21 @@ func (fe *FieldError) ViaField(prefix ...string) *FieldError { if fe == nil { return nil } - newErr := &FieldError{} - for _, e := range fe.getNormalizedErrors() { - // Prepend the Prefix to existing errors. - newPaths := make([]string, 0, len(e.Paths)) - for _, oldPath := range e.Paths { - newPaths = append(newPaths, flatten(append(prefix, oldPath))) - } - sort.Slice(newPaths, func(i, j int) bool { return newPaths[i] < newPaths[j] }) - e.Paths = newPaths + // Copy over message and details, paths will be updated and errors come + // along using .Also(). + newErr := &FieldError{ + Message: fe.Message, + Details: fe.Details, + } - // Append the mutated error to the errors list. - newErr = newErr.Also(&e) + // Prepend the Prefix to existing errors. + newPaths := make([]string, 0, len(fe.Paths)) + for _, oldPath := range fe.Paths { + newPaths = append(newPaths, flatten(append(prefix, oldPath))) + } + newErr.Paths = newPaths + for _, e := range fe.errors { + newErr = newErr.Also(e.ViaField(prefix...)) } return newErr } @@ -104,21 +107,32 @@ func (fe *FieldError) ViaFieldKey(field string, key string) *FieldError { // Also collects errors, returns a new collection of existing errors and new errors. func (fe *FieldError) Also(errs ...*FieldError) *FieldError { - newErr := &FieldError{} + var newErr *FieldError // collect the current objects errors, if it has any - if fe != nil { - newErr.errors = fe.getNormalizedErrors() + if !fe.isEmpty() { + newErr = fe.DeepCopy() + } else { + newErr = &FieldError{} } // and then collect the passed in errors for _, e := range errs { - newErr.errors = append(newErr.errors, e.getNormalizedErrors()...) + if !e.isEmpty() { + newErr.errors = append(newErr.errors, *e) + } } - if len(newErr.errors) == 0 { + if newErr.isEmpty() { return nil } return newErr } +func (fe *FieldError) isEmpty() bool { + if fe == nil { + return true + } + return fe.Message == "" && fe.Details == "" && len(fe.errors) == 0 && len(fe.Paths) == 0 +} + func (fe *FieldError) getNormalizedErrors() []FieldError { // in case we call getNormalizedErrors on a nil object, return just an empty // list. This can happen when .Error() is called on a nil object. @@ -139,14 +153,34 @@ func (fe *FieldError) getNormalizedErrors() []FieldError { for _, e := range fe.errors { errors = append(errors, e.getNormalizedErrors()...) } - sort.Slice(errors, func(i, j int) bool { return errors[i].Message < errors[j].Message }) return errors } +// Error implements error +func (fe *FieldError) Error() string { + var errs []string + // Get the list of errors as a flat merged list. + normedErrors := merge(fe.getNormalizedErrors()) + for _, e := range normedErrors { + if e.Details == "" { + errs = append(errs, fmt.Sprintf("%v: %v", e.Message, strings.Join(e.Paths, ", "))) + } else { + errs = append(errs, fmt.Sprintf("%v: %v\n%v", e.Message, strings.Join(e.Paths, ", "), e.Details)) + } + } + return strings.Join(errs, "\n") +} + +// Helpers --- + func asIndex(index int) string { return fmt.Sprintf("[%d]", index) } +func isIndex(part string) bool { + return strings.HasPrefix(part, "[") && strings.HasSuffix(part, "]") +} + func asKey(key string) string { return fmt.Sprintf("[%s]", key) } @@ -173,23 +207,80 @@ func flatten(path []string) string { return strings.Join(newPath, ".") } -func isIndex(part string) bool { - return strings.HasPrefix(part, "[") && strings.HasSuffix(part, "]") +// mergePaths takes in two string slices and returns the combination of them +// without any duplicate entries. +func mergePaths(a, b []string) []string { + newPaths := make([]string, 0, len(a)+len(b)) + newPaths = append(newPaths, a...) + for _, bi := range b { + if !containsString(newPaths, bi) { + newPaths = append(newPaths, bi) + } + } + return newPaths } -// Error implements error -func (fe *FieldError) Error() string { - var errs []string - for _, e := range fe.getNormalizedErrors() { - if e.Details == "" { - errs = append(errs, fmt.Sprintf("%v: %v", e.Message, strings.Join(e.Paths, ", "))) +// containsString takes in a string slice and looks for the provided string +// within the slice. +func containsString(slice []string, s string) bool { + for _, item := range slice { + if item == s { + return true + } + } + return false +} + +// merge takes in a flat list of FieldErrors and returns back a merged list of +// FiledErrors. FieldErrors have their Paths combined (and de-duped) if their +// Message and Details are the same. Merge will not inspect FieldError.errors. +// Merge will also sort the .Path slice, and the errors slice before returning. +func merge(errs []FieldError) []FieldError { + // make a map big enough for all the errors. + m := make(map[string]FieldError, len(errs)) + + // Convert errs to a map where the key is -
and the value + // is the error. If an error already exists in the map with the same key, + // then the paths will be merged. + for _, e := range errs { + k := key(&e) + if v, ok := m[k]; ok { + // Found a match, merge the keys. + v.Paths = mergePaths(v.Paths, e.Paths) + m[k] = v } else { - errs = append(errs, fmt.Sprintf("%v: %v\n%v", e.Message, strings.Join(e.Paths, ", "), e.Details)) + // Does not exist in the map, save the error. + m[k] = e } } - return strings.Join(errs, "\n") + + // Take the map made previously and flatten it back out again. + newErrs := make([]FieldError, 0, len(m)) + for _, v := range m { + // While we have access to the merged paths, sort them too. + sort.Slice(v.Paths, func(i, j int) bool { return v.Paths[i] < v.Paths[j] }) + newErrs = append(newErrs, v) + } + + // Sort the flattened map. + sort.Slice(newErrs, func(i, j int) bool { + if newErrs[i].Message == newErrs[j].Message { + return newErrs[i].Details < newErrs[j].Details + } + return newErrs[i].Message < newErrs[j].Message + }) + + // return back the merged list of sorted errors. + return newErrs } +// key returns the key using the fields .Message and .Details. +func key(err *FieldError) string { + return fmt.Sprintf("%s-%s", err.Message, err.Details) +} + +// Public helpers --- + // ErrMissingField is a variadic helper method for constructing a FieldError for // a set of missing fields. func ErrMissingField(fieldPaths ...string) *FieldError { diff --git a/vendor/github.com/knative/pkg/apis/zz_generated.deepcopy.go b/vendor/github.com/knative/pkg/apis/zz_generated.deepcopy.go index bacb0b708e4..76db35ce157 100644 --- a/vendor/github.com/knative/pkg/apis/zz_generated.deepcopy.go +++ b/vendor/github.com/knative/pkg/apis/zz_generated.deepcopy.go @@ -20,6 +20,34 @@ limitations under the License. package apis +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *FieldError) DeepCopyInto(out *FieldError) { + *out = *in + if in.Paths != nil { + in, out := &in.Paths, &out.Paths + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.errors != nil { + in, out := &in.errors, &out.errors + *out = make([]FieldError, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FieldError. +func (in *FieldError) DeepCopy() *FieldError { + if in == nil { + return nil + } + out := new(FieldError) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VolatileTime) DeepCopyInto(out *VolatileTime) { *out = *in diff --git a/vendor/github.com/knative/pkg/changeset/commit.go b/vendor/github.com/knative/pkg/changeset/commit.go new file mode 100644 index 00000000000..77ed7093211 --- /dev/null +++ b/vendor/github.com/knative/pkg/changeset/commit.go @@ -0,0 +1,64 @@ +/* +Copyright 2018 The Knative 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 changeset + +import ( + "fmt" + "io/ioutil" + "os" + "path/filepath" + "regexp" + "strings" +) + +const ( + commitIDFile = "HEAD" + koDataPathEnvName = "KO_DATA_PATH" +) + +var ( + commitIDRE = regexp.MustCompile(`^[a-f0-9]{40}$`) +) + +// Get tries to fetch the first 7 digitals of GitHub commit ID from HEAD file in +// KO_DATA_PATH. If it fails, it returns the error it gets. +func Get() (string, error) { + data, err := readFileFromKoData(commitIDFile) + if err != nil { + return "", err + } + commitID := strings.TrimSpace(string(data)) + if !commitIDRE.MatchString(commitID) { + err := fmt.Errorf("%q is not a valid GitHub commit ID", commitID) + return "", err + } + return string(commitID[0:7]), nil +} + +// readFileFromKoData tries to read data as string from the file with given name +// under KO_DATA_PATH then returns the content as string. The file is expected +// to be wrapped into the container from /kodata by ko. If it fails, returns +// the error it gets. +func readFileFromKoData(filename string) ([]byte, error) { + koDataPath := os.Getenv(koDataPathEnvName) + if koDataPath == "" { + err := fmt.Errorf("%q does not exist or is empty", koDataPathEnvName) + return nil, err + } + fullFilename := filepath.Join(koDataPath, filename) + return ioutil.ReadFile(fullFilename) +} diff --git a/vendor/github.com/knative/pkg/changeset/doc.go b/vendor/github.com/knative/pkg/changeset/doc.go new file mode 100644 index 00000000000..c56f7ebfb4d --- /dev/null +++ b/vendor/github.com/knative/pkg/changeset/doc.go @@ -0,0 +1,23 @@ +/* +Copyright 2018 The Knative 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 changeset provides Knative utilities for fetching GitHub Commit ID +// from kodata directory. It requires GitHub HEAD file to be linked into +// Knative component source code via the following command: +// ln -s -r .git/HEAD ./cmd//kodata/ +// Then ko will build this file into $KO_DATA_PATH when building the container +// for a Knative component. +package changeset diff --git a/pkg/event/doc.go b/vendor/github.com/knative/pkg/cloudevents/doc.go similarity index 89% rename from pkg/event/doc.go rename to vendor/github.com/knative/pkg/cloudevents/doc.go index 99474855687..d33753866f8 100644 --- a/pkg/event/doc.go +++ b/vendor/github.com/knative/pkg/cloudevents/doc.go @@ -14,9 +14,10 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package event implements utilities for handling CloudEvents. +// Package cloudevents implements utilities for handling CloudEvents. // For information on the spec, see // https://github.com/cloudevents/spec/blob/v0.1/http-transport-binding.md // and // https://github.com/cloudevents/spec/blob/v0.1/spec.md -package event + +package cloudevents diff --git a/pkg/event/encoding_binary.go b/vendor/github.com/knative/pkg/cloudevents/encoding_binary.go similarity index 99% rename from pkg/event/encoding_binary.go rename to vendor/github.com/knative/pkg/cloudevents/encoding_binary.go index c387658de2f..ed88e01c47a 100644 --- a/pkg/event/encoding_binary.go +++ b/vendor/github.com/knative/pkg/cloudevents/encoding_binary.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package event +package cloudevents // TODO(inlined): must add header encoding/decoding diff --git a/pkg/event/encoding_structured.go b/vendor/github.com/knative/pkg/cloudevents/encoding_structured.go similarity index 99% rename from pkg/event/encoding_structured.go rename to vendor/github.com/knative/pkg/cloudevents/encoding_structured.go index 55118e06d41..08c2acab97f 100644 --- a/pkg/event/encoding_structured.go +++ b/vendor/github.com/knative/pkg/cloudevents/encoding_structured.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package event +package cloudevents import ( "bytes" diff --git a/pkg/event/event.go b/vendor/github.com/knative/pkg/cloudevents/event.go similarity index 99% rename from pkg/event/event.go rename to vendor/github.com/knative/pkg/cloudevents/event.go index 3ace7433a21..2074139f1a7 100644 --- a/pkg/event/event.go +++ b/vendor/github.com/knative/pkg/cloudevents/event.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package event +package cloudevents import ( "context" diff --git a/pkg/event/handler.go b/vendor/github.com/knative/pkg/cloudevents/handler.go similarity index 99% rename from pkg/event/handler.go rename to vendor/github.com/knative/pkg/cloudevents/handler.go index f26444e46c5..7291064347a 100644 --- a/pkg/event/handler.go +++ b/vendor/github.com/knative/pkg/cloudevents/handler.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package event +package cloudevents import ( "context" diff --git a/vendor/github.com/knative/pkg/configmap/filter.go b/vendor/github.com/knative/pkg/configmap/filter.go new file mode 100644 index 00000000000..27bf13df98b --- /dev/null +++ b/vendor/github.com/knative/pkg/configmap/filter.go @@ -0,0 +1,44 @@ +/* +Copyright 2018 The Knative 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 + + https://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 configmap + +import "reflect" + +// TypeFilter accepts instances of types to check against and returns a function transformer that would only let +// the call to f through if value is assignable to any one of types of ts. Example: +// +// F := configmap.TypeFilter(&config.Domain{})(f) +// +// The result is a function F(name string, value interface{}) that will call the underlying function +// f(name, value) iff value is a *config.Domain +func TypeFilter(ts ...interface{}) func(func(string, interface{})) func(string, interface{}) { + return func(f func(string, interface{})) func(string, interface{}) { + return func(name string, value interface{}) { + satisfies := false + for _, t := range ts { + t := reflect.TypeOf(t) + if reflect.TypeOf(value).AssignableTo(t) { + satisfies = true + break + } + } + if satisfies { + f(name, value) + } + } + } +} diff --git a/vendor/github.com/knative/pkg/configmap/store.go b/vendor/github.com/knative/pkg/configmap/store.go new file mode 100644 index 00000000000..62cab432452 --- /dev/null +++ b/vendor/github.com/knative/pkg/configmap/store.go @@ -0,0 +1,174 @@ +/* +Copyright 2018 The Knative 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 + + https://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 configmap + +import ( + "reflect" + "sync/atomic" + + corev1 "k8s.io/api/core/v1" +) + +// Logger is the interface that UntypedStore expects its logger to conform to. +// UntypedStore will log when updates succeed or fail. +type Logger interface { + Infof(string, ...interface{}) + Fatalf(string, ...interface{}) + Errorf(string, ...interface{}) +} + +// Constructors is a map for specifying config names to +// their function constructors +// +// The values of this map must be functions with the definition +// +// func(*k8s.io/api/core/v1.ConfigMap) (... , error) +// +// These functions can return any type along with an error +type Constructors map[string]interface{} + +// An UntypedStore is a responsible for storing and +// constructing configs from Kubernetes ConfigMaps +// +// WatchConfigs should be used with a configmap,Watcher +// in order for this store to remain up to date +type UntypedStore struct { + name string + logger Logger + + storages map[string]*atomic.Value + constructors map[string]reflect.Value + + onAfterStore []func(name string, value interface{}) +} + +// NewUntypedStore creates an UntypedStore with given name, +// Logger and Constructors +// +// The Logger must not be nil +// +// The values in the Constructors map must be functions with +// the definition +// +// func(*k8s.io/api/core/v1.ConfigMap) (... , error) +// +// These functions can return any type along with an error. +// If the function definition differs then NewUntypedStore +// will panic. +// +// onAfterStore is a variadic list of callbacks to run +// after the ConfigMap has been transformed (via the appropriate Constructor) +// and stored. These callbacks run sequentially (in the argument order) in a +// separate go-routine and are of type func(name string, value interface{}) +// where name is the config-map name and value is the object that has been +// constructed from the config-map and stored. +func NewUntypedStore( + name string, + logger Logger, + constructors Constructors, + onAfterStore ...func(name string, value interface{})) *UntypedStore { + + store := &UntypedStore{ + name: name, + logger: logger, + storages: make(map[string]*atomic.Value), + constructors: make(map[string]reflect.Value), + onAfterStore: onAfterStore, + } + + for configName, constructor := range constructors { + store.registerConfig(configName, constructor) + } + + return store +} + +func (s *UntypedStore) registerConfig(name string, constructor interface{}) { + cType := reflect.TypeOf(constructor) + + if cType.Kind() != reflect.Func { + panic("config constructor must be a function") + } + + if cType.NumIn() != 1 || cType.In(0) != reflect.TypeOf(&corev1.ConfigMap{}) { + panic("config constructor must be of the type func(*k8s.io/api/core/v1/ConfigMap) (..., error)") + } + + errorType := reflect.TypeOf((*error)(nil)).Elem() + + if cType.NumOut() != 2 || !cType.Out(1).Implements(errorType) { + panic("config constructor must be of the type func(*k8s.io/api/core/v1/ConfigMap) (..., error)") + } + + s.storages[name] = &atomic.Value{} + s.constructors[name] = reflect.ValueOf(constructor) +} + +// WatchConfigs uses the provided configmap.Watcher +// to setup watches for the config names provided in the +// Constructors map +func (s *UntypedStore) WatchConfigs(w Watcher) { + for configMapName := range s.constructors { + w.Watch(configMapName, s.OnConfigChanged) + } +} + +// UntypedLoad will return the constructed value for a given +// ConfigMap name +func (s *UntypedStore) UntypedLoad(name string) interface{} { + storage := s.storages[name] + return storage.Load() +} + +// OnConfigChanged will invoke the mapped constructor against +// a Kubernetes ConfigMap. If successful it will be stored. +// If construction fails during the first appearance the store +// will log a fatal error. If construction fails while updating +// the store will log an error message. +func (s *UntypedStore) OnConfigChanged(c *corev1.ConfigMap) { + name := c.ObjectMeta.Name + + storage := s.storages[name] + constructor := s.constructors[name] + + inputs := []reflect.Value{ + reflect.ValueOf(c), + } + + outputs := constructor.Call(inputs) + result := outputs[0].Interface() + errVal := outputs[1] + + if !errVal.IsNil() { + err := errVal.Interface() + if storage.Load() != nil { + s.logger.Errorf("Error updating %s config %q: %q", s.name, name, err) + } else { + s.logger.Fatalf("Error initializing %s config %q: %q", s.name, name, err) + } + return + } + + s.logger.Infof("%s config %q config was added or updated: %v", s.name, name, result) + storage.Store(result) + + go func() { + for _, f := range s.onAfterStore { + f(name, result) + } + }() +} diff --git a/vendor/github.com/knative/pkg/kmeta/accessor.go b/vendor/github.com/knative/pkg/kmeta/accessor.go new file mode 100644 index 00000000000..07c69bedaa6 --- /dev/null +++ b/vendor/github.com/knative/pkg/kmeta/accessor.go @@ -0,0 +1,94 @@ +/* +Copyright 2018 The Knative 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 kmeta + +import ( + "fmt" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/tools/cache" +) + +// Accessor is a collection of interfaces from metav1.TypeMeta, +// runtime.Object and metav1.Object that Kubernetes API types +// registered with runtime.Scheme must support. +type Accessor interface { + // Interfaces for metav1.TypeMeta + GroupVersionKind() schema.GroupVersionKind + SetGroupVersionKind(gvk schema.GroupVersionKind) + + // Interfaces for runtime.Object + GetObjectKind() schema.ObjectKind + DeepCopyObject() runtime.Object + + // Interfaces for metav1.Object + GetNamespace() string + SetNamespace(namespace string) + GetName() string + SetName(name string) + GetGenerateName() string + SetGenerateName(name string) + GetUID() types.UID + SetUID(uid types.UID) + GetResourceVersion() string + SetResourceVersion(version string) + GetGeneration() int64 + SetGeneration(generation int64) + GetSelfLink() string + SetSelfLink(selfLink string) + GetCreationTimestamp() metav1.Time + SetCreationTimestamp(timestamp metav1.Time) + GetDeletionTimestamp() *metav1.Time + SetDeletionTimestamp(timestamp *metav1.Time) + GetDeletionGracePeriodSeconds() *int64 + SetDeletionGracePeriodSeconds(*int64) + GetLabels() map[string]string + SetLabels(labels map[string]string) + GetAnnotations() map[string]string + SetAnnotations(annotations map[string]string) + GetInitializers() *metav1.Initializers + SetInitializers(initializers *metav1.Initializers) + GetFinalizers() []string + SetFinalizers(finalizers []string) + GetOwnerReferences() []metav1.OwnerReference + SetOwnerReferences([]metav1.OwnerReference) + GetClusterName() string + SetClusterName(clusterName string) +} + +// DeletionHandlingAccessor tries to convert given interface into Accessor first; +// and to handle deletion, it try to fetch info from DeletedFinalStateUnknown on failure. +// The name is a reference to cache.DeletionHandlingMetaNamespaceKeyFunc +func DeletionHandlingAccessor(obj interface{}) (Accessor, error) { + accessor, ok := obj.(Accessor) + if !ok { + // To handle obj deletion, try to fetch info from DeletedFinalStateUnknown. + tombstone, ok := obj.(cache.DeletedFinalStateUnknown) + if !ok { + return nil, fmt.Errorf("Couldn't get Accessor from tombstone %#v", obj) + } + accessor, ok = tombstone.Obj.(Accessor) + if !ok { + return nil, fmt.Errorf("The object that Tombstone contained is not of kmeta.Accessor %#v", obj) + } + } + + return accessor, nil +} diff --git a/pkg/apis/feeds/v1alpha1/common_event_source_defaults.go b/vendor/github.com/knative/pkg/kmeta/doc.go similarity index 76% rename from pkg/apis/feeds/v1alpha1/common_event_source_defaults.go rename to vendor/github.com/knative/pkg/kmeta/doc.go index fc51100a254..53ff38d726b 100644 --- a/pkg/apis/feeds/v1alpha1/common_event_source_defaults.go +++ b/vendor/github.com/knative/pkg/kmeta/doc.go @@ -5,7 +5,7 @@ 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 + https://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, @@ -14,8 +14,6 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1alpha1 - -func (cess *CommonEventSourceSpec) SetDefaults() { - // nothing to default -} +// Package kmeta provides Knative utilities for operating on Kubernetes +// resources' ObjectMeta. +package kmeta diff --git a/vendor/github.com/knative/pkg/kmeta/labels.go b/vendor/github.com/knative/pkg/kmeta/labels.go new file mode 100644 index 00000000000..f9a72d8bf37 --- /dev/null +++ b/vendor/github.com/knative/pkg/kmeta/labels.go @@ -0,0 +1,114 @@ +/* +Copyright 2018 The Knative 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 kmeta + +import ( + "fmt" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/selection" +) + +// The methods in this file are used for managing subresources in cases where +// a controller instantiates different resources for each version of itself. +// There are two sets of methods available here: +// * `*VersionLabel*`: these methods act on `metadata.resourceVersion` and +// create new labels for EVERY change to the resource (incl. `/status`). +// * `*GenerationLabel*`: these methods act on `metadata.generation` and +// create new labels for changes to the resource's "spec" (typically, but +// some K8s resources change `metadata.generation` for annotations as well +// e.g. Deployment). +// +// For example, if an A might instantiate N B's at version 1 and M B's at +// version 2 then it can use MakeVersionLabels to decorate each subresource +// with the appropriate labels for the version at which it was instantiated. +// +// During reconciliation, MakeVersionLabelSelector can be used with the +// informer listers to access the appropriate subresources for the current +// version of the parent resource. +// +// Likewise during reconciliation, MakeOldVersionLabelSelector can be used +// with the API client's DeleteCollection method to clean up subresources +// for older versions of the resource. + +// MakeVersionLabels constructs a set of labels to apply to subresources +// instantiated at this version of the parent resource, so that we can +// efficiently select them. +func MakeVersionLabels(om metav1.ObjectMetaAccessor) labels.Set { + return map[string]string{ + "controller": string(om.GetObjectMeta().GetUID()), + "version": om.GetObjectMeta().GetResourceVersion(), + } +} + +// MakeVersionLabelSelector constructs a selector for subresources +// instantiated at this version of the parent resource. This keys +// off of the labels populated by MakeVersionLabels. +func MakeVersionLabelSelector(om metav1.ObjectMetaAccessor) labels.Selector { + return labels.SelectorFromSet(MakeVersionLabels(om)) +} + +// MakeOldVersionLabelSelector constructs a selector for subresources +// instantiated at an older version of the parent resource. This keys +// off of the labels populated by MakeVersionLabels. +func MakeOldVersionLabelSelector(om metav1.ObjectMetaAccessor) labels.Selector { + return labels.NewSelector().Add( + mustNewRequirement("controller", selection.Equals, []string{string(om.GetObjectMeta().GetUID())}), + mustNewRequirement("version", selection.NotEquals, []string{om.GetObjectMeta().GetResourceVersion()}), + ) +} + +// MakeGenerationLabels constructs a set of labels to apply to subresources +// instantiated at this version of the parent resource, so that we can +// efficiently select them. +func MakeGenerationLabels(om metav1.ObjectMetaAccessor) labels.Set { + return map[string]string{ + "controller": string(om.GetObjectMeta().GetUID()), + "generation": genStr(om), + } +} + +// MakeGenerationLabelSelector constructs a selector for subresources +// instantiated at this version of the parent resource. This keys +// off of the labels populated by MakeGenerationLabels. +func MakeGenerationLabelSelector(om metav1.ObjectMetaAccessor) labels.Selector { + return labels.SelectorFromSet(MakeGenerationLabels(om)) +} + +// MakeOldGenerationLabelSelector constructs a selector for subresources +// instantiated at an older version of the parent resource. This keys +// off of the labels populated by MakeGenerationLabels. +func MakeOldGenerationLabelSelector(om metav1.ObjectMetaAccessor) labels.Selector { + return labels.NewSelector().Add( + mustNewRequirement("controller", selection.Equals, []string{string(om.GetObjectMeta().GetUID())}), + mustNewRequirement("generation", selection.NotEquals, []string{genStr(om)}), + ) +} + +func genStr(om metav1.ObjectMetaAccessor) string { + return fmt.Sprintf("%05d", om.GetObjectMeta().GetGeneration()) +} + +// mustNewRequirement panics if there are any errors constructing our selectors. +func mustNewRequirement(key string, op selection.Operator, vals []string) labels.Requirement { + r, err := labels.NewRequirement(key, op, vals) + if err != nil { + panic(fmt.Sprintf("mustNewRequirement(%v, %v, %v) = %v", key, op, vals, err)) + } + return *r +} diff --git a/vendor/github.com/knative/pkg/kmeta/owner_references.go b/vendor/github.com/knative/pkg/kmeta/owner_references.go new file mode 100644 index 00000000000..2e9a1289f93 --- /dev/null +++ b/vendor/github.com/knative/pkg/kmeta/owner_references.go @@ -0,0 +1,38 @@ +/* +Copyright 2018 The Knative 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 kmeta + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +// OwnerRefable indicates that a particular type has sufficient +// information to produce a metav1.OwnerReference to an object. +type OwnerRefable interface { + metav1.ObjectMetaAccessor + + // GetGroupVersionKind returns a GroupVersionKind. The name is chosen + // to avoid collision with TypeMeta's GroupVersionKind() method. + // See: https://issues.k8s.io/3030 + GetGroupVersionKind() schema.GroupVersionKind +} + +// NewControllerRef creates an OwnerReference pointing to the given controller. +func NewControllerRef(obj OwnerRefable) *metav1.OwnerReference { + return metav1.NewControllerRef(obj.GetObjectMeta(), obj.GetGroupVersionKind()) +} diff --git a/vendor/github.com/knative/pkg/logging/config.go b/vendor/github.com/knative/pkg/logging/config.go index 8c0dfe50d94..c03c193148b 100644 --- a/vendor/github.com/knative/pkg/logging/config.go +++ b/vendor/github.com/knative/pkg/logging/config.go @@ -25,6 +25,7 @@ import ( "go.uber.org/zap/zapcore" corev1 "k8s.io/api/core/v1" + "github.com/knative/pkg/changeset" "github.com/knative/pkg/logging/logkey" ) @@ -37,7 +38,7 @@ import ( func NewLogger(configJSON string, levelOverride string, opts ...zap.Option) (*zap.SugaredLogger, zap.AtomicLevel) { logger, atomicLevel, err := newLoggerFromConfig(configJSON, levelOverride, opts) if err == nil { - return logger.Sugar(), atomicLevel + return enrichLoggerWithCommitID(logger.Sugar()), atomicLevel } loggingCfg := zap.NewProductionConfig() @@ -51,7 +52,18 @@ func NewLogger(configJSON string, levelOverride string, opts ...zap.Option) (*za if err2 != nil { panic(err2) } - return logger.Named("fallback-logger").Sugar(), loggingCfg.Level + return enrichLoggerWithCommitID(logger.Named("fallback-logger").Sugar()), loggingCfg.Level +} + +func enrichLoggerWithCommitID(logger *zap.SugaredLogger) *zap.SugaredLogger { + commmitID, err := changeset.Get() + if err == nil { + // Enrich logs with GitHub commit ID. + return logger.With(zap.String(logkey.GitHubCommitID, commmitID)) + } + + logger.Warnf("Fetch GitHub commit ID from kodata failed: %v", err) + return logger } // NewLoggerFromConfig creates a logger using the provided Config diff --git a/vendor/github.com/knative/pkg/logging/logkey/constants.go b/vendor/github.com/knative/pkg/logging/logkey/constants.go index 809b1012865..e4c62ee0daf 100644 --- a/vendor/github.com/knative/pkg/logging/logkey/constants.go +++ b/vendor/github.com/knative/pkg/logging/logkey/constants.go @@ -55,4 +55,8 @@ const ( // KubernetesService is the key used to represent a Kubernetes service name in logs KubernetesService = "knative.dev/k8sservice" + + // GitHubCommitID is the key used to represent the GitHub Commit ID where the + // Knative component was built from in logs + GitHubCommitID = "commit" ) diff --git a/vendor/github.com/knative/pkg/test/e2e_flags.go b/vendor/github.com/knative/pkg/test/e2e_flags.go index 7d8261accd1..1cd0fada634 100644 --- a/vendor/github.com/knative/pkg/test/e2e_flags.go +++ b/vendor/github.com/knative/pkg/test/e2e_flags.go @@ -45,8 +45,10 @@ func initializeFlags() *EnvironmentFlags { flag.StringVar(&f.Cluster, "cluster", defaultCluster, "Provide the cluster to test against. Defaults to $K8S_CLUSTER_OVERRIDE, then current cluster in kubeconfig if $K8S_CLUSTER_OVERRIDE is unset.") - usr, _ := user.Current() - defaultKubeconfig := path.Join(usr.HomeDir, ".kube/config") + var defaultKubeconfig string + if usr, err := user.Current(); err == nil { + defaultKubeconfig = path.Join(usr.HomeDir, ".kube/config") + } flag.StringVar(&f.Kubeconfig, "kubeconfig", defaultKubeconfig, "Provide the path to the `kubeconfig` file you'd like to use for these tests. The `current-context` will be used.") diff --git a/vendor/github.com/knative/pkg/test/kube_checks.go b/vendor/github.com/knative/pkg/test/kube_checks.go index 6d3a828cd50..74691b362e9 100644 --- a/vendor/github.com/knative/pkg/test/kube_checks.go +++ b/vendor/github.com/knative/pkg/test/kube_checks.go @@ -32,15 +32,15 @@ import ( ) const ( - interval = 1 * time.Second - timeout = 5 * time.Minute + interval = 1 * time.Second + podTimeout = 5 * time.Minute ) // WaitForDeploymentState polls the status of the Deployment called name // from client every interval until inState returns `true` indicating it // is done, returns an error or timeout. desc will be used to name the metric // that is emitted to track how long it took for name to get into the state checked by inState. -func WaitForDeploymentState(client *KubeClient, name string, inState func(d *apiv1beta1.Deployment) (bool, error), desc string, namespace string) error { +func WaitForDeploymentState(client *KubeClient, name string, inState func(d *apiv1beta1.Deployment) (bool, error), desc string, namespace string, timeout time.Duration) error { d := client.Kube.ExtensionsV1beta1().Deployments(namespace) metricName := fmt.Sprintf("WaitForDeploymentState/%s/%s", name, desc) _, span := trace.StartSpan(context.Background(), metricName) @@ -65,7 +65,7 @@ func WaitForPodListState(client *KubeClient, inState func(p *corev1.PodList) (bo _, span := trace.StartSpan(context.Background(), metricName) defer span.End() - return wait.PollImmediate(interval, timeout, func() (bool, error) { + return wait.PollImmediate(interval, podTimeout, func() (bool, error) { p, err := p.List(metav1.ListOptions{}) if err != nil { return true, err diff --git a/vendor/github.com/knative/pkg/test/logging/logging.go b/vendor/github.com/knative/pkg/test/logging/logging.go index 4bf52f7bdfe..b5166b207ec 100644 --- a/vendor/github.com/knative/pkg/test/logging/logging.go +++ b/vendor/github.com/knative/pkg/test/logging/logging.go @@ -77,17 +77,18 @@ func newLogger(logLevel string) *BaseLogger { "outputPaths": ["stdout"], "errorOutputPaths": ["stderr"], "encoderConfig": { + "timeKey": "ts", "messageKey": "message", - "levelKey": "level", - "nameKey": "logger", - "callerKey": "caller", - "messageKey": "msg", - "stacktraceKey": "stacktrace", - "lineEnding": "", - "levelEncoder": "", - "timeEncoder": "", - "durationEncoder": "", - "callerEncoder": "" + "levelKey": "level", + "nameKey": "logger", + "callerKey": "caller", + "messageKey": "msg", + "stacktraceKey": "stacktrace", + "lineEnding": "", + "levelEncoder": "", + "timeEncoder": "iso8601", + "durationEncoder": "", + "callerEncoder": "" } }` configJSON := fmt.Sprintf(configJSONTemplate, logLevel) diff --git a/vendor/github.com/knative/pkg/test/spoof/spoof.go b/vendor/github.com/knative/pkg/test/spoof/spoof.go index 21f5b83bb4a..9c94b3c5e70 100644 --- a/vendor/github.com/knative/pkg/test/spoof/spoof.go +++ b/vendor/github.com/knative/pkg/test/spoof/spoof.go @@ -19,6 +19,9 @@ limitations under the License. package spoof import ( + "bytes" + "encoding/json" + "errors" "fmt" "io/ioutil" "net" @@ -26,14 +29,22 @@ import ( "time" "github.com/knative/pkg/test/logging" + zipkin "github.com/knative/pkg/test/zipkin" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" + + "go.opencensus.io/plugin/ochttp" + "go.opencensus.io/plugin/ochttp/propagation/b3" + "go.opencensus.io/trace" ) const ( requestInterval = 1 * time.Second requestTimeout = 5 * time.Minute + // TODO(tcnghia): These probably shouldn't be hard-coded here? + ingressName = "knative-ingressgateway" + ingressNamespace = "istio-system" ) // Response is a stripped down subset of http.Response. The is primarily useful @@ -82,7 +93,7 @@ type SpoofingClient struct { // If that's a problem, see test/request.go#WaitForEndpointState for oneshot spoofing. func New(kubeClientset *kubernetes.Clientset, logger *logging.BaseLogger, domain string, resolvable bool) (*SpoofingClient, error) { sc := SpoofingClient{ - Client: http.DefaultClient, + Client: &http.Client{Transport: &ochttp.Transport{Propagation: &b3.HTTPFormat{}}}, // Using ochttp Transport required for zipkin-tracing RequestInterval: requestInterval, RequestTimeout: requestTimeout, logger: logger, @@ -92,25 +103,12 @@ func New(kubeClientset *kubernetes.Clientset, logger *logging.BaseLogger, domain // If the domain that the Route controller is configured to assign to Route.Status.Domain // (the domainSuffix) is not resolvable, we need to retrieve the IP of the endpoint and // spoof the Host in our requests. - - // TODO(tcnghia): These probably shouldn't be hard-coded here? - ingressName := "knative-ingressgateway" - ingressNamespace := "istio-system" - - ingress, err := kubeClientset.CoreV1().Services(ingressNamespace).Get(ingressName, metav1.GetOptions{}) + e, err := GetServiceEndpoint(kubeClientset) if err != nil { return nil, err } - if len(ingress.Status.LoadBalancer.Ingress) != 1 { - return nil, fmt.Errorf("Expected exactly one ingress load balancer, instead had %d: %s", len(ingress.Status.LoadBalancer.Ingress), ingress.Status.LoadBalancer.Ingress) - } - - if ingress.Status.LoadBalancer.Ingress[0].IP == "" { - return nil, fmt.Errorf("Expected ingress loadbalancer IP for %s to be set, instead was empty", ingressName) - } - - sc.endpoint = ingress.Status.LoadBalancer.Ingress[0].IP + sc.endpoint = *e sc.domain = domain } else { // If the domain is resolvable, we can use it directly when we make requests. @@ -120,8 +118,32 @@ func New(kubeClientset *kubernetes.Clientset, logger *logging.BaseLogger, domain return &sc, nil } +// GetServiceEndpoint gets the endpoint IP or hostname to use for the service +func GetServiceEndpoint(kubeClientset *kubernetes.Clientset) (*string, error) { + var endpoint string + ingress, err := kubeClientset.CoreV1().Services(ingressNamespace).Get(ingressName, metav1.GetOptions{}) + if err != nil { + return nil, err + } + ingresses := ingress.Status.LoadBalancer.Ingress + if len(ingresses) != 1 { + return nil, fmt.Errorf("Expected exactly one ingress load balancer, instead had %d: %s", len(ingresses), ingresses) + } + ingressToUse := ingresses[0] + if ingressToUse.IP == "" { + if ingressToUse.Hostname == "" { + return nil, fmt.Errorf("Expected ingress loadbalancer IP or hostname for %s to be set, instead was empty", ingressName) + } + endpoint = ingressToUse.Hostname + } else { + endpoint = ingressToUse.IP + } + return &endpoint, nil +} + // Do dispatches to the underlying http.Client.Do, spoofing domains as needed // and transforming the http.Response into a spoof.Response. +// Each response is augmented with "ZipkinTraceID" header that identifies the zipkin trace corresponding to the request. func (sc *SpoofingClient) Do(req *http.Request) (*Response, error) { // Controls the Host header, for spoofing. if sc.domain != "" { @@ -133,12 +155,18 @@ func (sc *SpoofingClient) Do(req *http.Request) (*Response, error) { req.URL.Host = sc.endpoint } - resp, err := sc.Client.Do(req) + // Starting span to capture zipkin trace. + traceContext, span := trace.StartSpan(req.Context(), "SpoofingClient-Trace") + defer span.End() + + resp, err := sc.Client.Do(req.WithContext(traceContext)) if err != nil { return nil, err } defer resp.Body.Close() + + resp.Header.Add(zipkin.ZipkinTraceIDHeader, span.SpanContext().TraceID.String()) body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err @@ -174,3 +202,34 @@ func (sc *SpoofingClient) Poll(req *http.Request, inState ResponseChecker) (*Res return resp, err } + +// LogZipkinTrace provides support to log Zipkin Trace for param: traceID +func (sc *SpoofingClient) LogZipkinTrace(traceID string) error { + if err := zipkin.CheckZipkinPortAvailability(); err == nil { + return errors.New("port-forwarding for Zipkin is not-setup. Failing Zipkin Trace retrieval") + } + + sc.logger.Infof("Logging Zipkin Trace: %s", traceID) + + zipkinTraceEndpoint := zipkin.ZipkinTraceEndpoint + traceID + // Sleep to ensure all traces are correctly pushed on the backend. + time.Sleep(5 * time.Second) + resp, err := http.Get(zipkinTraceEndpoint) + if err != nil { + return fmt.Errorf("Error retrieving Zipkin trace: %v", err) + } + + trace, err := ioutil.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("Error reading Zipkin trace response: %v", err) + } + + var prettyJSON bytes.Buffer + error := json.Indent(&prettyJSON, trace, "", "\t") + if error != nil { + return fmt.Errorf("JSON Parser Error while trying for Pretty-Format: %v, Original Response: %s", error, string(trace)) + } + sc.logger.Infof(prettyJSON.String()) + + return nil +} \ No newline at end of file diff --git a/vendor/github.com/knative/pkg/test/zipkin/util.go b/vendor/github.com/knative/pkg/test/zipkin/util.go new file mode 100644 index 00000000000..5d41e5dbc73 --- /dev/null +++ b/vendor/github.com/knative/pkg/test/zipkin/util.go @@ -0,0 +1,110 @@ +/* +Copyright 2018 The Knative 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. +*/ + +//util has constants and helper methods useful for zipkin tracing support. + +package zipkin + +import ( + "errors" + "fmt" + "net" + "os" + "os/exec" + + "github.com/knative/pkg/test/logging" + "go.opencensus.io/trace" + "k8s.io/client-go/kubernetes" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +const ( + + //ZipkinTraceIDHeader HTTP response header key to be used to store Zipkin Trace ID. + ZipkinTraceIDHeader = "ZIPKIN_TRACE_ID" + + // ZipkinPort port exposed by the Zipkin Pod + // https://github.com/knative/serving/blob/master/config/monitoring/200-common/100-zipkin.yaml#L25 configures the Zipkin Port on the cluster. + ZipkinPort = 9411 + + // ZipkinTraceEndpoint port-forwarded zipkin endpoint + ZipkinTraceEndpoint = "http://localhost:9411/api/v2/trace/" + + // ZipkinNamespace namespace where zipkin pod runs. + // https://github.com/knative/serving/blob/master/config/monitoring/200-common/100-zipkin.yaml#L19 configures the namespace for zipkin. + ZipkinNamespace = "istio-system" +) + +var zipkinPortForwardPID int + +// SetupZipkinTracing sets up zipkin tracing which involves a) Setting up port-forwarding from localhost to zipkin pod on the cluster (pid of the process doing Port-Forward is stored in a global variable). +// b) enable AlwaysSample config for tracing. +func SetupZipkinTracing(kubeClientset *kubernetes.Clientset) error { + logger := logging.GetContextLogger("SpoofUtil") + + if err := CheckZipkinPortAvailability(); err != nil { + return fmt.Errorf("Zipkin port not available on the machine: %v", err) + } + + zipkinPods, err := kubeClientset.CoreV1().Pods(ZipkinNamespace).List(metav1.ListOptions{LabelSelector: "app=zipkin"}) + if err != nil { + return fmt.Errorf("Error retrieving Zipkin pod details : %v", err) + } + + if len(zipkinPods.Items) == 0 { + return errors.New("No Zipkin Pod found on the cluster. Ensure monitoring is switched on for your Knative Setup") + } + + portForwardCmd := exec.Command("kubectl", "port-forward", "--namespace=" + ZipkinNamespace, zipkinPods.Items[0].Name, fmt.Sprintf("%d:%d", ZipkinPort, ZipkinPort)) + if err = portForwardCmd.Start(); err != nil { + return fmt.Errorf("Error starting kubectl port-forward command : %v", err) + + } + zipkinPortForwardPID = portForwardCmd.Process.Pid + logger.Infof("Zipkin port-forward process started with PID: %d", zipkinPortForwardPID) + + // Applying AlwaysSample config to ensure we propagate zipkin header for every request made by this client. + trace.ApplyConfig(trace.Config{DefaultSampler: trace.AlwaysSample()}) + + logger.Infof("Successfully setup SpoofingClient for Zipkin Tracing") + + return nil +} + +// CleanupZipkinTracingSetup cleans up the Zipkin tracing setup on the machine. This involves killing the process performing port-forward. +func CleanupZipkinTracingSetup() error { + logger := logging.GetContextLogger("SpoofUtil") + + ps := os.Process{Pid: zipkinPortForwardPID} + if err := ps.Kill(); err != nil { + return fmt.Errorf("Encoutered error killing port-forward process in CleanupZipkingTracingSetup() : %v", err) + } + + logger.Infof("Successfully killed Zipkin port-forward process") + return nil +} + +// CheckZipkinPortAvailability checks to see if Zipkin Port is available on the machine. +// returns error if the port is not available. +func CheckZipkinPortAvailability() error { + server, err := net.Listen("tcp", fmt.Sprintf(":%d", ZipkinPort)) + if err != nil { + // Port is likely taken + return err + } + server.Close() + return nil +} \ No newline at end of file diff --git a/vendor/github.com/knative/pkg/webhook/certs.go b/vendor/github.com/knative/pkg/webhook/certs.go index 8bc80b4f4ef..510783bbeca 100644 --- a/vendor/github.com/knative/pkg/webhook/certs.go +++ b/vendor/github.com/knative/pkg/webhook/certs.go @@ -47,7 +47,12 @@ func createCertTemplate(name, namespace string) (*x509.Certificate, error) { } serviceName := name + "." + namespace - serviceNames := []string{serviceName, serviceName + ".svc", serviceName + ".svc.cluster.local"} + serviceNames := []string{ + name, + serviceName, + serviceName + ".svc", + serviceName + ".svc.cluster.local", + } tmpl := x509.Certificate{ SerialNumber: serialNumber, diff --git a/vendor/github.com/knative/pkg/webhook/webhook.go b/vendor/github.com/knative/pkg/webhook/webhook.go index 8727dca7741..6ca41821419 100644 --- a/vendor/github.com/knative/pkg/webhook/webhook.go +++ b/vendor/github.com/knative/pkg/webhook/webhook.go @@ -38,6 +38,7 @@ import ( "github.com/knative/pkg/logging" "github.com/knative/pkg/logging/logkey" + "github.com/markbates/inflect" "github.com/mattbaird/jsonpatch" admissionv1beta1 "k8s.io/api/admission/v1beta1" admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1" @@ -94,6 +95,11 @@ type ControllerOptions struct { // potential races where registration completes and k8s apiserver // invokes the webhook before the HTTP server is started. RegistrationDelay time.Duration + + // ClientAuthType declares the policy the webhook server will follow for + // TLS Client Authentication. + // The default value is tls.NoClientCert. + ClientAuth tls.ClientAuthType } // ResourceCallback defines a signature for resource specific (Route, Configuration, etc.) @@ -134,15 +140,16 @@ func getAPIServerExtensionCACert(cl kubernetes.Interface) ([]byte, error) { if err != nil { return nil, err } - pem, ok := c.Data["requestheader-client-ca-file"] + const caFileName = "requestheader-client-ca-file" + pem, ok := c.Data[caFileName] if !ok { - return nil, fmt.Errorf("cannot find ca.crt in %v: ConfigMap.Data is %#v", name, c.Data) + return nil, fmt.Errorf("cannot find %s in ConfigMap %s: ConfigMap.Data is %#v", caFileName, name, c.Data) } return []byte(pem), nil } // MakeTLSConfig makes a TLS configuration suitable for use with the server -func makeTLSConfig(serverCert, serverKey, caCert []byte) (*tls.Config, error) { +func makeTLSConfig(serverCert, serverKey, caCert []byte, clientAuthType tls.ClientAuthType) (*tls.Config, error) { caCertPool := x509.NewCertPool() caCertPool.AppendCertsFromPEM(caCert) cert, err := tls.X509KeyPair(serverCert, serverKey) @@ -152,11 +159,7 @@ func makeTLSConfig(serverCert, serverKey, caCert []byte) (*tls.Config, error) { return &tls.Config{ Certificates: []tls.Certificate{cert}, ClientCAs: caCertPool, - ClientAuth: tls.NoClientCert, - // Note on GKE there apparently is no client cert sent, so this - // does not work on GKE. - // TODO: make this into a configuration option. - // ClientAuth: tls.RequireAndVerifyClientCert, + ClientAuth: clientAuthType, }, nil } @@ -234,16 +237,20 @@ func SetDefaults(ctx context.Context) ResourceDefaulter { } func configureCerts(ctx context.Context, client kubernetes.Interface, options *ControllerOptions) (*tls.Config, []byte, error) { - apiServerCACert, err := getAPIServerExtensionCACert(client) - if err != nil { - return nil, nil, err + var apiServerCACert []byte + if options.ClientAuth >= tls.VerifyClientCertIfGiven { + var err error + apiServerCACert, err = getAPIServerExtensionCACert(client) + if err != nil { + return nil, nil, err + } } - serverKey, serverCert, caCert, err := getOrGenerateKeyCertsFromSecret( - ctx, client, options) + + serverKey, serverCert, caCert, err := getOrGenerateKeyCertsFromSecret(ctx, client, options) if err != nil { return nil, nil, err } - tlsConfig, err := makeTLSConfig(serverCert, serverKey, apiServerCACert) + tlsConfig, err := makeTLSConfig(serverCert, serverKey, apiServerCACert, options.ClientAuth) if err != nil { return nil, nil, err } @@ -287,32 +294,25 @@ func (ac *AdmissionController) Run(stop <-chan struct{}) error { logger.Error("Failed to register webhook", zap.Error(err)) return err } - defer func() { - if err := ac.unregister(ctx, cl); err != nil { - logger.Error("Failed to unregister webhook", zap.Error(err)) - } - }() logger.Info("Successfully registered webhook") case <-stop: return nil } + serverBootstrapErrCh := make(chan struct{}) go func() { if err := server.ListenAndServeTLS("", ""); err != nil { logger.Error("ListenAndServeTLS for admission webhook returned error", zap.Error(err)) + close(serverBootstrapErrCh) } }() - <-stop - server.Close() // nolint: errcheck - return nil -} -// Unregister unregisters the external admission webhook -func (ac *AdmissionController) unregister( - ctx context.Context, client clientadmissionregistrationv1beta1.MutatingWebhookConfigurationInterface) error { - logger := logging.FromContext(ctx) - logger.Info("Exiting..") - return nil + select { + case <-stop: + return server.Close() + case <-serverBootstrapErrCh: + return errors.New("webhook server bootstrap failed") + } } // Register registers the external admission webhook for pilot @@ -324,8 +324,7 @@ func (ac *AdmissionController) register( var rules []admissionregistrationv1beta1.RuleWithOperations for gvk := range ac.Handlers { - // Lousy pluralizer - plural := strings.ToLower(gvk.Kind) + "s" + plural := strings.ToLower(inflect.Pluralize(gvk.Kind)) rules = append(rules, admissionregistrationv1beta1.RuleWithOperations{ Operations: []admissionregistrationv1beta1.OperationType{ @@ -502,7 +501,6 @@ func (ac *AdmissionController) mutate(ctx context.Context, kind metav1.GroupVers if len(newBytes) != 0 { newDecoder := json.NewDecoder(bytes.NewBuffer(newBytes)) - newDecoder.DisallowUnknownFields() if err := newDecoder.Decode(&newObj); err != nil { return nil, fmt.Errorf("cannot decode incoming new object: %v", err) } @@ -513,7 +511,6 @@ func (ac *AdmissionController) mutate(ctx context.Context, kind metav1.GroupVers if len(oldBytes) != 0 { oldDecoder := json.NewDecoder(bytes.NewBuffer(oldBytes)) - oldDecoder.DisallowUnknownFields() if err := oldDecoder.Decode(&oldObj); err != nil { return nil, fmt.Errorf("cannot decode incoming old object: %v", err) } diff --git a/vendor/github.com/knative/serving/AUTHORS b/vendor/github.com/knative/serving/AUTHORS index 4e068958755..5ab90824ca2 100644 --- a/vendor/github.com/knative/serving/AUTHORS +++ b/vendor/github.com/knative/serving/AUTHORS @@ -6,4 +6,5 @@ Google LLC Pivotal Software, Inc. IBM Corp -Red Hat, Inc. \ No newline at end of file +Red Hat, Inc. +Cisco Systems, Inc. diff --git a/vendor/github.com/knative/serving/cmd/activator/kodata/LICENSE b/vendor/github.com/knative/serving/cmd/activator/kodata/LICENSE new file mode 120000 index 00000000000..5853aaea53b --- /dev/null +++ b/vendor/github.com/knative/serving/cmd/activator/kodata/LICENSE @@ -0,0 +1 @@ +../../../LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/serving/cmd/activator/kodata/VENDOR-LICENSE b/vendor/github.com/knative/serving/cmd/activator/kodata/VENDOR-LICENSE new file mode 120000 index 00000000000..3cc89764519 --- /dev/null +++ b/vendor/github.com/knative/serving/cmd/activator/kodata/VENDOR-LICENSE @@ -0,0 +1 @@ +../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/serving/cmd/autoscaler/kodata/LICENSE b/vendor/github.com/knative/serving/cmd/autoscaler/kodata/LICENSE new file mode 120000 index 00000000000..5853aaea53b --- /dev/null +++ b/vendor/github.com/knative/serving/cmd/autoscaler/kodata/LICENSE @@ -0,0 +1 @@ +../../../LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/serving/cmd/autoscaler/kodata/VENDOR-LICENSE b/vendor/github.com/knative/serving/cmd/autoscaler/kodata/VENDOR-LICENSE new file mode 120000 index 00000000000..3cc89764519 --- /dev/null +++ b/vendor/github.com/knative/serving/cmd/autoscaler/kodata/VENDOR-LICENSE @@ -0,0 +1 @@ +../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/serving/cmd/controller/kodata/LICENSE b/vendor/github.com/knative/serving/cmd/controller/kodata/LICENSE new file mode 120000 index 00000000000..5853aaea53b --- /dev/null +++ b/vendor/github.com/knative/serving/cmd/controller/kodata/LICENSE @@ -0,0 +1 @@ +../../../LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/serving/cmd/controller/kodata/VENDOR-LICENSE b/vendor/github.com/knative/serving/cmd/controller/kodata/VENDOR-LICENSE new file mode 120000 index 00000000000..3cc89764519 --- /dev/null +++ b/vendor/github.com/knative/serving/cmd/controller/kodata/VENDOR-LICENSE @@ -0,0 +1 @@ +../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/serving/cmd/queue/kodata/LICENSE b/vendor/github.com/knative/serving/cmd/queue/kodata/LICENSE new file mode 120000 index 00000000000..5853aaea53b --- /dev/null +++ b/vendor/github.com/knative/serving/cmd/queue/kodata/LICENSE @@ -0,0 +1 @@ +../../../LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/serving/cmd/queue/kodata/VENDOR-LICENSE b/vendor/github.com/knative/serving/cmd/queue/kodata/VENDOR-LICENSE new file mode 120000 index 00000000000..3cc89764519 --- /dev/null +++ b/vendor/github.com/knative/serving/cmd/queue/kodata/VENDOR-LICENSE @@ -0,0 +1 @@ +../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/serving/cmd/webhook/kodata/LICENSE b/vendor/github.com/knative/serving/cmd/webhook/kodata/LICENSE new file mode 120000 index 00000000000..5853aaea53b --- /dev/null +++ b/vendor/github.com/knative/serving/cmd/webhook/kodata/LICENSE @@ -0,0 +1 @@ +../../../LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/serving/cmd/webhook/kodata/VENDOR-LICENSE b/vendor/github.com/knative/serving/cmd/webhook/kodata/VENDOR-LICENSE new file mode 120000 index 00000000000..3cc89764519 --- /dev/null +++ b/vendor/github.com/knative/serving/cmd/webhook/kodata/VENDOR-LICENSE @@ -0,0 +1 @@ +../../../third_party/VENDOR-LICENSE \ No newline at end of file diff --git a/vendor/github.com/knative/serving/config/300-imagecache.yaml b/vendor/github.com/knative/serving/config/300-imagecache.yaml new file mode 120000 index 00000000000..f10d6dacf6a --- /dev/null +++ b/vendor/github.com/knative/serving/config/300-imagecache.yaml @@ -0,0 +1 @@ +../vendor/github.com/knative/caching/config/image.yaml \ No newline at end of file diff --git a/vendor/github.com/knative/serving/pkg/apis/autoscaling/register.go b/vendor/github.com/knative/serving/pkg/apis/autoscaling/register.go new file mode 100644 index 00000000000..38626e0b85b --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/apis/autoscaling/register.go @@ -0,0 +1,36 @@ +/* +Copyright 2018 The Knative 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 autoscaling + +const ( + InternalGroupName = "autoscaling.internal.knative.dev" + + GroupName = "autoscaling.knative.dev" + + // ClassAnnotationKey is the annotation for the explicit class of autoscaler + // that a particular resource has opted into. For example, + // autoscaling.knative.dev/class: foo + // This uses a different domain because unlike the resource, it is user-facing. + ClassAnnotationKey = GroupName + "/class" + + MinScaleAnnotationKey = GroupName + "/minScale" + MaxScaleAnnotationKey = GroupName + "/maxScale" + + // KPALabelKey is the label key attached to a K8s Service to hint to the KPA + // which services/endpoints should trigger reconciles. + KPALabelKey = GroupName + "/kpa" +) diff --git a/pkg/apis/channels/v1alpha1/clusterbus_defaults.go b/vendor/github.com/knative/serving/pkg/apis/autoscaling/v1alpha1/doc.go similarity index 88% rename from pkg/apis/channels/v1alpha1/clusterbus_defaults.go rename to vendor/github.com/knative/serving/pkg/apis/autoscaling/v1alpha1/doc.go index 2dad3ce2327..bcdf80570a8 100644 --- a/pkg/apis/channels/v1alpha1/clusterbus_defaults.go +++ b/vendor/github.com/knative/serving/pkg/apis/autoscaling/v1alpha1/doc.go @@ -14,8 +14,6 @@ See the License for the specific language governing permissions and limitations under the License. */ +// +k8s:deepcopy-gen=package +// +groupName=autoscaling.internal.knative.dev package v1alpha1 - -func (b *ClusterBus) SetDefaults() { - b.Spec.SetDefaults() -} diff --git a/pkg/apis/feeds/v1alpha1/event_source_validation.go b/vendor/github.com/knative/serving/pkg/apis/autoscaling/v1alpha1/kpa_defaults.go similarity index 57% rename from pkg/apis/feeds/v1alpha1/event_source_validation.go rename to vendor/github.com/knative/serving/pkg/apis/autoscaling/v1alpha1/kpa_defaults.go index 277babf6ea3..6d168478d89 100644 --- a/pkg/apis/feeds/v1alpha1/event_source_validation.go +++ b/vendor/github.com/knative/serving/pkg/apis/autoscaling/v1alpha1/kpa_defaults.go @@ -17,13 +17,17 @@ limitations under the License. package v1alpha1 import ( - "github.com/knative/pkg/apis" + servingv1alpha1 "github.com/knative/serving/pkg/apis/serving/v1alpha1" ) -func (es *EventSource) Validate() *apis.FieldError { - return es.Spec.Validate().ViaField("spec") +func (r *PodAutoscaler) SetDefaults() { + r.Spec.SetDefaults() } -func (ess *EventSourceSpec) Validate() *apis.FieldError { - return ess.CommonEventSourceSpec.Validate() +func (rs *PodAutoscalerSpec) SetDefaults() { + // When ConcurrencyModel is specified but ContainerConcurrency + // is not (0), use the ConcurrencyModel value. + if rs.ConcurrencyModel == servingv1alpha1.RevisionRequestConcurrencyModelSingle && rs.ContainerConcurrency == 0 { + rs.ContainerConcurrency = 1 + } } diff --git a/vendor/github.com/knative/serving/pkg/apis/autoscaling/v1alpha1/kpa_types.go b/vendor/github.com/knative/serving/pkg/apis/autoscaling/v1alpha1/kpa_types.go new file mode 100644 index 00000000000..c5e73d28dd8 --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/apis/autoscaling/v1alpha1/kpa_types.go @@ -0,0 +1,191 @@ +/* +Copyright 2018 The Knative Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha1 + +import ( + "strconv" + "time" + + autoscalingv1 "k8s.io/api/autoscaling/v1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "github.com/knative/pkg/apis" + duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" + "github.com/knative/serving/pkg/apis/autoscaling" + servingv1alpha1 "github.com/knative/serving/pkg/apis/serving/v1alpha1" +) + +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// PodAutoscaler is a Knative abstraction that encapsulates the interface by which Knative +// components instantiate autoscalers. This definition is an abstraction that may be backed +// by multiple definitions. For more information, see the Knative Pluggability presentation: +// https://docs.google.com/presentation/d/10KWynvAJYuOEWy69VBa6bHJVCqIsz1TNdEKosNvcpPY/edit +type PodAutoscaler struct { + metav1.TypeMeta `json:",inline"` + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // Spec holds the desired state of the PodAutoscaler (from the client). + // +optional + Spec PodAutoscalerSpec `json:"spec,omitempty"` + + // Status communicates the observed state of the PodAutoscaler (from the controller). + // +optional + Status PodAutoscalerStatus `json:"status,omitempty"` +} + +// Check that PodAutoscaler can be validated, can be defaulted, and has immutable fields. +var _ apis.Validatable = (*PodAutoscaler)(nil) +var _ apis.Defaultable = (*PodAutoscaler)(nil) +var _ apis.Immutable = (*PodAutoscaler)(nil) + +// Check that ConfigurationStatus may have its conditions managed. +var _ duckv1alpha1.ConditionsAccessor = (*PodAutoscalerStatus)(nil) + +// PodAutoscalerSpec holds the desired state of the PodAutoscaler (from the client). +type PodAutoscalerSpec struct { + // TODO: Generation does not work correctly with CRD. They are scrubbed + // by the APIserver (https://github.com/kubernetes/kubernetes/issues/58778) + // So, we add Generation here. Once that gets fixed, remove this and use + // ObjectMeta.Generation instead. + // +optional + Generation int64 `json:"generation,omitempty"` + + // ConcurrencyModel specifies the desired concurrency model + // (Single or Multi) for the scale target. Defaults to Multi. + // Deprecated in favor of ContainerConcurrency. + // +optional + ConcurrencyModel servingv1alpha1.RevisionRequestConcurrencyModelType `json:"concurrencyModel,omitempty"` + + // ContainerConcurrency specifies the maximum allowed + // in-flight (concurrent) requests per container of the Revision. + // Defaults to `0` which means unlimited concurrency. + // This field replaces ConcurrencyModel. A value of `1` + // is equivalent to `Single` and `0` is equivalent to `Multi`. + // +optional + ContainerConcurrency servingv1alpha1.RevisionContainerConcurrencyType `json:"containerConcurrency,omitempty"` + + // ScaleTargetRef defines the /scale-able resource that this PodAutoscaler + // is responsible for quickly right-sizing. + ScaleTargetRef autoscalingv1.CrossVersionObjectReference `json:"scaleTargetRef"` + + // ServiceName holds the name of a core Kubernetes Service resource that + // load balances over the pods referenced by the ScaleTargetRef. + ServiceName string `json:"serviceName"` +} + +const ( + // PodAutoscalerConditionReady is set when the revision is starting to materialize + // runtime resources, and becomes true when those resources are ready. + PodAutoscalerConditionReady = duckv1alpha1.ConditionReady + // PodAutoscalerConditionActive is set when the PodAutoscaler's ScaleTargetRef is receiving traffic. + PodAutoscalerConditionActive duckv1alpha1.ConditionType = "Active" +) + +var podCondSet = duckv1alpha1.NewLivingConditionSet(PodAutoscalerConditionActive) + +// PodAutoscalerStatus communicates the observed state of the PodAutoscaler (from the controller). +type PodAutoscalerStatus struct { + // Conditions communicates information about ongoing/complete + // reconciliation processes that bring the "spec" inline with the observed + // state of the world. + // +optional + Conditions duckv1alpha1.Conditions `json:"conditions,omitempty"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// PodAutoscalerList is a list of PodAutoscaler resources +type PodAutoscalerList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata"` + + Items []PodAutoscaler `json:"items"` +} + +func (kpa *PodAutoscaler) scaleBoundInt32(key string) int32 { + if s, ok := kpa.Annotations[key]; ok { + // no error check: relying on validation + i, _ := strconv.ParseInt(s, 10, 32) + return int32(i) + } + return 0 +} + +// ScaleBounds returns scale bounds annotations values as a tuple: +// `(min, max int32)`. The value of 0 for any of min or max means the bound is +// not set +func (kpa *PodAutoscaler) ScaleBounds() (min, max int32) { + min = kpa.scaleBoundInt32(autoscaling.MinScaleAnnotationKey) + max = kpa.scaleBoundInt32(autoscaling.MaxScaleAnnotationKey) + return +} + +// IsReady looks at the conditions and if the Status has a condition +// PodAutoscalerConditionReady returns true if ConditionStatus is True +func (rs *PodAutoscalerStatus) IsReady() bool { + return podCondSet.Manage(rs).IsHappy() +} + +func (rs *PodAutoscalerStatus) GetCondition(t duckv1alpha1.ConditionType) *duckv1alpha1.Condition { + return podCondSet.Manage(rs).GetCondition(t) +} + +func (rs *PodAutoscalerStatus) InitializeConditions() { + podCondSet.Manage(rs).InitializeConditions() +} + +func (rs *PodAutoscalerStatus) MarkActive() { + podCondSet.Manage(rs).MarkTrue(PodAutoscalerConditionActive) +} + +func (rs *PodAutoscalerStatus) MarkActivating(reason, message string) { + podCondSet.Manage(rs).MarkUnknown(PodAutoscalerConditionActive, reason, message) +} + +func (rs *PodAutoscalerStatus) MarkInactive(reason, message string) { + podCondSet.Manage(rs).MarkFalse(PodAutoscalerConditionActive, reason, message) +} + +// CanScaleToZero checks whether the pod autoscaler has been in an inactive state +// for at least the specified grace period. +func (rs *PodAutoscalerStatus) CanScaleToZero(gracePeriod time.Duration) bool { + if cond := rs.GetCondition(PodAutoscalerConditionActive); cond != nil { + switch cond.Status { + case corev1.ConditionFalse: + // Check that this PodAutoscaler has been inactive for + // at least the grace period. + return time.Now().After(cond.LastTransitionTime.Inner.Add(gracePeriod)) + } + } + return false +} + +// GetConditions returns the Conditions array. This enables generic handling of +// conditions by implementing the duckv1alpha1.Conditions interface. +func (rs *PodAutoscalerStatus) GetConditions() duckv1alpha1.Conditions { + return rs.Conditions +} + +// SetConditions sets the Conditions array. This enables generic handling of +// conditions by implementing the duckv1alpha1.Conditions interface. +func (rs *PodAutoscalerStatus) SetConditions(conditions duckv1alpha1.Conditions) { + rs.Conditions = conditions +} diff --git a/vendor/github.com/knative/serving/pkg/apis/autoscaling/v1alpha1/kpa_validation.go b/vendor/github.com/knative/serving/pkg/apis/autoscaling/v1alpha1/kpa_validation.go new file mode 100644 index 00000000000..97bd744955d --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/apis/autoscaling/v1alpha1/kpa_validation.go @@ -0,0 +1,79 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha1 + +import ( + "github.com/google/go-cmp/cmp" + autoscalingv1 "k8s.io/api/autoscaling/v1" + "k8s.io/apimachinery/pkg/api/equality" + + "github.com/knative/pkg/apis" + servingv1alpha1 "github.com/knative/serving/pkg/apis/serving/v1alpha1" +) + +func (rt *PodAutoscaler) Validate() *apis.FieldError { + return servingv1alpha1.ValidateObjectMetadata(rt.GetObjectMeta()).ViaField("metadata").Also(rt.Spec.Validate().ViaField("spec")) +} + +func (rs *PodAutoscalerSpec) Validate() *apis.FieldError { + if equality.Semantic.DeepEqual(rs, &PodAutoscalerSpec{}) { + return apis.ErrMissingField(apis.CurrentField) + } + errs := validateReference(rs.ScaleTargetRef).ViaField("scaleTargetRef") + if rs.ServiceName == "" { + errs = errs.Also(apis.ErrMissingField("serviceName")) + } + if err := rs.ConcurrencyModel.Validate(); err != nil { + errs = errs.Also(err.ViaField("concurrencyModel")) + } else if err := servingv1alpha1.ValidateContainerConcurrency(rs.ContainerConcurrency, rs.ConcurrencyModel); err != nil { + errs = errs.Also(err) + } + return errs +} + +func validateReference(ref autoscalingv1.CrossVersionObjectReference) *apis.FieldError { + if equality.Semantic.DeepEqual(ref, autoscalingv1.CrossVersionObjectReference{}) { + return apis.ErrMissingField(apis.CurrentField) + } + var errs *apis.FieldError + if ref.Kind == "" { + errs = errs.Also(apis.ErrMissingField("kind")) + } + if ref.Name == "" { + errs = errs.Also(apis.ErrMissingField("name")) + } + if ref.APIVersion == "" { + errs = errs.Also(apis.ErrMissingField("apiVersion")) + } + return errs +} + +func (current *PodAutoscaler) CheckImmutableFields(og apis.Immutable) *apis.FieldError { + original, ok := og.(*PodAutoscaler) + if !ok { + return &apis.FieldError{Message: "The provided original was not a PodAutoscaler"} + } + + if diff := cmp.Diff(original.Spec, current.Spec); diff != "" { + return &apis.FieldError{ + Message: "Immutable fields changed (-old +new)", + Paths: []string{"spec"}, + Details: diff, + } + } + return nil +} diff --git a/vendor/github.com/knative/serving/pkg/apis/istio/v1alpha3/register.go b/vendor/github.com/knative/serving/pkg/apis/autoscaling/v1alpha1/register.go similarity index 84% rename from vendor/github.com/knative/serving/pkg/apis/istio/v1alpha3/register.go rename to vendor/github.com/knative/serving/pkg/apis/autoscaling/v1alpha1/register.go index 2a70cb2340d..92d4fee7f36 100644 --- a/vendor/github.com/knative/serving/pkg/apis/istio/v1alpha3/register.go +++ b/vendor/github.com/knative/serving/pkg/apis/autoscaling/v1alpha1/register.go @@ -1,5 +1,5 @@ /* -Copyright 2018 The Knative Authors +Copyright 2018 The Knative Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,17 +14,18 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1alpha3 +package v1alpha1 import ( - "github.com/knative/serving/pkg/apis/istio" + "github.com/knative/serving/pkg/apis/autoscaling" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ) // SchemeGroupVersion is group version used to register these objects -var SchemeGroupVersion = schema.GroupVersion{Group: istio.GroupName, Version: "v1alpha3"} +var SchemeGroupVersion = schema.GroupVersion{Group: autoscaling.InternalGroupName, Version: "v1alpha1"} // Kind takes an unqualified kind and returns back a Group qualified GroupKind func Kind(kind string) schema.GroupKind { @@ -44,10 +45,8 @@ var ( // Adds the list of known types to Scheme. func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes(SchemeGroupVersion, - &VirtualService{}, - &Gateway{}, - &VirtualServiceList{}, - &GatewayList{}, + &PodAutoscaler{}, + &PodAutoscalerList{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil diff --git a/vendor/github.com/knative/serving/pkg/apis/autoscaling/v1alpha1/zz_generated.deepcopy.go b/vendor/github.com/knative/serving/pkg/apis/autoscaling/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 00000000000..466269da328 --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/apis/autoscaling/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,129 @@ +// +build !ignore_autogenerated + +/* +Copyright 2018 The Knative 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package v1alpha1 + +import ( + duck_v1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodAutoscaler) DeepCopyInto(out *PodAutoscaler) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + out.Spec = in.Spec + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodAutoscaler. +func (in *PodAutoscaler) DeepCopy() *PodAutoscaler { + if in == nil { + return nil + } + out := new(PodAutoscaler) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PodAutoscaler) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } else { + return nil + } +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodAutoscalerList) DeepCopyInto(out *PodAutoscalerList) { + *out = *in + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PodAutoscaler, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodAutoscalerList. +func (in *PodAutoscalerList) DeepCopy() *PodAutoscalerList { + if in == nil { + return nil + } + out := new(PodAutoscalerList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PodAutoscalerList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } else { + return nil + } +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodAutoscalerSpec) DeepCopyInto(out *PodAutoscalerSpec) { + *out = *in + out.ScaleTargetRef = in.ScaleTargetRef + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodAutoscalerSpec. +func (in *PodAutoscalerSpec) DeepCopy() *PodAutoscalerSpec { + if in == nil { + return nil + } + out := new(PodAutoscalerSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PodAutoscalerStatus) DeepCopyInto(out *PodAutoscalerStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(duck_v1alpha1.Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodAutoscalerStatus. +func (in *PodAutoscalerStatus) DeepCopy() *PodAutoscalerStatus { + if in == nil { + return nil + } + out := new(PodAutoscalerStatus) + in.DeepCopyInto(out) + return out +} diff --git a/vendor/github.com/knative/serving/pkg/apis/istio/register.go b/vendor/github.com/knative/serving/pkg/apis/istio/register.go deleted file mode 100644 index 647eb38a0e1..00000000000 --- a/vendor/github.com/knative/serving/pkg/apis/istio/register.go +++ /dev/null @@ -1,21 +0,0 @@ -/* -Copyright 2018 The Knative 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 istio - -const ( - GroupName = "networking.istio.io" -) diff --git a/vendor/github.com/knative/serving/pkg/apis/istio/v1alpha3/gateway_types.go b/vendor/github.com/knative/serving/pkg/apis/istio/v1alpha3/gateway_types.go deleted file mode 100644 index 0822a5e3b4e..00000000000 --- a/vendor/github.com/knative/serving/pkg/apis/istio/v1alpha3/gateway_types.go +++ /dev/null @@ -1,318 +0,0 @@ -/* -Copyright 2018 The Knative 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 v1alpha3 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// Gateway describes a load balancer operating at the edge of the mesh -// receiving incoming or outgoing HTTP/TCP connections. The specification -// describes a set of ports that should be exposed, the type of protocol to -// use, SNI configuration for the load balancer, etc. -// -// For example, the following gateway spec sets up a proxy to act as a load -// balancer exposing port 80 and 9080 (http), 443 (https), and port 2379 -// (TCP) for ingress. The gateway will be applied to the proxy running on -// a pod with labels "app: my-gateway-controller". While Istio will configure the -// proxy to listen on these ports, it is the responsibility of the user to -// ensure that external traffic to these ports are allowed into the mesh. -// -// apiVersion: networking.istio.io/v1alpha3 -// kind: Gateway -// metadata: -// name: my-gateway -// spec: -// selector: -// app: my-gatweway-controller -// servers: -// - port: -// number: 80 -// name: http -// protocol: HTTP -// hosts: -// - uk.bookinfo.com -// - eu.bookinfo.com -// tls: -// httpsRedirect: true # sends 302 redirect for http requests -// - port: -// number: 443 -// name: https -// protocol: HTTPS -// hosts: -// - uk.bookinfo.com -// - eu.bookinfo.com -// tls: -// mode: SIMPLE #enables HTTPS on this port -// serverCertificate: /etc/certs/servercert.pem -// privateKey: /etc/certs/privatekey.pem -// - port: -// number: 9080 -// name: http-wildcard -// protocol: HTTP -// # no hosts implies wildcard match -// - port: -// number: 2379 #to expose internal service via external port 2379 -// name: mongo -// protocol: MONGO -// -// The gateway specification above describes the L4-L6 properties of a load -// balancer. A VirtualService can then be bound to a gateway to control -// the forwarding of traffic arriving at a particular host or gateway port. -// -// For example, the following VirtualService splits traffic for -// https://uk.bookinfo.com/reviews, https://eu.bookinfo.com/reviews, -// http://uk.bookinfo.com:9080/reviews, http://eu.bookinfo.com:9080/reviews -// into two versions (prod and qa) of an internal reviews service on port -// 9080. In addition, requests containing the cookie user: dev-123 will be -// sent to special port 7777 in the qa version. The same rule is also -// applicable inside the mesh for requests to the reviews.prod -// service. This rule is applicable across ports 443, 9080. Note that -// http://uk.bookinfo.com gets redirected to https://uk.bookinfo.com -// (i.e. 80 redirects to 443). -// -// apiVersion: networking.istio.io/v1alpha3 -// kind: VirtualService -// metadata: -// name: bookinfo-rule -// spec: -// hosts: -// - reviews.prod -// - uk.bookinfo.com -// - eu.bookinfo.com -// gateways: -// - my-gateway -// - mesh # applies to all the sidecars in the mesh -// http: -// - match: -// - headers: -// cookie: -// user: dev-123 -// route: -// - destination: -// port: -// number: 7777 -// name: reviews.qa -// - match: -// uri: -// prefix: /reviews/ -// route: -// - destination: -// port: -// number: 9080 # can be omitted if its the only port for reviews -// name: reviews.prod -// weight: 80 -// - destination: -// name: reviews.qa -// weight: 20 -// -// The following VirtualService forwards traffic arriving at (external) port -// 2379 from 172.17.16.0/24 subnet to internal Mongo server on port 5555. This -// rule is not applicable internally in the mesh as the gateway list omits -// the reserved name "mesh". -// -// apiVersion: networking.istio.io/v1alpha3 -// kind: VirtualService -// metadata: -// name: bookinfo-Mongo -// spec: -// hosts: -// - mongosvr #name of Mongo service -// gateways: -// - my-gateway -// tcp: -// - match: -// - port: -// number: 2379 -// sourceSubnet: "172.17.16.0/24" -// route: -// - destination: -// name: mongo.prod -// -type Gateway struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec GatewaySpec `json:"spec"` -} - -type GatewaySpec struct { - // REQUIRED: A list of server specifications. - Servers []Server `json:"servers"` - - // One or more labels that indicate a specific set of pods/VMs - // on which this gateway configuration should be applied. - // If no selectors are provided, the gateway will be implemented by - // the default istio-ingress controller. - Selector map[string]string `json:"selector,omitempty"` -} - -// Server describes the properties of the proxy on a given load balancer port. -// For example, -// -// apiVersion: networking.istio.io/v1alpha3 -// kind: Gateway -// metadata: -// name: my-ingress -// spec: -// selector: -// app: my-ingress-controller -// servers: -// - port: -// number: 80 -// name: http2 -// protocol: HTTP2 -// -// Another example -// -// apiVersion: networking.istio.io/v1alpha3 -// kind: Gateway -// metadata: -// name: my-tcp-ingress -// spec: -// selector: -// app: my-tcp-ingress-controller -// servers: -// - port: -// number: 27018 -// name: mongo -// protocol: MONGO -// -// The following is an example of TLS configuration for port 443 -// -// apiVersion: networking.istio.io/v1alpha3 -// kind: Gateway -// metadata: -// name: my-tls-ingress -// spec: -// selector: -// app: my-tls-ingress-controller -// servers: -// - port: -// number: 443 -// name: https -// protocol: HTTPS -// tls: -// mode: SIMPLE -// serverCertificate: /etc/certs/server.pem -// privateKey: /etc/certs/privatekey.pem -// -type Server struct { - // REQUIRED: The Port on which the proxy should listen for incoming - // connections - Port Port `json:"port"` - - // A list of hosts exposed by this gateway. While - // typically applicable to HTTP services, it can also be used for TCP - // services using TLS with SNI. Standard DNS wildcard prefix syntax - // is permitted. - // - // A VirtualService that is bound to a gateway must having a matching host - // in its default destination. Specifically one of the VirtualService - // destination hosts is a strict suffix of a gateway host or - // a gateway host is a suffix of one of the VirtualService hosts. - Hosts []string `json:"hosts,omitempty"` - - // Set of TLS related options that govern the server's behavior. Use - // these options to control if all http requests should be redirected to - // https, and the TLS modes to use. - TLS *TLSOptions `json:"tls,omitempty"` -} - -type TLSOptions struct { - // If set to true, the load balancer will send a 302 redirect for all - // http connections, asking the clients to use HTTPS. - HttpsRedirect bool `json:"httpsRedirect"` - - // Optional: Indicates whether connections to this port should be - // secured using TLS. The value of this field determines how TLS is - // enforced. - Mode TLSMode `json:"mode,omitempty"` - - // REQUIRED if mode is "SIMPLE" or "MUTUAL". The path to the file - // holding the server-side TLS certificate to use. - ServerCertificate string `json:"serverCertificate"` - - // REQUIRED if mode is "SIMPLE" or "MUTUAL". The path to the file - // holding the server's private key. - PrivateKey string `json:"privateKey"` - - // REQUIRED if mode is "MUTUAL". The path to a file containing - // certificate authority certificates to use in verifying a presented - // client side certificate. - CaCertificates string `json:"caCertificates"` - - // A list of alternate names to verify the subject identity in the - // certificate presented by the client. - SubjectAltNames []string `json:"subjectAltNames"` -} - -// TLS modes enforced by the proxy -type TLSMode string - -const ( - // If set to "PASSTHROUGH", the proxy will forward the connection - // to the upstream server selected based on the SNI string presented - // by the client. - TLSModePassThrough TLSMode = "PASSTHROUGH" - - // If set to "SIMPLE", the proxy will secure connections with - // standard TLS semantics. - TLSModeSimple TLSMode = "SIMPLE" - - // If set to "MUTUAL", the proxy will secure connections to the - // upstream using mutual TLS by presenting client certificates for - // authentication. - TLSModeMutual TLSMode = "MUTUAL" -) - -// Port describes the properties of a specific port of a service. -type Port struct { - // REQUIRED: A valid non-negative integer port number. - Number int `json:"number"` - - // REQUIRED: The protocol exposed on the port. - // MUST BE one of HTTP|HTTPS|GRPC|HTTP2|MONGO|TCP. - Protocol PortProtocol `json:"protocol"` - - // Label assigned to the port. - Name string `json:"name,omitempty"` -} - -type PortProtocol string - -const ( - ProtocolHTTP PortProtocol = "HTTP" - ProtocolHTTPS PortProtocol = "HTTPS" - ProtocolGRPC PortProtocol = "GRPC" - ProtocolHTTP2 PortProtocol = "HTTP2" - ProtocolMongo PortProtocol = "Mongo" - ProtocolTCP PortProtocol = "TCP" -) - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// GatewayList is a list of Gateway resources -type GatewayList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []Gateway `json:"items"` -} diff --git a/vendor/github.com/knative/serving/pkg/apis/istio/v1alpha3/virtualservice_types.go b/vendor/github.com/knative/serving/pkg/apis/istio/v1alpha3/virtualservice_types.go deleted file mode 100644 index 87e2f9815ef..00000000000 --- a/vendor/github.com/knative/serving/pkg/apis/istio/v1alpha3/virtualservice_types.go +++ /dev/null @@ -1,783 +0,0 @@ -/* -Copyright 2018 The Knative 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 v1alpha3 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// VirtualService -type VirtualService struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec VirtualServiceSpec `json:"spec"` -} - -// A VirtualService defines a set of traffic routing rules to apply when a host is -// addressed. Each routing rule defines matching criteria for traffic of a specific -// protocol. If the traffic is matched, then it is sent to a named destination service -// (or subset/version of it) defined in the registry. -// -// The source of traffic can also be matched in a routing rule. This allows routing -// to be customized for specific client contexts. -// -// The following example routes all HTTP traffic by default to -// pods of the reviews service with label "version: v1". In addition, -// HTTP requests containing /wpcatalog/, /consumercatalog/ url prefixes will -// be rewritten to /newcatalog and sent to pods with label "version: v2". The -// rules will be applied at the gateway named "bookinfo" as well as at all -// the sidecars in the mesh (indicated by the reserved gateway name -// "mesh"). -// -// apiVersion: networking.istio.io/v1alpha3 -// kind: VirtualService -// metadata: -// name: reviews-route -// spec: -// hosts: -// - reviews -// gateways: # if omitted, defaults to "mesh" -// - bookinfo -// - mesh -// http: -// - match: -// - uri: -// prefix: "/wpcatalog" -// - uri: -// prefix: "/consumercatalog" -// rewrite: -// uri: "/newcatalog" -// route: -// - destination: -// host: reviews -// subset: v2 -// - route: -// - destination: -// host: reviews -// subset: v1 -// -// A subset/version of a route destination is identified with a reference -// to a named service subset which must be declared in a corresponding -// DestinationRule. -// -// apiVersion: networking.istio.io/v1alpha3 -// kind: DestinationRule -// metadata: -// name: reviews-destination -// spec: -// host: reviews -// subsets: -// - name: v1 -// labels: -// version: v1 -// - name: v2 -// labels: -// version: v2 -// -// A host name can be defined by only one VirtualService. A single -// VirtualService can be used to describe traffic properties for multiple -// HTTP and TCP ports. -type VirtualServiceSpec struct { - // REQUIRED. The destination address for traffic captured by this virtual - // service. Could be a DNS name with wildcard prefix or a CIDR - // prefix. Depending on the platform, short-names can also be used - // instead of a FQDN (i.e. has no dots in the name). In such a scenario, - // the FQDN of the host would be derived based on the underlying - // platform. - // - // For example on Kubernetes, when hosts contains a short name, Istio will - // interpret the short name based on the namespace of the rule. Thus, when a - // client namespace applies a rule in the "default" namespace containing a name - // "reviews, Istio will setup routes to the "reviews.default.svc.cluster.local" - // service. However, if a different name such as "reviews.sales.svc.cluster.local" - // is used, it would be treated as a FQDN during virtual host matching. - // In Consul, a plain service name would be resolved to the FQDN - // "reviews.service.consul". - // - // Note that the hosts field applies to both HTTP and TCP - // services. Service inside the mesh, i.e., those found in the service - // registry, must always be referred to using their alphanumeric - // names. IP addresses or CIDR prefixes are allowed only for services - // defined via the Gateway. - Hosts []string `json:"hosts"` - - // The names of gateways and sidecars that should apply these routes. A - // single VirtualService is used for sidecars inside the mesh as well - // as for one or more gateways. The selection condition imposed by this field - // can be overridden using the source field in the match conditions of HTTP/TCP - // routes. The reserved word "mesh" is used to imply all the sidecars in - // the mesh. When this field is omitted, the default gateway ("mesh") - // will be used, which would apply the rule to all sidecars in the - // mesh. If a list of gateway names is provided, the rules will apply - // only to the gateways. To apply the rules to both gateways and sidecars, - // specify "mesh" as one of the gateway names. - Gateways []string `json:"gateways,omitempty"` - - // An ordered list of route rules for HTTP traffic. - // The first rule matching an incoming request is used. - Http []HTTPRoute `json:"http,omitempty"` - - // An ordered list of route rules for TCP traffic. - // The first rule matching an incoming request is used. - Tcp []TCPRoute `json:"tcp,omitempty"` -} - -// Describes match conditions and actions for routing HTTP/1.1, HTTP2, and -// gRPC traffic. See VirtualService for usage examples. -type HTTPRoute struct { - // Match conditions to be satisfied for the rule to be - // activated. All conditions inside a single match block have AND - // semantics, while the list of match blocks have OR semantics. The rule - // is matched if any one of the match blocks succeed. - Match []HTTPMatchRequest `json:"match,omitempty"` - - // A http rule can either redirect or forward (default) traffic. The - // forwarding target can be one of several versions of a service (see - // glossary in beginning of document). Weights associated with the - // service version determine the proportion of traffic it receives. - Route []DestinationWeight `json:"route,omitempty"` - - // A http rule can either redirect or forward (default) traffic. If - // traffic passthrough option is specified in the rule, - // route/redirect will be ignored. The redirect primitive can be used to - // send a HTTP 302 redirect to a different URI or Authority. - Redirect *HTTPRedirect `json:"redirect,omitempty"` - - // Rewrite HTTP URIs and Authority headers. Rewrite cannot be used with - // Redirect primitive. Rewrite will be performed before forwarding. - Rewrite *HTTPRewrite `json:"rewrite,omitempty"` - - // Indicates that a HTTP/1.1 client connection to this particular route - // should be allowed (and expected) to upgrade to a WebSocket connection. - // The default is false. Istio's reference sidecar implementation (Envoy) - // expects the first request to this route to contain the WebSocket - // upgrade headers. Otherwise, the request will be rejected. Note that - // Websocket allows secondary protocol negotiation which may then be - // subject to further routing rules based on the protocol selected. - WebsocketUpgrade bool `json:"websocketUpgrade,omitempty"` - - // Timeout for HTTP requests. - Timeout string `json:"timeout,omitempty"` - - // Retry policy for HTTP requests. - Retries *HTTPRetry `json:"retries,omitempty"` - - // Fault injection policy to apply on HTTP traffic. - Fault *HTTPFaultInjection `json:"fault,omitempty"` - - // Mirror HTTP traffic to a another destination in addition to forwarding - // the requests to the intended destination. Mirrored traffic is on a - // best effort basis where the sidecar/gateway will not wait for the - // mirrored cluster to respond before returning the response from the - // original destination. Statistics will be generated for the mirrored - // destination. - Mirror *Destination `json:"mirror,omitempty"` - - // Additional HTTP headers to add before forwarding a request to the - // destination service. - AppendHeaders map[string]string `json:"appendHeaders,omitempty"` - - // Http headers to remove before returning the response to the caller - RemoveResponseHeaders map[string]string `json:"removeResponseHeaders,omitempty"` -} - -// HttpMatchRequest specifies a set of criterion to be met in order for the -// rule to be applied to the HTTP request. For example, the following -// restricts the rule to match only requests where the URL path -// starts with /ratings/v2/ and the request contains a "cookie" with value -// "user=jason". -// -// apiVersion: networking.istio.io/v1alpha3 -// kind: VirtualService -// metadata: -// name: ratings-route -// spec: -// hosts: -// - ratings -// http: -// - match: -// - headers: -// cookie: -// regex: "^(.*?;)?(user=jason)(;.*)?" -// uri: -// prefix: "/ratings/v2/" -// route: -// - destination: -// host: ratings -// -// HTTPMatchRequest CANNOT be empty. -type HTTPMatchRequest struct { - // URI to match - // values are case-sensitive and formatted as follows: - // - // - `exact: "value"` for exact string match - // - // - `prefix: "value"` for prefix-based match - // - // - `regex: "value"` for ECMAscript style regex-based match - // - Uri *StringMatch `json:"uri,omitempty"` - - // URI Scheme - // values are case-sensitive and formatted as follows: - // - // - `exact: "value"` for exact string match - // - // - `prefix: "value"` for prefix-based match - // - // - `regex: "value"` for ECMAscript style regex-based match - // - Scheme *StringMatch `json:"scheme,omitempty"` - - // HTTP Method - // values are case-sensitive and formatted as follows: - // - // - `exact: "value"` for exact string match - // - // - `prefix: "value"` for prefix-based match - // - // - `regex: "value"` for ECMAscript style regex-based match - // - Method *StringMatch `json:"method,omitempty"` - - // HTTP Authority - // values are case-sensitive and formatted as follows: - // - // - `exact: "value"` for exact string match - // - // - `prefix: "value"` for prefix-based match - // - // - `regex: "value"` for ECMAscript style regex-based match - // - Authority *StringMatch `json:"authority,omitempty"` - - // The header keys must be lowercase and use hyphen as the separator, - // e.g. _x-request-id_. - // - // Header values are case-sensitive and formatted as follows: - // - // - `exact: "value"` for exact string match - // - // - `prefix: "value"` for prefix-based match - // - // - `regex: "value"` for ECMAscript style regex-based match - // - // **Note:** The keys `uri`, `scheme`, `method`, and `authority` will be ignored. - Headers map[string]StringMatch `json:"headers,omitempty"` -} - -// Describes how to match a given string in HTTP headers. Match is -// case-sensitive. -type StringMatch struct { - // Specified exactly one of the fields below. - - // exact string match - Exact string `json:"exact,omitempty"` - - // prefix-based match - Prefix string `json:"prefix,omitempty"` - - // ECMAscript style regex-based match - Regex string `json:"regex,omitempty"` -} - -type DestinationWeight struct { - // REQUIRED. Destination uniquely identifies the instances of a service - // to which the request/connection should be forwarded to. - Destination Destination `json:"destination"` - - // REQUIRED. The proportion of traffic to be forwarded to the service - // version. (0-100). Sum of weights across destinations SHOULD BE == 100. - // If there is only destination in a rule, the weight value is assumed to - // be 100. - Weight int `json:"weight"` -} - -// Destination indicates the network addressable service to which the -// request/connection will be sent after processing a routing rule. The -// destination.name should unambiguously refer to a service in the service -// registry. It can be a short name or a fully qualified domain name from -// the service registry, a resolvable DNS name, an IP address or a service -// name from the service registry and a subset name. The order of inference -// is as follows: -// -// 1. Service registry lookup. The entire name is looked up in the service -// registry. If the lookup succeeds, the search terminates. The requests -// will be routed to any instance of the service in the mesh. When the -// service name consists of a single word, the FQDN will be constructed in -// a platform specific manner. For example, in Kubernetes, the namespace -// associated with the routing rule will be used to identify the service as -// .. However, if the service name contains -// multiple words separated by a dot (e.g., reviews.prod), the name in its -// entirety would be looked up in the service registry. -// -// 2. Runtime DNS lookup by the proxy. If step 1 fails, and the name is not -// an IP address, it will be considered as a DNS name that is not in the -// service registry (e.g., wikipedia.org). The sidecar/gateway will resolve -// the DNS and load balance requests appropriately. See Envoy's strict_dns -// for details. -// -// The following example routes all traffic by default to pods of the -// reviews service with label "version: v1" (i.e., subset v1), and some -// to subset v2, in a kubernetes environment. -// -// apiVersion: networking.istio.io/v1alpha3 -// kind: VirtualService -// metadata: -// name: reviews-route -// spec: -// hosts: -// - reviews # namespace is same as the client/caller's namespace -// http: -// - match: -// - uri: -// prefix: "/wpcatalog" -// - uri: -// prefix: "/consumercatalog" -// rewrite: -// uri: "/newcatalog" -// route: -// - destination: -// host: reviews -// subset: v2 -// - route: -// - destination: -// host: reviews -// subset: v1 -// -// And the associated DestinationRule -// -// apiVersion: networking.istio.io/v1alpha3 -// kind: DestinationRule -// metadata: -// name: reviews-destination -// spec: -// host: reviews -// subsets: -// - name: v1 -// labels: -// version: v1 -// - name: v2 -// labels: -// version: v2 -// -// The following VirtualService sets a timeout of 5s for all calls to -// productpage.prod service. Notice that there are no subsets defined in -// this rule. Istio will fetch all instances of productpage.prod service -// from the service registry and populate the sidecar's load balancing -// pool. -// -// apiVersion: networking.istio.io/v1alpha3 -// kind: VirtualService -// metadata: -// name: my-productpage-rule -// spec: -// hosts: -// - productpage.prod # in kubernetes, this applies only to prod namespace -// http: -// - timeout: 5s -// route: -// - destination: -// host: productpage.prod -// -// The following sets a timeout of 5s for all calls to the external -// service wikipedia.org, as there is no internal service of that name. -// -// apiVersion: networking.istio.io/v1alpha3 -// kind: VirtualService -// metadata: -// name: my-wiki-rule -// spec: -// hosts: -// - wikipedia.org -// http: -// - timeout: 5s -// route: -// - destination: -// host: wikipedia.org -// -type Destination struct { - // REQUIRED. The name of a service from the service registry. Service - // names are looked up from the platform's service registry (e.g., - // Kubernetes services, Consul services, etc.) and from the hosts - // declared by [ServiceEntry](#ServiceEntry). Traffic forwarded to - // destinations that are not found in either of the two, will be dropped. - // - // *Note for Kubernetes users*: When short names are used (e.g. "reviews" - // instead of "reviews.default.svc.cluster.local"), Istio will interpret - // the short name based on the namespace of the rule, not the service. A - // rule in the "default" namespace containing a host "reviews will be - // interpreted as "reviews.default.svc.cluster.local", irrespective of - // the actual namespace associated with the reviews service. _To avoid - // potential misconfigurations, it is recommended to always use fully - // qualified domain names over short names._ - Host string `json:"host"` - - // The name of a subset within the service. Applicable only to services - // within the mesh. The subset must be defined in a corresponding - // DestinationRule. - Subset string `json:"subset,omitempty"` - - // Specifies the port on the host that is being addressed. If a service - // exposes only a single port it is not required to explicitly select the - // port. - Port PortSelector `json:"port,omitempty"` -} - -// PortSelector specifies the number of a port to be used for -// matching or selection for final routing. -type PortSelector struct { - // Choose one of the fields below. - - // Valid port number - Number uint32 `json:"number,omitempty"` - - // Valid port name - Name string `json:"name,omitempty"` -} - -// Describes match conditions and actions for routing TCP traffic. The -// following routing rule forwards traffic arriving at port 27017 for -// mongo.prod.svc.cluster.local from 172.17.16.* subnet to another Mongo -// server on port 5555. -// -// ```yaml -// apiVersion: networking.istio.io/v1alpha3 -// kind: VirtualService -// metadata: -// name: bookinfo-Mongo -// spec: -// hosts: -// - mongo.prod.svc.cluster.local -// tcp: -// - match: -// - port: 27017 -// sourceSubnet: "172.17.16.0/24" -// route: -// - destination: -// host: mongo.backup.svc.cluster.local -// port: -// number: 5555 -// ``` -type TCPRoute struct { - // Match conditions to be satisfied for the rule to be - // activated. All conditions inside a single match block have AND - // semantics, while the list of match blocks have OR semantics. The rule - // is matched if any one of the match blocks succeed. - Match []L4MatchAttributes `json:"match"` - - // The destination to which the connection should be forwarded to. - // Currently, only one destination is allowed for TCP services. When TCP - // weighted routing support is introduced in Envoy, multiple destinations - // with weights can be specified. - Route DestinationWeight `json:"route"` -} - -// L4 connection match attributes. Note that L4 connection matching support -// is incomplete. -type L4MatchAttributes struct { - // IPv4 or IPv6 ip address of destination with optional subnet. E.g., - // a.b.c.d/xx form or just a.b.c.d. This is only valid when the - // destination service has several IPs and the application explicitly - // specifies a particular IP. - DestinationSubnet string `json:"destinationSubnet,omitempty"` - - // Specifies the port on the host that is being addressed. Many services - // only expose a single port or label ports with the protocols they support, - // in these cases it is not required to explicitly select the port. - Port int `json:"port,omitempty"` - - // IPv4 or IPv6 ip address of source with optional subnet. E.g., a.b.c.d/xx - // form or just a.b.c.d - SourceSubnet string `json:"sourceSubnet,omitempty"` - - // One or more labels that constrain the applicability of a rule to - // workloads with the given labels. If the VirtualService has a list of - // gateways specified at the top, it should include the reserved gateway - // `mesh` in order for this field to be applicable. - SourceLabel map[string]string `json:"sourceLabel,omitempty"` - - // Names of gateways where the rule should be applied to. Gateway names - // at the top of the VirtualService (if any) are overridden. The gateway match is - // independent of sourceLabels. - Gateways []string `json:"gateways,omitempty"` -} - -// HTTPRedirect can be used to send a 302 redirect response to the caller, -// where the Authority/Host and the URI in the response can be swapped with -// the specified values. For example, the following rule redirects -// requests for /v1/getProductRatings API on the ratings service to -// /v1/bookRatings provided by the bookratings service. -// -// apiVersion: networking.istio.io/v1alpha3 -// kind: VirtualService -// metadata: -// name: ratings-route -// spec: -// hosts: -// - ratings -// http: -// - match: -// - uri: -// exact: /v1/getProductRatings -// redirect: -// uri: /v1/bookRatings -// authority: bookratings.default.svc.cluster.local -// ... -// -type HTTPRedirect struct { - // On a redirect, overwrite the Path portion of the URL with this - // value. Note that the entire path will be replaced, irrespective of the - // request URI being matched as an exact path or prefix. - Uri string `json:"uri,omitempty"` - - // On a redirect, overwrite the Authority/Host portion of the URL with - // this value. - Authority string `json:"authority,omitempty"` -} - -// HTTPRewrite can be used to rewrite specific parts of a HTTP request -// before forwarding the request to the destination. Rewrite primitive can -// be used only with the DestinationWeights. The following example -// demonstrates how to rewrite the URL prefix for api call (/ratings) to -// ratings service before making the actual API call. -// -// apiVersion: networking.istio.io/v1alpha3 -// kind: VirtualService -// metadata: -// name: ratings-route -// spec: -// hosts: -// - ratings -// http: -// - match: -// - uri: -// prefix: /ratings -// rewrite: -// uri: /v1/bookRatings -// route: -// - destination: -// host: ratings -// subset: v1 -// -type HTTPRewrite struct { - // rewrite the path (or the prefix) portion of the URI with this - // value. If the original URI was matched based on prefix, the value - // provided in this field will replace the corresponding matched prefix. - Uri string `json:"uri,omitempty"` - - // rewrite the Authority/Host header with this value. - Authority string `json:"authority,omitempty"` -} - -// Describes the retry policy to use when a HTTP request fails. For -// example, the following rule sets the maximum number of retries to 3 when -// calling ratings:v1 service, with a 2s timeout per retry attempt. -// -// apiVersion: networking.istio.io/v1alpha3 -// kind: VirtualService -// metadata: -// name: ratings-route -// spec: -// hosts: -// - ratings -// http: -// - route: -// - destination: -// host: ratings -// subset: v1 -// retries: -// attempts: 3 -// perTryTimeout: 2s -// -type HTTPRetry struct { - // REQUIRED. Number of retries for a given request. The interval - // between retries will be determined automatically (25ms+). Actual - // number of retries attempted depends on the httpReqTimeout. - Attempts int `json:"attempts"` - - // Timeout per retry attempt for a given request. format: 1h/1m/1s/1ms. MUST BE >=1ms. - PerTryTimeout string `json:"perTryTimeout"` -} - -// Describes the Cross-Origin Resource Sharing (CORS) policy, for a given -// service. Refer to -// https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS -// for further details about cross origin resource sharing. For example, -// the following rule restricts cross origin requests to those originating -// from example.com domain using HTTP POST/GET, and sets the -// Access-Control-Allow-Credentials header to false. In addition, it only -// exposes X-Foo-bar header and sets an expiry period of 1 day. -// -// apiVersion: networking.istio.io/v1alpha3 -// kind: VirtualService -// metadata: -// name: ratings-route -// spec: -// hosts: -// - ratings -// http: -// - route: -// - destination: -// host: ratings -// subset: v1 -// corsPolicy: -// allowOrigin: -// - example.com -// allowMethods: -// - POST -// - GET -// allowCredentials: false -// allowHeaders: -// - X-Foo-Bar -// maxAge: "1d" -// -type CorsPolicy struct { - // The list of origins that are allowed to perform CORS requests. The - // content will be serialized into the Access-Control-Allow-Origin - // header. Wildcard * will allow all origins. - AllowOrigin []string `json:"allowOrigin,omitempty"` - - // List of HTTP methods allowed to access the resource. The content will - // be serialized into the Access-Control-Allow-Methods header. - AllowMethods []string `json:"allowMethods,omitempty"` - - // List of HTTP headers that can be used when requesting the - // resource. Serialized to Access-Control-Allow-Methods header. - AllowHeaders []string `json:"allowHeaders,omitempty"` - - // A white list of HTTP headers that the browsers are allowed to - // access. Serialized into Access-Control-Expose-Headers header. - ExposeHeaders []string `json:"exposeHeaders,omitempty"` - - // Specifies how long the the results of a preflight request can be - // cached. Translates to the Access-Control-Max-Age header. - MaxAge string `json:"maxAge,omitempty"` - - // Indicates whether the caller is allowed to send the actual request - // (not the preflight) using credentials. Translates to - // Access-Control-Allow-Credentials header. - AllowCredentials bool `json:"allowCredentials,omitempty"` -} - -// HTTPFaultInjection can be used to specify one or more faults to inject -// while forwarding http requests to the destination specified in a route. -// Fault specification is part of a VirtualService rule. Faults include -// aborting the Http request from downstream service, and/or delaying -// proxying of requests. A fault rule MUST HAVE delay or abort or both. -// -// *Note:* Delay and abort faults are independent of one another, even if -// both are specified simultaneously. -type HTTPFaultInjection struct { - // Delay requests before forwarding, emulating various failures such as - // network issues, overloaded upstream service, etc. - Delay *InjectDelay `json:"delay,omitempty"` - - // Abort Http request attempts and return error codes back to downstream - // service, giving the impression that the upstream service is faulty. - Abort *InjectAbort `json:"abort,omitempty"` -} - -// Delay specification is used to inject latency into the request -// forwarding path. The following example will introduce a 5 second delay -// in 10% of the requests to the "v1" version of the "reviews" -// service from all pods with label env: prod -// -// apiVersion: networking.istio.io/v1alpha3 -// kind: VirtualService -// metadata: -// name: reviews-route -// spec: -// hosts: -// - reviews -// http: -// - match: -// - sourceLabels: -// env: prod -// route: -// - destination: -// host: reviews -// subset: v1 -// fault: -// delay: -// percent: 10 -// fixedDelay: 5s -// -// The _fixedDelay_ field is used to indicate the amount of delay in -// seconds. An optional _percent_ field, a value between 0 and 100, can -// be used to only delay a certain percentage of requests. If left -// unspecified, all request will be delayed. -type InjectDelay struct { - // Percentage of requests on which the delay will be injected (0-100). - Percent int `json:"percent,omitempty"` - - // REQUIRED. Add a fixed delay before forwarding the request. Format: - // 1h/1m/1s/1ms. MUST be >=1ms. - FixedDelay string `json:"fixedDelay"` - - // (-- Add a delay (based on an exponential function) before forwarding - // the request. mean delay needed to derive the exponential delay - // values --) - ExponentialDelay string `json:"exponentialDelay,omitempty"` -} - -// Abort specification is used to prematurely abort a request with a -// pre-specified error code. The following example will return an HTTP -// 400 error code for 10% of the requests to the "ratings" service "v1". -// -// apiVersion: networking.istio.io/v1alpha3 -// kind: VirtualService -// metadata: -// name: ratings-route -// spec: -// hosts: -// - ratings -// http: -// - route: -// - destination: -// host: ratings -// subset: v1 -// fault: -// abort: -// percent: 10 -// httpStatus: 400 -// -// The _httpStatus_ field is used to indicate the HTTP status code to -// return to the caller. The optional _percent_ field, a value between 0 -// and 100, is used to only abort a certain percentage of requests. If -// not specified, all requests are aborted. -type InjectAbort struct { - // Percentage of requests to be aborted with the error code provided (0-100). - Perecent int `json:"percent,omitempty"` - - // REQUIRED. HTTP status code to use to abort the Http request. - HttpStatus int `json:"httpStatus"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// VirtualServiceList is a list of VirtualService resources -type VirtualServiceList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []VirtualService `json:"items"` -} diff --git a/vendor/github.com/knative/serving/pkg/apis/istio/v1alpha3/zz_generated.deepcopy.go b/vendor/github.com/knative/serving/pkg/apis/istio/v1alpha3/zz_generated.deepcopy.go deleted file mode 100644 index 5857c8585ae..00000000000 --- a/vendor/github.com/knative/serving/pkg/apis/istio/v1alpha3/zz_generated.deepcopy.go +++ /dev/null @@ -1,701 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2018 The Knative 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. -*/ - -// This file was autogenerated by deepcopy-gen. Do not edit it manually! - -package v1alpha3 - -import ( - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CorsPolicy) DeepCopyInto(out *CorsPolicy) { - *out = *in - if in.AllowOrigin != nil { - in, out := &in.AllowOrigin, &out.AllowOrigin - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.AllowMethods != nil { - in, out := &in.AllowMethods, &out.AllowMethods - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.AllowHeaders != nil { - in, out := &in.AllowHeaders, &out.AllowHeaders - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.ExposeHeaders != nil { - in, out := &in.ExposeHeaders, &out.ExposeHeaders - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CorsPolicy. -func (in *CorsPolicy) DeepCopy() *CorsPolicy { - if in == nil { - return nil - } - out := new(CorsPolicy) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Destination) DeepCopyInto(out *Destination) { - *out = *in - out.Port = in.Port - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Destination. -func (in *Destination) DeepCopy() *Destination { - if in == nil { - return nil - } - out := new(Destination) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *DestinationWeight) DeepCopyInto(out *DestinationWeight) { - *out = *in - out.Destination = in.Destination - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DestinationWeight. -func (in *DestinationWeight) DeepCopy() *DestinationWeight { - if in == nil { - return nil - } - out := new(DestinationWeight) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Gateway) DeepCopyInto(out *Gateway) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Gateway. -func (in *Gateway) DeepCopy() *Gateway { - if in == nil { - return nil - } - out := new(Gateway) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Gateway) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } else { - return nil - } -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *GatewayList) DeepCopyInto(out *GatewayList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Gateway, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GatewayList. -func (in *GatewayList) DeepCopy() *GatewayList { - if in == nil { - return nil - } - out := new(GatewayList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *GatewayList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } else { - return nil - } -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *GatewaySpec) DeepCopyInto(out *GatewaySpec) { - *out = *in - if in.Servers != nil { - in, out := &in.Servers, &out.Servers - *out = make([]Server, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Selector != nil { - in, out := &in.Selector, &out.Selector - *out = make(map[string]string, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GatewaySpec. -func (in *GatewaySpec) DeepCopy() *GatewaySpec { - if in == nil { - return nil - } - out := new(GatewaySpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *HTTPFaultInjection) DeepCopyInto(out *HTTPFaultInjection) { - *out = *in - if in.Delay != nil { - in, out := &in.Delay, &out.Delay - if *in == nil { - *out = nil - } else { - *out = new(InjectDelay) - **out = **in - } - } - if in.Abort != nil { - in, out := &in.Abort, &out.Abort - if *in == nil { - *out = nil - } else { - *out = new(InjectAbort) - **out = **in - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPFaultInjection. -func (in *HTTPFaultInjection) DeepCopy() *HTTPFaultInjection { - if in == nil { - return nil - } - out := new(HTTPFaultInjection) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *HTTPMatchRequest) DeepCopyInto(out *HTTPMatchRequest) { - *out = *in - if in.Uri != nil { - in, out := &in.Uri, &out.Uri - if *in == nil { - *out = nil - } else { - *out = new(StringMatch) - **out = **in - } - } - if in.Scheme != nil { - in, out := &in.Scheme, &out.Scheme - if *in == nil { - *out = nil - } else { - *out = new(StringMatch) - **out = **in - } - } - if in.Method != nil { - in, out := &in.Method, &out.Method - if *in == nil { - *out = nil - } else { - *out = new(StringMatch) - **out = **in - } - } - if in.Authority != nil { - in, out := &in.Authority, &out.Authority - if *in == nil { - *out = nil - } else { - *out = new(StringMatch) - **out = **in - } - } - if in.Headers != nil { - in, out := &in.Headers, &out.Headers - *out = make(map[string]StringMatch, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPMatchRequest. -func (in *HTTPMatchRequest) DeepCopy() *HTTPMatchRequest { - if in == nil { - return nil - } - out := new(HTTPMatchRequest) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *HTTPRedirect) DeepCopyInto(out *HTTPRedirect) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPRedirect. -func (in *HTTPRedirect) DeepCopy() *HTTPRedirect { - if in == nil { - return nil - } - out := new(HTTPRedirect) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *HTTPRetry) DeepCopyInto(out *HTTPRetry) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPRetry. -func (in *HTTPRetry) DeepCopy() *HTTPRetry { - if in == nil { - return nil - } - out := new(HTTPRetry) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *HTTPRewrite) DeepCopyInto(out *HTTPRewrite) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPRewrite. -func (in *HTTPRewrite) DeepCopy() *HTTPRewrite { - if in == nil { - return nil - } - out := new(HTTPRewrite) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *HTTPRoute) DeepCopyInto(out *HTTPRoute) { - *out = *in - if in.Match != nil { - in, out := &in.Match, &out.Match - *out = make([]HTTPMatchRequest, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Route != nil { - in, out := &in.Route, &out.Route - *out = make([]DestinationWeight, len(*in)) - copy(*out, *in) - } - if in.Redirect != nil { - in, out := &in.Redirect, &out.Redirect - if *in == nil { - *out = nil - } else { - *out = new(HTTPRedirect) - **out = **in - } - } - if in.Rewrite != nil { - in, out := &in.Rewrite, &out.Rewrite - if *in == nil { - *out = nil - } else { - *out = new(HTTPRewrite) - **out = **in - } - } - if in.Retries != nil { - in, out := &in.Retries, &out.Retries - if *in == nil { - *out = nil - } else { - *out = new(HTTPRetry) - **out = **in - } - } - if in.Fault != nil { - in, out := &in.Fault, &out.Fault - if *in == nil { - *out = nil - } else { - *out = new(HTTPFaultInjection) - (*in).DeepCopyInto(*out) - } - } - if in.Mirror != nil { - in, out := &in.Mirror, &out.Mirror - if *in == nil { - *out = nil - } else { - *out = new(Destination) - **out = **in - } - } - if in.AppendHeaders != nil { - in, out := &in.AppendHeaders, &out.AppendHeaders - *out = make(map[string]string, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - if in.RemoveResponseHeaders != nil { - in, out := &in.RemoveResponseHeaders, &out.RemoveResponseHeaders - *out = make(map[string]string, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPRoute. -func (in *HTTPRoute) DeepCopy() *HTTPRoute { - if in == nil { - return nil - } - out := new(HTTPRoute) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *InjectAbort) DeepCopyInto(out *InjectAbort) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new InjectAbort. -func (in *InjectAbort) DeepCopy() *InjectAbort { - if in == nil { - return nil - } - out := new(InjectAbort) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *InjectDelay) DeepCopyInto(out *InjectDelay) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new InjectDelay. -func (in *InjectDelay) DeepCopy() *InjectDelay { - if in == nil { - return nil - } - out := new(InjectDelay) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *L4MatchAttributes) DeepCopyInto(out *L4MatchAttributes) { - *out = *in - if in.SourceLabel != nil { - in, out := &in.SourceLabel, &out.SourceLabel - *out = make(map[string]string, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - if in.Gateways != nil { - in, out := &in.Gateways, &out.Gateways - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new L4MatchAttributes. -func (in *L4MatchAttributes) DeepCopy() *L4MatchAttributes { - if in == nil { - return nil - } - out := new(L4MatchAttributes) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Port) DeepCopyInto(out *Port) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Port. -func (in *Port) DeepCopy() *Port { - if in == nil { - return nil - } - out := new(Port) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PortSelector) DeepCopyInto(out *PortSelector) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PortSelector. -func (in *PortSelector) DeepCopy() *PortSelector { - if in == nil { - return nil - } - out := new(PortSelector) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Server) DeepCopyInto(out *Server) { - *out = *in - out.Port = in.Port - if in.Hosts != nil { - in, out := &in.Hosts, &out.Hosts - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.TLS != nil { - in, out := &in.TLS, &out.TLS - if *in == nil { - *out = nil - } else { - *out = new(TLSOptions) - (*in).DeepCopyInto(*out) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Server. -func (in *Server) DeepCopy() *Server { - if in == nil { - return nil - } - out := new(Server) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *StringMatch) DeepCopyInto(out *StringMatch) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new StringMatch. -func (in *StringMatch) DeepCopy() *StringMatch { - if in == nil { - return nil - } - out := new(StringMatch) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *TCPRoute) DeepCopyInto(out *TCPRoute) { - *out = *in - if in.Match != nil { - in, out := &in.Match, &out.Match - *out = make([]L4MatchAttributes, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - out.Route = in.Route - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TCPRoute. -func (in *TCPRoute) DeepCopy() *TCPRoute { - if in == nil { - return nil - } - out := new(TCPRoute) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *TLSOptions) DeepCopyInto(out *TLSOptions) { - *out = *in - if in.SubjectAltNames != nil { - in, out := &in.SubjectAltNames, &out.SubjectAltNames - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TLSOptions. -func (in *TLSOptions) DeepCopy() *TLSOptions { - if in == nil { - return nil - } - out := new(TLSOptions) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *VirtualService) DeepCopyInto(out *VirtualService) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VirtualService. -func (in *VirtualService) DeepCopy() *VirtualService { - if in == nil { - return nil - } - out := new(VirtualService) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *VirtualService) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } else { - return nil - } -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *VirtualServiceList) DeepCopyInto(out *VirtualServiceList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]VirtualService, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VirtualServiceList. -func (in *VirtualServiceList) DeepCopy() *VirtualServiceList { - if in == nil { - return nil - } - out := new(VirtualServiceList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *VirtualServiceList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } else { - return nil - } -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *VirtualServiceSpec) DeepCopyInto(out *VirtualServiceSpec) { - *out = *in - if in.Hosts != nil { - in, out := &in.Hosts, &out.Hosts - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Gateways != nil { - in, out := &in.Gateways, &out.Gateways - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Http != nil { - in, out := &in.Http, &out.Http - *out = make([]HTTPRoute, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Tcp != nil { - in, out := &in.Tcp, &out.Tcp - *out = make([]TCPRoute, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VirtualServiceSpec. -func (in *VirtualServiceSpec) DeepCopy() *VirtualServiceSpec { - if in == nil { - return nil - } - out := new(VirtualServiceSpec) - in.DeepCopyInto(out) - return out -} diff --git a/vendor/github.com/knative/serving/pkg/apis/networking/register.go b/vendor/github.com/knative/serving/pkg/apis/networking/register.go new file mode 100644 index 00000000000..e47c0cfa043 --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/apis/networking/register.go @@ -0,0 +1,40 @@ +/* +Copyright 2018 The Knative 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 networking + +const ( + GroupName = "networking.internal.knative.dev" + + // IngressClassAnnotationKey is the annotation for the + // explicit class of ClusterIngress that a particular resource has + // opted into. For example, + // + // networking.knative.dev/ingress.class: some-network-impl + // + // This uses a different domain because unlike the resource, it is + // user-facing. + // + // The parent resource may use its own annotations to choose the + // annotation value for the ClusterIngress it uses. Based on such + // value a different reconcilation logic may be used (for examples, + // Istio-based ClusterIngress will reconcile into a VirtualService). + IngressClassAnnotationKey = "networking.knative.dev/ingress.class" + + // IngressLabelKey is the label key attached to underlying network programming + // resources to indicate which ClusterIngress triggered their creation. + IngressLabelKey = GroupName + "/clusteringress" +) diff --git a/vendor/github.com/knative/serving/pkg/apis/networking/v1alpha1/clusteringress_defaults.go b/vendor/github.com/knative/serving/pkg/apis/networking/v1alpha1/clusteringress_defaults.go new file mode 100644 index 00000000000..7a6df88b3b1 --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/apis/networking/v1alpha1/clusteringress_defaults.go @@ -0,0 +1,85 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha1 + +import ( + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +const ( + // DefaultTimeout will be set if timeout not specified. + DefaultTimeout = 60 * time.Second + // DefaultRetryCount will be set if Attempts not specified. + DefaultRetryCount = 3 +) + +func (c *ClusterIngress) SetDefaults() { + c.Spec.SetDefaults() +} + +func (c *IngressSpec) SetDefaults() { + for i := range c.TLS { + c.TLS[i].SetDefaults() + } + for i := range c.Rules { + c.Rules[i].SetDefaults() + } +} + +func (t *ClusterIngressTLS) SetDefaults() { + // Default Secret key for ServerCertificate is `tls.cert`. + if t.ServerCertificate == "" { + t.ServerCertificate = "tls.cert" + } + // Default Secret key for PrivateKey is `tls.key`. + if t.PrivateKey == "" { + t.PrivateKey = "tls.key" + } +} + +func (r *ClusterIngressRule) SetDefaults() { + r.HTTP.SetDefaults() +} + +func (r *HTTPClusterIngressRuleValue) SetDefaults() { + for i := range r.Paths { + r.Paths[i].SetDefaults() + } +} + +func (p *HTTPClusterIngressPath) SetDefaults() { + // If only one split is specified, we default to 100. + if len(p.Splits) == 1 && p.Splits[0].Percent == 0 { + p.Splits[0].Percent = 100 + } + + if p.Timeout == nil { + p.Timeout = &metav1.Duration{Duration: DefaultTimeout} + } + + if p.Retries == nil { + p.Retries = &HTTPRetry{ + PerTryTimeout: &metav1.Duration{Duration: DefaultTimeout}, + Attempts: DefaultRetryCount, + } + } + if p.Retries.PerTryTimeout == nil { + p.Retries.PerTryTimeout = &metav1.Duration{Duration: DefaultTimeout} + } +} diff --git a/vendor/github.com/knative/serving/pkg/apis/networking/v1alpha1/clusteringress_types.go b/vendor/github.com/knative/serving/pkg/apis/networking/v1alpha1/clusteringress_types.go new file mode 100644 index 00000000000..7d19a45b79d --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/apis/networking/v1alpha1/clusteringress_types.go @@ -0,0 +1,346 @@ +/* +Copyright 2018 The Knative Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha1 + +import ( + "github.com/knative/pkg/apis" + duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/util/intstr" +) + +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +genclient:nonNamespaced + +// ClusterIngress is a collection of rules that allow inbound connections to reach the +// endpoints defined by a backend. An ClusterIngress can be configured to give services +// externally-reachable urls, load balance traffic offer name based virtual hosting etc. +// +// This is heavily based on K8s Ingress https://godoc.org/k8s.io/api/extensions/v1beta1#Ingress +// which some highlighted modifications. +type ClusterIngress struct { + metav1.TypeMeta `json:",inline"` + // Standard object's metadata. + // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + // Spec is the desired state of the ClusterIngress. + // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status + // +optional + Spec IngressSpec `json:"spec,omitempty"` + + // Status is the current state of the ClusterIngress. + // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status + // +optional + Status IngressStatus `json:"status,omitempty"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ClusterIngressList is a collection of ClusterIngress. +type ClusterIngressList struct { + metav1.TypeMeta `json:",inline"` + // Standard object's metadata. + // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata + // +optional + metav1.ListMeta `json:"metadata,omitempty"` + + // Items is the list of ClusterIngress. + Items []ClusterIngress `json:"items"` +} + +// IngressSpec describes the ClusterIngress the user wishes to exist. +// +// In general this follow the same shape as K8s Ingress. Some notable differences: +// - Backends now can have namespace: +// - Traffic can be split across multiple backends. +// - Timeout & Retry can be configured. +// - Headers can be appended. +type IngressSpec struct { + // TODO: Generation does not work correctly with CRD. They are scrubbed + // by the APIserver (https://github.com/kubernetes/kubernetes/issues/58778) + // So, we add Generation here. Once that gets fixed, remove this and use + // ObjectMeta.Generation instead. + // +optional + Generation int64 `json:"generation,omitempty"` + + // TLS configuration. Currently the ClusterIngress only supports a single TLS + // port, 443. If multiple members of this list specify different hosts, they + // will be multiplexed on the same port according to the hostname specified + // through the SNI TLS extension, if the ingress controller fulfilling the + // ingress supports SNI. + // +optional + TLS []ClusterIngressTLS `json:"tls,omitempty"` + + // A list of host rules used to configure the ClusterIngress. + // +optional + Rules []ClusterIngressRule `json:"rules,omitempty"` + + // TODO: We need to consider a way to specify if the ClusterIngress address + // should be exposed to the Internet, or only exposed privately (cluster local, + // VPC, RFC1918). An example use case is for + // https://github.com/knative/serving/issues/2127. +} + +// ClusterIngressTLS describes the transport layer security associated with an ClusterIngress. +type ClusterIngressTLS struct { + // Hosts are a list of hosts included in the TLS certificate. The values in + // this list must match the name/s used in the tlsSecret. Defaults to the + // wildcard host setting for the loadbalancer controller fulfilling this + // ClusterIngress, if left unspecified. + // +optional + Hosts []string `json:"hosts,omitempty"` + + // SecretName is the name of the secret used to terminate SSL traffic. + SecretName string `json:"secretName,omitempty"` + + // SecretNamespace is the namespace of the secret used to terminate SSL traffic. + SecretNamespace string `json:"secretNamespace,omitempty"` + + // ServerCertificate identifies the certificate filename in the secret. + // Defaults to `tls.cert`. + // +optional + ServerCertificate string `json:"serverCertificate,omitempty"` + + // PrivateKey identifies the private key filename in the secret. + // Defaults to `tls.key`. + // +optional + PrivateKey string `json:"privateKey,omitempty"` +} + +// ClusterIngressRule represents the rules mapping the paths under a specified host to +// the related backend services. Incoming requests are first evaluated for a host +// match, then routed to the backend associated with the matching ClusterIngressRuleValue. +type ClusterIngressRule struct { + // Host is the fully qualified domain name of a network host, as defined + // by RFC 3986. Note the following deviations from the "host" part of the + // URI as defined in the RFC: + // 1. IPs are not allowed. Currently a rule value can only apply to the + // IP in the Spec of the parent ClusterIngress. + // 2. The `:` delimiter is not respected because ports are not allowed. + // Currently the port of an ClusterIngress is implicitly :80 for http and + // :443 for https. + // Both these may change in the future. + // If the host is unspecified, the ClusterIngress routes all traffic based on the + // specified ClusterIngressRuleValue. + // If multiple matching Hosts were provided, the first rule will take precedent. + // +optional + Hosts []string `json:"hosts,omitempty"` + + // HTTP represents a rule to apply against incoming requests. If the + // rule is satisfied, the request is routed to the specified backend. + HTTP *HTTPClusterIngressRuleValue `json:"http,omitempty"` +} + +// HTTPClusterIngressRuleValue is a list of http selectors pointing to backends. +// In the example: http:///? -> backend where +// where parts of the url correspond to RFC 3986, this resource will be used +// to match against everything after the last '/' and before the first '?' +// or '#'. +type HTTPClusterIngressRuleValue struct { + // A collection of paths that map requests to backends. + // + // If they are multiple matching paths, the first match takes precendent. + Paths []HTTPClusterIngressPath `json:"paths"` + + // TODO: Consider adding fields for ingress-type specific global + // options usable by a loadbalancer, like http keep-alive. +} + +// HTTPClusterIngressPath associates a path regex with a backend. Incoming urls matching +// the path are forwarded to the backend. +type HTTPClusterIngressPath struct { + // Path is an extended POSIX regex as defined by IEEE Std 1003.1, + // (i.e this follows the egrep/unix syntax, not the perl syntax) + // matched against the path of an incoming request. Currently it can + // contain characters disallowed from the conventional "path" + // part of a URL as defined by RFC 3986. Paths must begin with + // a '/'. If unspecified, the path defaults to a catch all sending + // traffic to the backend. + // +optional + Path string `json:"path,omitempty"` + + // Splits defines the referenced service endpoints to which the traffic + // will be forwarded to. + Splits []ClusterIngressBackendSplit `json:"splits"` + + // AppendHeaders allow specifying additional HTTP headers to add + // before forwarding a request to the destination service. + // + // NOTE: This differs from K8s Ingress which doesn't allow header appending. + // +optional + AppendHeaders map[string]string `json:"appendHeaders,omitempty"` + + // Timeout for HTTP requests. + // + // NOTE: This differs from K8s Ingress which doesn't allow setting timeouts. + // +optional + Timeout *metav1.Duration `json:"timeout,omitempty"` + + // Retry policy for HTTP requests. + // + // NOTE: This differs from K8s Ingress which doesn't allow retry settings. + // +optional + Retries *HTTPRetry `json:"retries,omitempty"` +} + +// ClusterIngressBackend describes all endpoints for a given service and port. +type ClusterIngressBackendSplit struct { + // Specifies the backend receiving the traffic split. + ClusterIngressBackend `json:",inline"` + + // Specifies the split percentage, a number between 0 and 100. If + // only one split is specified, we default to 100. + // + // NOTE: This differs from K8s Ingress to allow percentage split. + Percent int `json:"percent,omitempty"` +} + +// ClusterIngressBackend describes all endpoints for a given service and port. +type ClusterIngressBackend struct { + // Specifies the namespace of the referenced service. + // + // NOTE: This differs from K8s Ingress to allow routing to different namespaces. + ServiceNamespace string `json:"serviceNamespace"` + + // Specifies the name of the referenced service. + ServiceName string `json:"serviceName"` + + // Specifies the port of the referenced service. + ServicePort intstr.IntOrString `json:"servicePort"` +} + +// HTTPRetry describes the retry policy to use when a HTTP request fails. +type HTTPRetry struct { + // Number of retries for a given request. + Attempts int `json:"attempts"` + + // Timeout per retry attempt for a given request. format: 1h/1m/1s/1ms. MUST BE >=1ms. + PerTryTimeout *metav1.Duration `json:"perTryTimeout"` +} + +// IngressStatus describe the current state of the ClusterIngress. +type IngressStatus struct { + // +optional + Conditions duckv1alpha1.Conditions `json:"conditions,omitempty"` + // LoadBalancer contains the current status of the load-balancer. + // +optional + LoadBalancer *LoadBalancerStatus `json:"loadBalancer,omitempty"` +} + +// LoadBalancerStatus represents the status of a load-balancer. +type LoadBalancerStatus struct { + // Ingress is a list containing ingress points for the load-balancer. + // Traffic intended for the service should be sent to these ingress points. + // +optional + Ingress []LoadBalancerIngressStatus `json:"ingress,omitempty"` +} + +// LoadBalancerIngress represents the status of a load-balancer ingress point: +// traffic intended for the service should be sent to an ingress point. +type LoadBalancerIngressStatus struct { + // IP is set for load-balancer ingress points that are IP based + // (typically GCE or OpenStack load-balancers) + // +optional + IP string `json:"ip,omitempty"` + + // Domain is set for load-balancer ingress points that are DNS based + // (typically AWS load-balancers) + // +optional + Domain string `json:"domain,omitempty"` + + // DomainInternal is set if there is a cluster-local DNS name to access the Ingress. + // + // NOTE: This differs from K8s Ingress, since we also desire to have a cluster-local + // DNS name to allow routing in case of not having a mesh. + // + // +optional + DomainInternal string `json:"domainInternal,omitempty"` +} + +// ConditionType represents a ClusterIngress condition value +const ( + // ClusterIngressConditionReady is set when the clusterIngress networking setting is + // configured and it has a load balancer address. + ClusterIngressConditionReady = duckv1alpha1.ConditionReady + + // ClusterIngressConditionNetworkConfigured is set when the ClusterIngress's underlying + // network programming has been configured. This doesn't include conditions of the + // backends, so even if this should remain true when network is configured and backends + // are not ready. + ClusterIngressConditionNetworkConfigured duckv1alpha1.ConditionType = "NetworkConfigured" + + // ClusterIngressConditionLoadBalancerReady is set when the ClusterIngress has + // a ready LoadBalancer. + ClusterIngressConditionLoadBalancerReady duckv1alpha1.ConditionType = "LoadBalancerReady" +) + +var clusterIngressCondSet = duckv1alpha1.NewLivingConditionSet( + ClusterIngressConditionNetworkConfigured, + ClusterIngressConditionLoadBalancerReady) + +var _ apis.Validatable = (*ClusterIngress)(nil) +var _ apis.Defaultable = (*ClusterIngress)(nil) + +func (ci *ClusterIngress) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("ClusterIngress") +} + +// GetConditions returns the Conditions array. This enables generic handling of +// conditions by implementing the duckv1alpha1.Conditions interface. +func (cis *IngressStatus) GetConditions() duckv1alpha1.Conditions { + return cis.Conditions +} + +// SetConditions sets the Conditions array. This enables generic handling of +// conditions by implementing the duckv1alpha1.Conditions interface. +func (cis *IngressStatus) SetConditions(conditions duckv1alpha1.Conditions) { + cis.Conditions = conditions +} + +func (cis *IngressStatus) GetCondition(t duckv1alpha1.ConditionType) *duckv1alpha1.Condition { + return clusterIngressCondSet.Manage(cis).GetCondition(t) +} + +func (cis *IngressStatus) InitializeConditions() { + clusterIngressCondSet.Manage(cis).InitializeConditions() +} + +func (cis *IngressStatus) MarkNetworkConfigured() { + clusterIngressCondSet.Manage(cis).MarkTrue(ClusterIngressConditionNetworkConfigured) +} + +// MarkLoadBalancerReady marks the Ingress with ClusterIngressConditionLoadBalancerReady, +// and also populate the address of the load balancer. +func (cis *IngressStatus) MarkLoadBalancerReady(lbs []LoadBalancerIngressStatus) { + cis.LoadBalancer = &LoadBalancerStatus{ + Ingress: []LoadBalancerIngressStatus{}, + } + for _, lb := range lbs { + cis.LoadBalancer.Ingress = append(cis.LoadBalancer.Ingress, lb) + } + clusterIngressCondSet.Manage(cis).MarkTrue(ClusterIngressConditionLoadBalancerReady) +} + +// IsReady looks at the conditions and if the Status has a condition +// ClusterIngressConditionReady returns true if ConditionStatus is True +func (cis *IngressStatus) IsReady() bool { + return clusterIngressCondSet.Manage(cis).IsHappy() +} diff --git a/vendor/github.com/knative/serving/pkg/apis/networking/v1alpha1/clusteringress_validation.go b/vendor/github.com/knative/serving/pkg/apis/networking/v1alpha1/clusteringress_validation.go new file mode 100644 index 00000000000..b64129b2ed1 --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/apis/networking/v1alpha1/clusteringress_validation.go @@ -0,0 +1,168 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha1 + +import ( + "fmt" + + "github.com/knative/pkg/apis" + "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/util/intstr" +) + +func (ci *ClusterIngress) Validate() *apis.FieldError { + return ci.Spec.Validate().ViaField("spec") +} + +func (spec *IngressSpec) Validate() *apis.FieldError { + // Spec must not be empty. + if equality.Semantic.DeepEqual(spec, &IngressSpec{}) { + return apis.ErrMissingField(apis.CurrentField) + } + var all *apis.FieldError = nil + // Spec must have at least one rule. + if len(spec.Rules) == 0 { + all = all.Also(apis.ErrMissingField("rules")) + } + // Validate each rule. + for idx, rule := range spec.Rules { + all = all.Also(rule.Validate().ViaFieldIndex("rules", idx)) + } + // TLS settings are optional. However, all provided settings should be valid. + for idx, tls := range spec.TLS { + all = all.Also(tls.Validate().ViaFieldIndex("tls", idx)) + } + return all +} + +func (r *ClusterIngressRule) Validate() *apis.FieldError { + // Provided rule must not be empty. + if equality.Semantic.DeepEqual(r, &ClusterIngressRule{}) { + return apis.ErrMissingField(apis.CurrentField) + } + var all *apis.FieldError = nil + if r.HTTP == nil { + all = all.Also(apis.ErrMissingField("http")) + } else { + all = all.Also(r.HTTP.Validate().ViaField("http")) + } + return all +} + +func (h *HTTPClusterIngressRuleValue) Validate() *apis.FieldError { + if len(h.Paths) == 0 { + return apis.ErrMissingField("paths") + } + var all *apis.FieldError = nil + for idx, path := range h.Paths { + all = all.Also(path.Validate().ViaFieldIndex("paths", idx)) + } + return all +} + +func (h HTTPClusterIngressPath) Validate() *apis.FieldError { + // Provided rule must not be empty. + if equality.Semantic.DeepEqual(h, HTTPClusterIngressPath{}) { + return apis.ErrMissingField(apis.CurrentField) + } + var all *apis.FieldError = nil + // Must provide as least one split. + if len(h.Splits) == 0 { + all = all.Also(apis.ErrMissingField("splits")) + } else { + totalPct := 0 + for idx, split := range h.Splits { + if err := split.Validate(); err != nil { + return err.ViaFieldIndex("splits", idx) + } + totalPct += split.Percent + } + // If a single split is provided we allow missing Percent, and + // interpret as 100%. + if len(h.Splits) == 1 && totalPct == 0 { + totalPct = 100 + } + // Total traffic split percentage must sum up to 100%. + if totalPct != 100 { + all = all.Also(&apis.FieldError{ + Message: "Traffic split percentage must total to 100", + Paths: []string{"splits"}, + }) + } + } + if h.Retries != nil { + all = all.Also(h.Retries.Validate().ViaField("retries")) + } + return all +} + +func (s ClusterIngressBackendSplit) Validate() *apis.FieldError { + // Must not be empty. + if equality.Semantic.DeepEqual(s, ClusterIngressBackendSplit{}) { + return apis.ErrMissingField(apis.CurrentField) + } + var all *apis.FieldError = nil + // Percent must be between 0 and 100. + if s.Percent < 0 || s.Percent > 100 { + all = all.Also(apis.ErrInvalidValue(fmt.Sprintf("%d", s.Percent), "percent")) + } + return all.Also(s.ClusterIngressBackend.Validate()) +} + +// Validate inspects the fields of the type ClusterIngressBackend +// to determine if they are valid. +func (b ClusterIngressBackend) Validate() *apis.FieldError { + // Must not be empty. + if equality.Semantic.DeepEqual(b, ClusterIngressBackend{}) { + return apis.ErrMissingField(apis.CurrentField) + } + var all *apis.FieldError = nil + if b.ServiceNamespace == "" { + all = all.Also(apis.ErrMissingField("serviceNamespace")) + } + if b.ServiceName == "" { + all = all.Also(apis.ErrMissingField("serviceName")) + } + if equality.Semantic.DeepEqual(b.ServicePort, intstr.IntOrString{}) { + all = all.Also(apis.ErrMissingField("servicePort")) + } + return all +} + +func (r *HTTPRetry) Validate() *apis.FieldError { + // Attempts must be greater than 0. + if r.Attempts < 0 { + return apis.ErrInvalidValue(fmt.Sprintf("%d", r.Attempts), "attempts") + } + return nil +} + +func (t *ClusterIngressTLS) Validate() *apis.FieldError { + // Provided TLS setting must not be empty. + if equality.Semantic.DeepEqual(t, &ClusterIngressTLS{}) { + return apis.ErrMissingField(apis.CurrentField) + } + var all *apis.FieldError = nil + // SecretName and SecretNamespace must not be empty. + if t.SecretName == "" { + all = all.Also(apis.ErrMissingField("secretName")) + } + if t.SecretNamespace == "" { + all = all.Also(apis.ErrMissingField("secretNamespace")) + } + return all +} diff --git a/pkg/apis/channels/v1alpha1/doc.go b/vendor/github.com/knative/serving/pkg/apis/networking/v1alpha1/doc.go similarity index 67% rename from pkg/apis/channels/v1alpha1/doc.go rename to vendor/github.com/knative/serving/pkg/apis/networking/v1alpha1/doc.go index 1fd7726b2c2..f3f12f28aa8 100644 --- a/pkg/apis/channels/v1alpha1/doc.go +++ b/vendor/github.com/knative/serving/pkg/apis/networking/v1alpha1/doc.go @@ -1,16 +1,24 @@ /* Copyright 2018 The Knative 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. */ + // +k8s:deepcopy-gen=package -// Package v1alpha1 is the v1alpha1 version of the API. -// +groupName=channels.knative.dev +// +groupName=networking.internal.knative.dev package v1alpha1 + +// ClusterIngress is heavily based on K8s Ingress +// https://godoc.org/k8s.io/api/extensions/v1beta1#Ingress with some +// highlighted modifications. See clusteringress_types.go for more +// information about the modifications that we made. diff --git a/pkg/apis/flows/v1alpha1/register.go b/vendor/github.com/knative/serving/pkg/apis/networking/v1alpha1/register.go similarity index 86% rename from pkg/apis/flows/v1alpha1/register.go rename to vendor/github.com/knative/serving/pkg/apis/networking/v1alpha1/register.go index 918c85b031c..1f1290f4055 100644 --- a/pkg/apis/flows/v1alpha1/register.go +++ b/vendor/github.com/knative/serving/pkg/apis/networking/v1alpha1/register.go @@ -1,5 +1,5 @@ /* -Copyright 2018 The Knative Authors +Copyright 2018 The Knative Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ limitations under the License. package v1alpha1 import ( - "github.com/knative/eventing/pkg/apis/flows" + "github.com/knative/serving/pkg/apis/networking" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -25,7 +25,7 @@ import ( ) // SchemeGroupVersion is group version used to register these objects -var SchemeGroupVersion = schema.GroupVersion{Group: flows.GroupName, Version: "v1alpha1"} +var SchemeGroupVersion = schema.GroupVersion{Group: networking.GroupName, Version: "v1alpha1"} // Kind takes an unqualified kind and returns back a Group qualified GroupKind func Kind(kind string) schema.GroupKind { @@ -45,8 +45,8 @@ var ( // Adds the list of known types to Scheme. func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes(SchemeGroupVersion, - &Flow{}, - &FlowList{}, + &ClusterIngress{}, + &ClusterIngressList{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil diff --git a/vendor/github.com/knative/serving/pkg/apis/networking/v1alpha1/zz_generated.deepcopy.go b/vendor/github.com/knative/serving/pkg/apis/networking/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 00000000000..10cc937b823 --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/apis/networking/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,368 @@ +// +build !ignore_autogenerated + +/* +Copyright 2018 The Knative 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. +*/ + +// This file was autogenerated by deepcopy-gen. Do not edit it manually! + +package v1alpha1 + +import ( + duck_v1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterIngress) DeepCopyInto(out *ClusterIngress) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterIngress. +func (in *ClusterIngress) DeepCopy() *ClusterIngress { + if in == nil { + return nil + } + out := new(ClusterIngress) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClusterIngress) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } else { + return nil + } +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterIngressBackend) DeepCopyInto(out *ClusterIngressBackend) { + *out = *in + out.ServicePort = in.ServicePort + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterIngressBackend. +func (in *ClusterIngressBackend) DeepCopy() *ClusterIngressBackend { + if in == nil { + return nil + } + out := new(ClusterIngressBackend) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterIngressBackendSplit) DeepCopyInto(out *ClusterIngressBackendSplit) { + *out = *in + out.ClusterIngressBackend = in.ClusterIngressBackend + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterIngressBackendSplit. +func (in *ClusterIngressBackendSplit) DeepCopy() *ClusterIngressBackendSplit { + if in == nil { + return nil + } + out := new(ClusterIngressBackendSplit) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterIngressList) DeepCopyInto(out *ClusterIngressList) { + *out = *in + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ClusterIngress, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterIngressList. +func (in *ClusterIngressList) DeepCopy() *ClusterIngressList { + if in == nil { + return nil + } + out := new(ClusterIngressList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClusterIngressList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } else { + return nil + } +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterIngressRule) DeepCopyInto(out *ClusterIngressRule) { + *out = *in + if in.Hosts != nil { + in, out := &in.Hosts, &out.Hosts + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.HTTP != nil { + in, out := &in.HTTP, &out.HTTP + if *in == nil { + *out = nil + } else { + *out = new(HTTPClusterIngressRuleValue) + (*in).DeepCopyInto(*out) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterIngressRule. +func (in *ClusterIngressRule) DeepCopy() *ClusterIngressRule { + if in == nil { + return nil + } + out := new(ClusterIngressRule) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterIngressTLS) DeepCopyInto(out *ClusterIngressTLS) { + *out = *in + if in.Hosts != nil { + in, out := &in.Hosts, &out.Hosts + *out = make([]string, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterIngressTLS. +func (in *ClusterIngressTLS) DeepCopy() *ClusterIngressTLS { + if in == nil { + return nil + } + out := new(ClusterIngressTLS) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *HTTPClusterIngressPath) DeepCopyInto(out *HTTPClusterIngressPath) { + *out = *in + if in.Splits != nil { + in, out := &in.Splits, &out.Splits + *out = make([]ClusterIngressBackendSplit, len(*in)) + copy(*out, *in) + } + if in.AppendHeaders != nil { + in, out := &in.AppendHeaders, &out.AppendHeaders + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + if in.Timeout != nil { + in, out := &in.Timeout, &out.Timeout + if *in == nil { + *out = nil + } else { + *out = new(v1.Duration) + **out = **in + } + } + if in.Retries != nil { + in, out := &in.Retries, &out.Retries + if *in == nil { + *out = nil + } else { + *out = new(HTTPRetry) + (*in).DeepCopyInto(*out) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPClusterIngressPath. +func (in *HTTPClusterIngressPath) DeepCopy() *HTTPClusterIngressPath { + if in == nil { + return nil + } + out := new(HTTPClusterIngressPath) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *HTTPClusterIngressRuleValue) DeepCopyInto(out *HTTPClusterIngressRuleValue) { + *out = *in + if in.Paths != nil { + in, out := &in.Paths, &out.Paths + *out = make([]HTTPClusterIngressPath, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPClusterIngressRuleValue. +func (in *HTTPClusterIngressRuleValue) DeepCopy() *HTTPClusterIngressRuleValue { + if in == nil { + return nil + } + out := new(HTTPClusterIngressRuleValue) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *HTTPRetry) DeepCopyInto(out *HTTPRetry) { + *out = *in + if in.PerTryTimeout != nil { + in, out := &in.PerTryTimeout, &out.PerTryTimeout + if *in == nil { + *out = nil + } else { + *out = new(v1.Duration) + **out = **in + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPRetry. +func (in *HTTPRetry) DeepCopy() *HTTPRetry { + if in == nil { + return nil + } + out := new(HTTPRetry) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *IngressSpec) DeepCopyInto(out *IngressSpec) { + *out = *in + if in.TLS != nil { + in, out := &in.TLS, &out.TLS + *out = make([]ClusterIngressTLS, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Rules != nil { + in, out := &in.Rules, &out.Rules + *out = make([]ClusterIngressRule, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressSpec. +func (in *IngressSpec) DeepCopy() *IngressSpec { + if in == nil { + return nil + } + out := new(IngressSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *IngressStatus) DeepCopyInto(out *IngressStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make(duck_v1alpha1.Conditions, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.LoadBalancer != nil { + in, out := &in.LoadBalancer, &out.LoadBalancer + if *in == nil { + *out = nil + } else { + *out = new(LoadBalancerStatus) + (*in).DeepCopyInto(*out) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressStatus. +func (in *IngressStatus) DeepCopy() *IngressStatus { + if in == nil { + return nil + } + out := new(IngressStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *LoadBalancerIngressStatus) DeepCopyInto(out *LoadBalancerIngressStatus) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LoadBalancerIngressStatus. +func (in *LoadBalancerIngressStatus) DeepCopy() *LoadBalancerIngressStatus { + if in == nil { + return nil + } + out := new(LoadBalancerIngressStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *LoadBalancerStatus) DeepCopyInto(out *LoadBalancerStatus) { + *out = *in + if in.Ingress != nil { + in, out := &in.Ingress, &out.Ingress + *out = make([]LoadBalancerIngressStatus, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LoadBalancerStatus. +func (in *LoadBalancerStatus) DeepCopy() *LoadBalancerStatus { + if in == nil { + return nil + } + out := new(LoadBalancerStatus) + in.DeepCopyInto(out) + return out +} diff --git a/vendor/github.com/knative/serving/pkg/apis/serving/register.go b/vendor/github.com/knative/serving/pkg/apis/serving/register.go index d4c7ae5f880..a5daf5d0343 100644 --- a/vendor/github.com/knative/serving/pkg/apis/serving/register.go +++ b/vendor/github.com/knative/serving/pkg/apis/serving/register.go @@ -27,10 +27,20 @@ const ( // generation of the Configuration that created this revision ConfigurationGenerationAnnotationKey = GroupName + "/configurationGeneration" + // RevisionLastPinnedAnnotationKey is the annotation key used for determining when a route has + // pinned a revision + RevisionLastPinnedAnnotationKey = GroupName + "/lastPinned" + // RouteLabelKey is the label key attached to a Configuration indicating by // which Route it is configured as traffic target. + // The key can also be attached to ClusterIngress resources to indicate + // which Route triggered their creation. RouteLabelKey = GroupName + "/route" + // RouteNamespaceLabelKey is the label key attached to a ClusterIngress + // by a Route to indicate which namespace the Route was created in. + RouteNamespaceLabelKey = GroupName + "/routeNamespace" + // RevisionLabelKey is the label key attached to k8s resources to indicate // which Revision triggered their creation. RevisionLabelKey = GroupName + "/revision" diff --git a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/build_compat.go b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/build_compat.go new file mode 100644 index 00000000000..3069caec0e7 --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/build_compat.go @@ -0,0 +1,101 @@ +/* +Copyright 2018 The Knative Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha1 + +import ( + "bytes" + "encoding/json" + "errors" + + "k8s.io/apimachinery/pkg/runtime" + + buildv1alpha1 "github.com/knative/build/pkg/apis/build/v1alpha1" +) + +// RawExtension is modeled after runtime.RawExtension, and should be +// replaced with it (or an alias) once we can stop supporting embedded +// BuildSpecs. +type RawExtension struct { + // Field order is the precedence for JSON marshaling if multiple + // fields are set. + Raw []byte + Object runtime.Object + BuildSpec *buildv1alpha1.BuildSpec +} + +var _ json.Unmarshaler = (*RawExtension)(nil) +var _ json.Marshaler = (*RawExtension)(nil) + +func (re *RawExtension) UnmarshalJSON(in []byte) error { + if re == nil { + return errors.New("RawExtension: UnmarshalJSON on nil pointer") + } + if !bytes.Equal(in, []byte("null")) { + re.Raw = append(re.Raw[0:0], in...) + } + return nil +} + +// MarshalJSON may get called on pointers or values, so implement MarshalJSON on value. +// http://stackoverflow.com/questions/21390979/custom-marshaljson-never-gets-called-in-go +func (re RawExtension) MarshalJSON() ([]byte, error) { + switch { + case re.Raw != nil: + return re.Raw, nil + + case re.Object != nil: + return json.Marshal(re.Object) + + case re.BuildSpec != nil: + return json.Marshal(re.BuildSpec) + + default: + return []byte("null"), nil + } +} + +func (re *RawExtension) ensureRaw() (err error) { + switch { + case re.Raw != nil: + // Nothing to do. + case re.Object != nil, re.BuildSpec != nil: + re.Raw, err = re.MarshalJSON() + } + return +} + +// As is a helper to decode the raw object into a particular type. +// The type is expected to exhaustively specify the fields encountered. +func (re *RawExtension) As(x interface{}) error { + if err := re.ensureRaw(); err != nil { + return err + } + decoder := json.NewDecoder(bytes.NewBuffer(re.Raw)) + decoder.DisallowUnknownFields() + return decoder.Decode(&x) +} + +// AsDuck is a helper to decode the raw object into a particular duck type. +// The type may only represent a subset of the fields present. +func (re *RawExtension) AsDuck(x interface{}) error { + if err := re.ensureRaw(); err != nil { + return err + } + decoder := json.NewDecoder(bytes.NewBuffer(re.Raw)) + // Allow unknown fields. + return decoder.Decode(&x) +} diff --git a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/configuration_defaults.go b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/configuration_defaults.go index 559ede792d8..150ff4a9e31 100644 --- a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/configuration_defaults.go +++ b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/configuration_defaults.go @@ -1,5 +1,6 @@ /* -Copyright 2017 The Knative Authors +Copyright 2018 The Knative 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 diff --git a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/configuration_types.go b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/configuration_types.go index 0bb54743e30..503d4ea9b0f 100644 --- a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/configuration_types.go +++ b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/configuration_types.go @@ -17,15 +17,12 @@ limitations under the License. package v1alpha1 import ( - "encoding/json" - "fmt" - "reflect" - "time" - - build "github.com/knative/build/pkg/apis/build/v1alpha1" - - corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + + "github.com/knative/pkg/apis" + duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" + "github.com/knative/pkg/kmeta" ) // +genclient @@ -52,8 +49,14 @@ type Configuration struct { } // Check that Configuration may be validated and defaulted. -var _ Validatable = (*Configuration)(nil) -var _ Defaultable = (*Configuration)(nil) +var _ apis.Validatable = (*Configuration)(nil) +var _ apis.Defaultable = (*Configuration)(nil) + +// Check that we can create OwnerReferences to a Configuration. +var _ kmeta.OwnerRefable = (*Configuration)(nil) + +// Check that ConfigurationStatus may have its conditions managed. +var _ duckv1alpha1.ConditionsAccessor = (*ConfigurationStatus)(nil) // ConfigurationSpec holds the desired state of the Configuration (from the client). type ConfigurationSpec struct { @@ -67,7 +70,7 @@ type ConfigurationSpec struct { // Build optionally holds the specification for the build to // perform to produce the Revision's container image. // +optional - Build *build.BuildSpec `json:"build,omitempty"` + Build *RawExtension `json:"build,omitempty"` // RevisionTemplate holds the latest specification for the Revision to // be stamped out. If a Build specification is provided, then the @@ -77,32 +80,13 @@ type ConfigurationSpec struct { RevisionTemplate RevisionTemplateSpec `json:"revisionTemplate"` } -// ConfigurationConditionType is used to communicate the status of the reconciliation process. -// See also: https://github.com/knative/serving/blob/master/docs/spec/errors.md#error-conditions-and-reporting -type ConfigurationConditionType string - const ( // ConfigurationConditionReady is set when the configuration's latest // underlying revision has reported readiness. - ConfigurationConditionReady ConfigurationConditionType = "Ready" + ConfigurationConditionReady = duckv1alpha1.ConditionReady ) -// ConfigurationCondition defines a readiness condition for a Configuration. -// See: https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#typical-status-properties -type ConfigurationCondition struct { - Type ConfigurationConditionType `json:"type" description:"type of Configuration condition"` - - Status corev1.ConditionStatus `json:"status" description:"status of the condition, one of True, False, Unknown"` - - // +optional - LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" description:"last time the condition transit from one status to another"` - - // +optional - Reason string `json:"reason,omitempty" description:"one-word CamelCase reason for the condition's last transition"` - - // +optional - Message string `json:"message,omitempty" description:"human-readable message indicating details about last transition"` -} +var confCondSet = duckv1alpha1.NewLivingConditionSet() // ConfigurationStatus communicates the observed state of the Configuration (from the controller). type ConfigurationStatus struct { @@ -110,7 +94,7 @@ type ConfigurationStatus struct { // reconciliation processes that bring the "spec" inline with the observed // state of the world. // +optional - Conditions []ConfigurationCondition `json:"conditions,omitempty"` + Conditions duckv1alpha1.Conditions `json:"conditions,omitempty"` // LatestReadyRevisionName holds the name of the latest Revision stamped out // from this Configuration that has had its "Ready" condition become "True". @@ -139,25 +123,13 @@ type ConfigurationList struct { Items []Configuration `json:"items"` } -func (r *Configuration) GetGeneration() int64 { - return r.Spec.Generation +func (r *Configuration) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("Configuration") } -func (r *Configuration) SetGeneration(generation int64) { - r.Spec.Generation = generation -} - -func (r *Configuration) GetSpecJSON() ([]byte, error) { - return json.Marshal(r.Spec) -} - -// IsReady looks at the conditions on the ConfigurationStatus. -// ConfigurationConditionReady returns true if ConditionStatus is True +// IsReady looks at the conditions to see if they are happy. func (cs *ConfigurationStatus) IsReady() bool { - if c := cs.GetCondition(ConfigurationConditionReady); c != nil { - return c.Status == corev1.ConditionTrue - } - return false + return confCondSet.Manage(cs).IsHappy() } // IsLatestReadyRevisionNameUpToDate returns true if the Configuration is ready @@ -168,115 +140,58 @@ func (cs *ConfigurationStatus) IsLatestReadyRevisionNameUpToDate() bool { cs.LatestCreatedRevisionName == cs.LatestReadyRevisionName } -func (config *ConfigurationStatus) GetCondition(t ConfigurationConditionType) *ConfigurationCondition { - for _, cond := range config.Conditions { - if cond.Type == t { - return &cond - } - } - return nil -} - -func (cs *ConfigurationStatus) setCondition(new *ConfigurationCondition) { - if new == nil { - return - } - t := new.Type - var conditions []ConfigurationCondition - for _, cond := range cs.Conditions { - if cond.Type != t { - conditions = append(conditions, cond) - } else { - // If we'd only update the LastTransitionTime, then return. - new.LastTransitionTime = cond.LastTransitionTime - if reflect.DeepEqual(new, &cond) { - return - } - } - } - new.LastTransitionTime = metav1.NewTime(time.Now()) - conditions = append(conditions, *new) - cs.Conditions = conditions -} - -func (cs *ConfigurationStatus) RemoveCondition(t ConfigurationConditionType) { - var conditions []ConfigurationCondition - for _, cond := range cs.Conditions { - if cond.Type != t { - conditions = append(conditions, cond) - } - } - cs.Conditions = conditions +func (cs *ConfigurationStatus) GetCondition(t duckv1alpha1.ConditionType) *duckv1alpha1.Condition { + return confCondSet.Manage(cs).GetCondition(t) } func (cs *ConfigurationStatus) InitializeConditions() { - for _, cond := range []ConfigurationConditionType{ - ConfigurationConditionReady, - } { - if rc := cs.GetCondition(cond); rc == nil { - cs.setCondition(&ConfigurationCondition{ - Type: cond, - Status: corev1.ConditionUnknown, - }) - } - } + confCondSet.Manage(cs).InitializeConditions() } func (cs *ConfigurationStatus) SetLatestCreatedRevisionName(name string) { cs.LatestCreatedRevisionName = name if cs.LatestReadyRevisionName != name { - cs.setCondition(&ConfigurationCondition{ - Type: ConfigurationConditionReady, - Status: corev1.ConditionUnknown, - }) + confCondSet.Manage(cs).MarkUnknown( + ConfigurationConditionReady, + "", + "") } } func (cs *ConfigurationStatus) SetLatestReadyRevisionName(name string) { cs.LatestReadyRevisionName = name - for _, cond := range []ConfigurationConditionType{ - ConfigurationConditionReady, - } { - cs.setCondition(&ConfigurationCondition{ - Type: cond, - Status: corev1.ConditionTrue, - }) - } + confCondSet.Manage(cs).MarkTrue(ConfigurationConditionReady) } func (cs *ConfigurationStatus) MarkLatestCreatedFailed(name, message string) { - cct := []ConfigurationConditionType{ConfigurationConditionReady} - if cs.LatestReadyRevisionName == "" { - cct = append(cct, ConfigurationConditionReady) - } - for _, cond := range cct { - cs.setCondition(&ConfigurationCondition{ - Type: cond, - Status: corev1.ConditionFalse, - Reason: "RevisionFailed", - Message: fmt.Sprintf("Revision %q failed with message: %q.", name, message), - }) - } + confCondSet.Manage(cs).MarkFalse( + ConfigurationConditionReady, + "RevisionFailed", + "Revision %q failed with message: %q.", name, message) } func (cs *ConfigurationStatus) MarkRevisionCreationFailed(message string) { - cs.setCondition(&ConfigurationCondition{ - Type: ConfigurationConditionReady, - Status: corev1.ConditionFalse, - Reason: "RevisionFailed", - Message: fmt.Sprintf("Revision creation failed with message: %q.", message), - }) + confCondSet.Manage(cs).MarkFalse( + ConfigurationConditionReady, + "RevisionFailed", + "Revision creation failed with message: %q.", message) } func (cs *ConfigurationStatus) MarkLatestReadyDeleted() { - cct := []ConfigurationConditionType{ConfigurationConditionReady} - for _, cond := range cct { - cs.setCondition(&ConfigurationCondition{ - Type: cond, - Status: corev1.ConditionFalse, - Reason: "RevisionDeleted", - Message: fmt.Sprintf("Revision %q was deleted.", cs.LatestReadyRevisionName), - }) - } - cs.LatestReadyRevisionName = "" + confCondSet.Manage(cs).MarkFalse( + ConfigurationConditionReady, + "RevisionDeleted", + "Revision %q was deleted.", cs.LatestReadyRevisionName) +} + +// GetConditions returns the Conditions array. This enables generic handling of +// conditions by implementing the duckv1alpha1.Conditions interface. +func (cs *ConfigurationStatus) GetConditions() duckv1alpha1.Conditions { + return cs.Conditions +} + +// SetConditions sets the Conditions array. This enables generic handling of +// conditions by implementing the duckv1alpha1.Conditions interface. +func (cs *ConfigurationStatus) SetConditions(conditions duckv1alpha1.Conditions) { + cs.Conditions = conditions } diff --git a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/configuration_validation.go b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/configuration_validation.go index 5a28faeb40d..04f5827a1be 100644 --- a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/configuration_validation.go +++ b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/configuration_validation.go @@ -1,5 +1,6 @@ /* -Copyright 2017 The Knative Authors +Copyright 2018 The Knative 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 @@ -17,20 +18,33 @@ package v1alpha1 import ( "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + + buildv1alpha1 "github.com/knative/build/pkg/apis/build/v1alpha1" + "github.com/knative/pkg/apis" ) -func (c *Configuration) Validate() *FieldError { - return c.Spec.Validate().ViaField("spec") +func (c *Configuration) Validate() *apis.FieldError { + return ValidateObjectMetadata(c.GetObjectMeta()).ViaField("metadata"). + Also(c.Spec.Validate().ViaField("spec")) } -func (cs *ConfigurationSpec) Validate() *FieldError { +func (cs *ConfigurationSpec) Validate() *apis.FieldError { if equality.Semantic.DeepEqual(cs, &ConfigurationSpec{}) { - return errMissingField(currentField) + return apis.ErrMissingField(apis.CurrentField) } - // In the context of Configuration, serving state may not be specified at all. + var errs *apis.FieldError // TODO(mattmoor): Check ObjectMeta for Name/Namespace/GenerateName - if cs.RevisionTemplate.Spec.ServingState != "" { - return errDisallowedFields("revisionTemplate.spec.servingState") + + if cs.Build == nil { + // No build was specified. + } else if err := cs.Build.As(&buildv1alpha1.BuildSpec{}); err == nil { + // It is a BuildSpec, this is the legacy path. + } else if err = cs.Build.As(&unstructured.Unstructured{}); err == nil { + // It is an unstructured.Unstructured. + } else { + errs = errs.Also(apis.ErrInvalidValue(err.Error(), "build")) } - return cs.RevisionTemplate.Validate().ViaField("revisionTemplate") + + return errs.Also(cs.RevisionTemplate.Validate().ViaField("revisionTemplate")) } diff --git a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/defaults.go b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/defaults.go deleted file mode 100644 index f458c0650f7..00000000000 --- a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/defaults.go +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright 2017 The Knative Authors -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -// Defaultable defines an interface for setting the defaults for the -// uninitialized fields of this instance. -type Defaultable interface { - SetDefaults() -} diff --git a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/field_error.go b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/field_error.go deleted file mode 100644 index 18321cfb74e..00000000000 --- a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/field_error.go +++ /dev/null @@ -1,106 +0,0 @@ -/* -Copyright 2017 The Knative Authors -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 - -import ( - "fmt" - "strings" -) - -// currentField is a constant to supply as a fieldPath for when there is -// a problem with the current field itself. -const currentField = "" - -// FieldError is used to propagate the context of errors pertaining to -// specific fields in a manner suitable for use in a recursive walk, so -// that errors contain the appropriate field context. -// +k8s:deepcopy-gen=false -type FieldError struct { - Message string - Paths []string - // Details contains an optional longer payload. - Details string -} - -// FieldError implements error -var _ error = (*FieldError)(nil) - -// Validatable indicates that a particular type may have its fields validated. -type Validatable interface { - // Validate checks the validity of this types fields. - Validate() *FieldError -} - -// HasImmutableFields indicates that a particular type has fields that should -// not change after creation. -type HasImmutableFields interface { - // CheckImmutableFields checks that the current instance's immutable - // fields haven't changed from the provided original. - CheckImmutableFields(original HasImmutableFields) *FieldError -} - -// ViaField is used to propagate a validation error along a field access. -// For example, if a type recursively validates its "spec" via: -// if err := foo.Spec.Validate(); err != nil { -// // Augment any field paths with the context that they were accessed -// // via "spec". -// return err.ViaField("spec") -// } -func (fe *FieldError) ViaField(prefix ...string) *FieldError { - if fe == nil { - return nil - } - var newPaths []string - for _, oldPath := range fe.Paths { - if oldPath == currentField { - newPaths = append(newPaths, strings.Join(prefix, ".")) - } else { - newPaths = append(newPaths, - strings.Join(append(prefix, oldPath), ".")) - } - } - fe.Paths = newPaths - return fe -} - -// Error implements error -func (fe *FieldError) Error() string { - if fe.Details == "" { - return fmt.Sprintf("%v: %v", fe.Message, strings.Join(fe.Paths, ", ")) - } - return fmt.Sprintf("%v: %v\n%v", fe.Message, strings.Join(fe.Paths, ", "), fe.Details) -} - -func errMissingField(fieldPaths ...string) *FieldError { - return &FieldError{ - Message: "missing field(s)", - Paths: fieldPaths, - } -} - -func errDisallowedFields(fieldPaths ...string) *FieldError { - return &FieldError{ - Message: "must not set the field(s)", - Paths: fieldPaths, - } -} - -func errInvalidValue(value string, fieldPath string) *FieldError { - return &FieldError{ - Message: fmt.Sprintf("invalid value %q", value), - Paths: []string{fieldPath}, - } -} diff --git a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/immutable.go b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/immutable.go deleted file mode 100644 index d2883e221cd..00000000000 --- a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/immutable.go +++ /dev/null @@ -1,16 +0,0 @@ -/* -Copyright 2017 The Knative Authors -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1alpha1 diff --git a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/metadata_validation.go b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/metadata_validation.go new file mode 100644 index 00000000000..b6755d2bdaa --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/metadata_validation.go @@ -0,0 +1,90 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha1 + +import ( + "fmt" + "strconv" + "strings" + + "github.com/knative/pkg/apis" + "github.com/knative/serving/pkg/apis/autoscaling" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +func ValidateObjectMetadata(meta metav1.Object) *apis.FieldError { + name := meta.GetName() + + if strings.Contains(name, ".") { + return &apis.FieldError{ + Message: "Invalid resource name: special character . must not be present", + Paths: []string{"name"}, + } + } + + if len(name) > 63 { + return &apis.FieldError{ + Message: "Invalid resource name: length must be no more than 63 characters", + Paths: []string{"name"}, + } + } + + if err := validateScaleBoundsAnnotations(meta.GetAnnotations()); err != nil { + return err.ViaField("annotations") + } + + return nil +} + +func getIntGT0(m map[string]string, k string) (int64, *apis.FieldError) { + v, ok := m[k] + if ok { + i, err := strconv.ParseInt(v, 10, 32) + if err != nil || i < 1 { + return 0, &apis.FieldError{ + Message: fmt.Sprintf("Invalid %s annotation value: must be integer greater than 0", k), + Paths: []string{k}, + } + } + return i, nil + } + return 0, nil +} + +func validateScaleBoundsAnnotations(annotations map[string]string) *apis.FieldError { + if annotations == nil { + return nil + } + + min, err := getIntGT0(annotations, autoscaling.MinScaleAnnotationKey) + if err != nil { + return err + } + max, err := getIntGT0(annotations, autoscaling.MaxScaleAnnotationKey) + if err != nil { + return err + } + + if max != 0 && max < min { + return &apis.FieldError{ + Message: fmt.Sprintf("%s=%v is less than %s=%v", autoscaling.MaxScaleAnnotationKey, max, autoscaling.MinScaleAnnotationKey, min), + Paths: []string{autoscaling.MaxScaleAnnotationKey, autoscaling.MinScaleAnnotationKey}, + } + } + + return nil +} diff --git a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/revision_defaults.go b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/revision_defaults.go index db4bedfb6f1..2cd42b02e2a 100644 --- a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/revision_defaults.go +++ b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/revision_defaults.go @@ -1,5 +1,6 @@ /* -Copyright 2017 The Knative Authors +Copyright 2018 The Knative 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 @@ -16,17 +17,13 @@ limitations under the License. package v1alpha1 func (r *Revision) SetDefaults() { - // We only set the default ServingState in the context of Revision - // because we want it unspecified in other contexts (e.g. RevisionTemplateSpec). - if r.Spec.ServingState == "" { - r.Spec.ServingState = RevisionServingStateActive - } - r.Spec.SetDefaults() } func (rs *RevisionSpec) SetDefaults() { - if rs.ConcurrencyModel == "" { - rs.ConcurrencyModel = RevisionRequestConcurrencyModelMulti + // When ConcurrencyModel is specified but ContainerConcurrency + // is not (0), use the ConcurrencyModel value. + if rs.ConcurrencyModel == RevisionRequestConcurrencyModelSingle && rs.ContainerConcurrency == 0 { + rs.ContainerConcurrency = 1 } } diff --git a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/revision_types.go b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/revision_types.go index 7bafa1fd914..2cc72974048 100644 --- a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/revision_types.go +++ b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/revision_types.go @@ -17,14 +17,18 @@ limitations under the License. package v1alpha1 import ( - "encoding/json" - "reflect" + "fmt" + "strconv" "time" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" - buildv1alpha1 "github.com/knative/build/pkg/apis/build/v1alpha1" + "github.com/knative/pkg/apis" + duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" + "github.com/knative/pkg/kmeta" + "github.com/knative/serving/pkg/apis/serving" ) // +genclient @@ -51,9 +55,15 @@ type Revision struct { } // Check that Revision can be validated, can be defaulted, and has immutable fields. -var _ Validatable = (*Revision)(nil) -var _ Defaultable = (*Revision)(nil) -var _ HasImmutableFields = (*Revision)(nil) +var _ apis.Validatable = (*Revision)(nil) +var _ apis.Defaultable = (*Revision)(nil) +var _ apis.Immutable = (*Revision)(nil) + +// Check that RevisionStatus may have its conditions managed. +var _ duckv1alpha1.ConditionsAccessor = (*RevisionStatus)(nil) + +// Check that we can create OwnerReferences to a Revision. +var _ kmeta.OwnerRefable = (*Revision)(nil) // RevisionTemplateSpec describes the data a revision should have when created from a template. // Based on: https://github.com/kubernetes/api/blob/e771f807/core/v1/types.go#L3179-L3190 @@ -64,28 +74,29 @@ type RevisionTemplateSpec struct { Spec RevisionSpec `json:"spec,omitempty"` } -// RevisionServingStateType is an enumeration of the levels of serving readiness of the Revision. +// DeprecatedRevisionServingStateType is an enumeration of the levels of serving readiness of the Revision. // See also: https://github.com/knative/serving/blob/master/docs/spec/errors.md#error-conditions-and-reporting -type RevisionServingStateType string +type DeprecatedRevisionServingStateType string const ( // The revision is ready to serve traffic. It should have Kubernetes // resources, and the Istio route should be pointed to the given resources. - RevisionServingStateActive RevisionServingStateType = "Active" + DeprecatedRevisionServingStateActive DeprecatedRevisionServingStateType = "Active" // The revision is not currently serving traffic, but could be made to serve // traffic quickly. It should have Kubernetes resources, but the Istio route // should be pointed to the activator. - RevisionServingStateReserve RevisionServingStateType = "Reserve" + DeprecatedRevisionServingStateReserve DeprecatedRevisionServingStateType = "Reserve" // The revision has been decommissioned and is not needed to serve traffic // anymore. It should not have any Istio routes or Kubernetes resources. // A Revision may be brought out of retirement, but it may take longer than // it would from a "Reserve" state. // Note: currently not set anywhere. See https://github.com/knative/serving/issues/1203 - RevisionServingStateRetired RevisionServingStateType = "Retired" + DeprecatedRevisionServingStateRetired DeprecatedRevisionServingStateType = "Retired" ) // RevisionRequestConcurrencyModelType is an enumeration of the // concurrency models supported by a Revision. +// Deprecated in favor of RevisionContainerConcurrencyType. type RevisionRequestConcurrencyModelType string const ( @@ -99,6 +110,15 @@ const ( RevisionRequestConcurrencyModelMulti RevisionRequestConcurrencyModelType = "Multi" ) +// RevisionContainerConcurrencyType is an integer expressing a number of +// in-flight (concurrent) requests. +type RevisionContainerConcurrencyType int64 + +const ( + // The maximum configurable container concurrency. + RevisionContainerConcurrencyMax RevisionContainerConcurrencyType = 1000 +) + // RevisionSpec holds the desired state of the Revision (from the client). type RevisionSpec struct { // TODO: Generation does not work correctly with CRD. They are scrubbed @@ -108,19 +128,28 @@ type RevisionSpec struct { // +optional Generation int64 `json:"generation,omitempty"` - // ServingState holds a value describing the desired state the Kubernetes + // DeprecatedServingState holds a value describing the desired state the Kubernetes // resources should be in for this Revision. - // Users must not specify this when creating a revision. It is expected - // that the system will manipulate this based on routability and load. + // Users must not specify this when creating a revision. These values are no longer + // updated by the system. // +optional - ServingState RevisionServingStateType `json:"servingState,omitempty"` + DeprecatedServingState DeprecatedRevisionServingStateType `json:"servingState,omitempty"` // ConcurrencyModel specifies the desired concurrency model // (Single or Multi) for the // Revision. Defaults to Multi. + // Deprecated in favor of ContainerConcurrency. // +optional ConcurrencyModel RevisionRequestConcurrencyModelType `json:"concurrencyModel,omitempty"` + // ContainerConcurrency specifies the maximum allowed + // in-flight (concurrent) requests per container of the Revision. + // Defaults to `0` which means unlimited concurrency. + // This field replaces ConcurrencyModel. A value of `1` + // is equivalent to `Single` and `0` is equivalent to `Multi`. + // +optional + ContainerConcurrency RevisionContainerConcurrencyType `json:"containerConcurrency,omitempty"` + // ServiceAccountName holds the name of the Kubernetes service account // as which the underlying K8s resources should be run. If unspecified // this will default to the "default" service account for the namespace @@ -133,9 +162,15 @@ type RevisionSpec struct { // BuildName optionally holds the name of the Build responsible for // producing the container image for its Revision. + // DEPRECATED: Use BuildRef instead. // +optional BuildName string `json:"buildName,omitempty"` + // BuildRef holds the reference to the build (if there is one) responsible + // for producing the container image for this Revision. Otherwise, nil + // +optional + BuildRef *corev1.ObjectReference `json:"buildRef,omitempty"` + // Container defines the unit of execution for this Revision. // In the context of a Revision, we disallow a number of the fields of // this Container, including: name, resources, ports, and volumeMounts. @@ -145,40 +180,29 @@ type RevisionSpec struct { Container corev1.Container `json:"container,omitempty"` } -// RevisionConditionType is used to communicate the status of the reconciliation process. -// See also: https://github.com/knative/serving/blob/master/docs/spec/errors.md#error-conditions-and-reporting -type RevisionConditionType string - const ( // RevisionConditionReady is set when the revision is starting to materialize // runtime resources, and becomes true when those resources are ready. - RevisionConditionReady RevisionConditionType = "Ready" - // RevisionConditionBuildComplete is set when the revision has an associated build - // and is marked True if/once the Build has completed succesfully. - RevisionConditionBuildSucceeded RevisionConditionType = "BuildSucceeded" + RevisionConditionReady = duckv1alpha1.ConditionReady + // RevisionConditionBuildSucceeded is set when the revision has an associated build + // and is marked True if/once the Build has completed successfully. + RevisionConditionBuildSucceeded duckv1alpha1.ConditionType = "BuildSucceeded" // RevisionConditionResourcesAvailable is set when underlying // Kubernetes resources have been provisioned. - RevisionConditionResourcesAvailable RevisionConditionType = "ResourcesAvailable" + RevisionConditionResourcesAvailable duckv1alpha1.ConditionType = "ResourcesAvailable" // RevisionConditionContainerHealthy is set when the revision readiness check completes. - RevisionConditionContainerHealthy RevisionConditionType = "ContainerHealthy" + RevisionConditionContainerHealthy duckv1alpha1.ConditionType = "ContainerHealthy" + // RevisionConditionActive is set when the revision is receiving traffic. + RevisionConditionActive duckv1alpha1.ConditionType = "Active" ) -// RevisionCondition defines a readiness condition for a Revision. -// See: https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#typical-status-properties -type RevisionCondition struct { - Type RevisionConditionType `json:"type" description:"type of Revision condition"` - - Status corev1.ConditionStatus `json:"status" description:"status of the condition, one of True, False, Unknown"` - - // +optional - LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" description:"last time the condition transit from one status to another"` - - // +optional - Reason string `json:"reason,omitempty" description:"one-word CamelCase reason for the condition's last transition"` +var revCondSet = duckv1alpha1.NewLivingConditionSet( + RevisionConditionResourcesAvailable, + RevisionConditionContainerHealthy, + RevisionConditionActive, +) - // +optional - Message string `json:"message,omitempty" description:"human-readable message indicating details about last transition"` -} +var buildCondSet = duckv1alpha1.NewBatchConditionSet() // RevisionStatus communicates the observed state of the Revision (from the controller). type RevisionStatus struct { @@ -193,7 +217,7 @@ type RevisionStatus struct { // reconciliation processes that bring the "spec" inline with the observed // state of the world. // +optional - Conditions []RevisionCondition `json:"conditions,omitempty"` + Conditions duckv1alpha1.Conditions `json:"conditions,omitempty"` // ObservedGeneration is the 'Generation' of the Configuration that // was last processed by the controller. The observed generation is updated @@ -205,6 +229,14 @@ type RevisionStatus struct { // based on the revision url template specified in the controller's config. // +optional LogURL string `json:"logUrl,omitempty"` + + // ImageDigest holds the resolved digest for the image specified + // within .Spec.Container.Image. The digest is resolved during the creation + // of Revision. This field holds the digest value regardless of whether + // a tag or digest was originally specified in the Container object. It + // may be empty if the image comes from a registry listed to skip resolution. + // +optional + ImageDigest string `json:"imageDigest,omitempty"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object @@ -217,31 +249,40 @@ type RevisionList struct { Items []Revision `json:"items"` } -func (r *Revision) GetGeneration() int64 { - return r.Spec.Generation +func (r *Revision) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("Revision") } -func (r *Revision) SetGeneration(generation int64) { - r.Spec.Generation = generation -} +func (r *Revision) BuildRef() *corev1.ObjectReference { + if r.Spec.BuildRef != nil { + buildRef := r.Spec.BuildRef.DeepCopy() + if buildRef.Namespace == "" { + buildRef.Namespace = r.Namespace + } + return buildRef + } -func (r *Revision) GetSpecJSON() ([]byte, error) { - return json.Marshal(r.Spec) + if r.Spec.BuildName != "" { + return &corev1.ObjectReference{ + APIVersion: "build.knative.dev/v1alpha1", + Kind: "Build", + Namespace: r.Namespace, + Name: r.Spec.BuildName, + } + } + + return nil } // IsReady looks at the conditions and if the Status has a condition // RevisionConditionReady returns true if ConditionStatus is True func (rs *RevisionStatus) IsReady() bool { - if c := rs.GetCondition(RevisionConditionReady); c != nil { - return c.Status == corev1.ConditionTrue - } - return false + return revCondSet.Manage(rs).IsHappy() } func (rs *RevisionStatus) IsActivationRequired() bool { - if c := rs.GetCondition(RevisionConditionReady); c != nil { - return (c.Reason == "Inactive" && c.Status == corev1.ConditionFalse) || - (c.Reason == "Updating" && c.Status == corev1.ConditionUnknown) + if c := revCondSet.Manage(rs).GetCondition(RevisionConditionActive); c != nil { + return c.Status != corev1.ConditionTrue } return false } @@ -250,194 +291,173 @@ func (rs *RevisionStatus) IsRoutable() bool { return rs.IsReady() || rs.IsActivationRequired() } -func (rs *RevisionStatus) GetCondition(t RevisionConditionType) *RevisionCondition { - for _, cond := range rs.Conditions { - if cond.Type == t { - return &cond - } - } - return nil -} - -func (rs *RevisionStatus) setCondition(new *RevisionCondition) { - if new == nil { - return - } - - t := new.Type - var conditions []RevisionCondition - for _, cond := range rs.Conditions { - if cond.Type != t { - conditions = append(conditions, cond) - } else { - // If we'd only update the LastTransitionTime, then return. - new.LastTransitionTime = cond.LastTransitionTime - if reflect.DeepEqual(new, &cond) { - return - } - } - } - new.LastTransitionTime = metav1.NewTime(time.Now()) - conditions = append(conditions, *new) - rs.Conditions = conditions -} - -func (rs *RevisionStatus) RemoveCondition(t RevisionConditionType) { - var conditions []RevisionCondition - for _, cond := range rs.Conditions { - if cond.Type != t { - conditions = append(conditions, cond) - } - } - rs.Conditions = conditions +func (rs *RevisionStatus) GetCondition(t duckv1alpha1.ConditionType) *duckv1alpha1.Condition { + return revCondSet.Manage(rs).GetCondition(t) } func (rs *RevisionStatus) InitializeConditions() { + revCondSet.Manage(rs).InitializeConditions() + // We don't include BuildSucceeded here because it could confuse users if // no `buildName` was specified. - for _, cond := range []RevisionConditionType{ - RevisionConditionResourcesAvailable, - RevisionConditionContainerHealthy, - RevisionConditionReady, - } { - if rc := rs.GetCondition(cond); rc == nil { - rs.setCondition(&RevisionCondition{ - Type: cond, - Status: corev1.ConditionUnknown, - }) - } - } } func (rs *RevisionStatus) InitializeBuildCondition() { - if rc := rs.GetCondition(RevisionConditionBuildSucceeded); rc == nil { - rs.setCondition(&RevisionCondition{ - Type: RevisionConditionBuildSucceeded, - Status: corev1.ConditionUnknown, - }) - } + revCondSet.Manage(rs).InitializeCondition(RevisionConditionBuildSucceeded) } -func (rs *RevisionStatus) PropagateBuildStatus(bs buildv1alpha1.BuildStatus) { - bc := bs.GetCondition(buildv1alpha1.BuildSucceeded) +func (rs *RevisionStatus) PropagateBuildStatus(bs duckv1alpha1.KResourceStatus) { + bc := buildCondSet.Manage(&bs).GetCondition(duckv1alpha1.ConditionSucceeded) if bc == nil { return } - rct := []RevisionConditionType{RevisionConditionBuildSucceeded} - // If the underlying Build is not ready, then mark the Revision not ready. - if bc.Status != corev1.ConditionTrue { - rct = append(rct, RevisionConditionReady) - } - reason := "Building" - if bc.Status != corev1.ConditionUnknown { - reason = bc.Reason - } - for _, cond := range rct { - rs.setCondition(&RevisionCondition{ - Type: cond, - Status: bc.Status, - Reason: reason, - Message: bc.Message, - }) + switch { + case bc.Status == corev1.ConditionUnknown: + revCondSet.Manage(rs).MarkUnknown(RevisionConditionBuildSucceeded, "Building", bc.Message) + case bc.Status == corev1.ConditionTrue: + revCondSet.Manage(rs).MarkTrue(RevisionConditionBuildSucceeded) + case bc.Status == corev1.ConditionFalse: + revCondSet.Manage(rs).MarkFalse(RevisionConditionBuildSucceeded, bc.Reason, bc.Message) } } func (rs *RevisionStatus) MarkDeploying(reason string) { - for _, cond := range []RevisionConditionType{ - RevisionConditionResourcesAvailable, - RevisionConditionContainerHealthy, - RevisionConditionReady, - } { - rs.setCondition(&RevisionCondition{ - Type: cond, - Status: corev1.ConditionUnknown, - Reason: reason, - }) - } + revCondSet.Manage(rs).MarkUnknown(RevisionConditionResourcesAvailable, reason, "") + revCondSet.Manage(rs).MarkUnknown(RevisionConditionContainerHealthy, reason, "") } func (rs *RevisionStatus) MarkServiceTimeout() { - for _, cond := range []RevisionConditionType{ - RevisionConditionResourcesAvailable, - RevisionConditionReady, - } { - rs.setCondition(&RevisionCondition{ - Type: cond, - Status: corev1.ConditionFalse, - Reason: "ServiceTimeout", - Message: "Timed out waiting for a service endpoint to become ready", - }) - } + revCondSet.Manage(rs).MarkFalse(RevisionConditionResourcesAvailable, "ServiceTimeout", + "Timed out waiting for a service endpoint to become ready") } func (rs *RevisionStatus) MarkProgressDeadlineExceeded(message string) { - for _, cond := range []RevisionConditionType{ - RevisionConditionResourcesAvailable, - RevisionConditionReady, - } { - rs.setCondition(&RevisionCondition{ - Type: cond, - Status: corev1.ConditionFalse, - Reason: "ProgressDeadlineExceeded", - Message: message, - }) - } + revCondSet.Manage(rs).MarkFalse(RevisionConditionResourcesAvailable, "ProgressDeadlineExceeded", message) } func (rs *RevisionStatus) MarkContainerHealthy() { - rs.setCondition(&RevisionCondition{ - Type: RevisionConditionContainerHealthy, - Status: corev1.ConditionTrue, - }) - rs.checkAndMarkReady() + revCondSet.Manage(rs).MarkTrue(RevisionConditionContainerHealthy) } func (rs *RevisionStatus) MarkResourcesAvailable() { - rs.setCondition(&RevisionCondition{ - Type: RevisionConditionResourcesAvailable, - Status: corev1.ConditionTrue, - }) - rs.checkAndMarkReady() + revCondSet.Manage(rs).MarkTrue(RevisionConditionResourcesAvailable) +} + +func (rs *RevisionStatus) MarkActive() { + revCondSet.Manage(rs).MarkTrue(RevisionConditionActive) } -func (rs *RevisionStatus) MarkInactive() { - rs.setCondition(&RevisionCondition{ - Type: RevisionConditionReady, - Status: corev1.ConditionFalse, - Reason: "Inactive", - }) +func (rs *RevisionStatus) MarkActivating(reason, message string) { + revCondSet.Manage(rs).MarkUnknown(RevisionConditionActive, reason, message) +} + +func (rs *RevisionStatus) MarkInactive(reason, message string) { + revCondSet.Manage(rs).MarkFalse(RevisionConditionActive, reason, message) } func (rs *RevisionStatus) MarkContainerMissing(message string) { - for _, cond := range []RevisionConditionType{ - RevisionConditionContainerHealthy, - RevisionConditionReady, - } { - rs.setCondition(&RevisionCondition{ - Type: cond, - Status: corev1.ConditionFalse, - Reason: "ContainerMissing", - Message: message, - }) + revCondSet.Manage(rs).MarkFalse(RevisionConditionContainerHealthy, "ContainerMissing", message) +} + +// GetConditions returns the Conditions array. This enables generic handling of +// conditions by implementing the duckv1alpha1.Conditions interface. +func (rs *RevisionStatus) GetConditions() duckv1alpha1.Conditions { + return rs.Conditions +} + +// SetConditions sets the Conditions array. This enables generic handling of +// conditions by implementing the duckv1alpha1.Conditions interface. +func (rs *RevisionStatus) SetConditions(conditions duckv1alpha1.Conditions) { + rs.Conditions = conditions +} + +const ( + AnnotationParseErrorTypeMissing = "Missing" + AnnotationParseErrorTypeInvalid = "Invalid" +) + +// +k8s:deepcopy-gen=false +type AnnotationParseError struct { + Type string + Value string + Err error +} + +// +k8s:deepcopy-gen=false +type LastPinnedParseError AnnotationParseError + +func (e LastPinnedParseError) Error() string { + return fmt.Sprintf("%v lastPinned value: %q", e.Type, e.Value) +} + +// +k8s:deepcopy-gen=false +type configurationGenerationParseError AnnotationParseError + +func (e configurationGenerationParseError) Error() string { + return fmt.Sprintf("%v configurationGeneration value: %q", e.Type, e.Value) +} + +func RevisionLastPinnedString(t time.Time) string { + return fmt.Sprintf("%d", t.Unix()) +} + +func (r *Revision) SetLastPinned(t time.Time) { + if r.ObjectMeta.Annotations == nil { + r.ObjectMeta.Annotations = make(map[string]string) } + + r.ObjectMeta.Annotations[serving.RevisionLastPinnedAnnotationKey] = RevisionLastPinnedString(t) } -func (rs *RevisionStatus) checkAndMarkReady() { - for _, cond := range []RevisionConditionType{ - RevisionConditionContainerHealthy, - RevisionConditionResourcesAvailable, - } { - c := rs.GetCondition(cond) - if c == nil || c.Status != corev1.ConditionTrue { - return +func (r *Revision) GetLastPinned() (time.Time, error) { + if r.Annotations == nil { + return time.Time{}, LastPinnedParseError{ + Type: AnnotationParseErrorTypeMissing, + } + } + + str, ok := r.ObjectMeta.Annotations[serving.RevisionLastPinnedAnnotationKey] + if !ok { + // If a revision is past the create delay without an annotation it is stale + return time.Time{}, LastPinnedParseError{ + Type: AnnotationParseErrorTypeMissing, + } + } + + secs, err := strconv.ParseInt(str, 10, 64) + if err != nil { + return time.Time{}, LastPinnedParseError{ + Type: AnnotationParseErrorTypeInvalid, + Value: str, + Err: err, } } - rs.markReady() + + return time.Unix(secs, 0), nil } -func (rs *RevisionStatus) markReady() { - rs.setCondition(&RevisionCondition{ - Type: RevisionConditionReady, - Status: corev1.ConditionTrue, - }) +func (r *Revision) GetConfigurationGeneration() (int64, error) { + if r.Annotations == nil { + return 0, configurationGenerationParseError{ + Type: AnnotationParseErrorTypeMissing, + } + } + + str, ok := r.ObjectMeta.Annotations[serving.ConfigurationGenerationAnnotationKey] + if !ok { + return 0, configurationGenerationParseError{ + Type: AnnotationParseErrorTypeMissing, + } + } + + gen, err := strconv.ParseInt(str, 10, 64) + if err != nil { + return 0, configurationGenerationParseError{ + Type: AnnotationParseErrorTypeInvalid, + Value: str, + Err: err, + } + } + + return gen, nil } diff --git a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/revision_validation.go b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/revision_validation.go index fc90195fce8..882682d939d 100644 --- a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/revision_validation.go +++ b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/revision_validation.go @@ -1,5 +1,6 @@ /* -Copyright 2017 The Knative Authors +Copyright 2018 The Knative 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 @@ -16,60 +17,87 @@ limitations under the License. package v1alpha1 import ( + "strconv" + "github.com/google/go-cmp/cmp" - "github.com/google/go-cmp/cmp/cmpopts" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/equality" "k8s.io/apimachinery/pkg/util/intstr" + "k8s.io/apimachinery/pkg/util/validation" + + "github.com/knative/pkg/apis" ) -func (rt *Revision) Validate() *FieldError { - return rt.Spec.Validate().ViaField("spec") +func (rt *Revision) Validate() *apis.FieldError { + return ValidateObjectMetadata(rt.GetObjectMeta()).ViaField("metadata"). + Also(rt.Spec.Validate().ViaField("spec")) } -func (rt *RevisionTemplateSpec) Validate() *FieldError { +func (rt *RevisionTemplateSpec) Validate() *apis.FieldError { return rt.Spec.Validate().ViaField("spec") } -func (rs *RevisionSpec) Validate() *FieldError { +func (rs *RevisionSpec) Validate() *apis.FieldError { if equality.Semantic.DeepEqual(rs, &RevisionSpec{}) { - return errMissingField(currentField) + return apis.ErrMissingField(apis.CurrentField) } - if err := rs.ServingState.Validate(); err != nil { - return err.ViaField("servingState") - } - if err := validateContainer(rs.Container); err != nil { - return err.ViaField("container") + errs := validateContainer(rs.Container).ViaField("container"). + Also(validateBuildRef(rs.BuildRef).ViaField("buildRef")) + + if err := rs.ConcurrencyModel.Validate().ViaField("concurrencyModel"); err != nil { + errs = errs.Also(err) + } else if err := ValidateContainerConcurrency(rs.ContainerConcurrency, rs.ConcurrencyModel); err != nil { + errs = errs.Also(err) } - return rs.ConcurrencyModel.Validate().ViaField("concurrencyModel") + return errs } -func (ss RevisionServingStateType) Validate() *FieldError { +func (ss DeprecatedRevisionServingStateType) Validate() *apis.FieldError { switch ss { - case RevisionServingStateType(""), - RevisionServingStateRetired, - RevisionServingStateReserve, - RevisionServingStateActive: + case DeprecatedRevisionServingStateType(""), + DeprecatedRevisionServingStateRetired, + DeprecatedRevisionServingStateReserve, + DeprecatedRevisionServingStateActive: return nil default: - return errInvalidValue(string(ss), currentField) + return apis.ErrInvalidValue(string(ss), apis.CurrentField) } } -func (cm RevisionRequestConcurrencyModelType) Validate() *FieldError { +func (cm RevisionRequestConcurrencyModelType) Validate() *apis.FieldError { switch cm { case RevisionRequestConcurrencyModelType(""), RevisionRequestConcurrencyModelMulti, RevisionRequestConcurrencyModelSingle: return nil default: - return errInvalidValue(string(cm), currentField) + return apis.ErrInvalidValue(string(cm), apis.CurrentField) } } -func validateContainer(container corev1.Container) *FieldError { +func ValidateContainerConcurrency(cc RevisionContainerConcurrencyType, cm RevisionRequestConcurrencyModelType) *apis.FieldError { + // Validate ContainerConcurrency alone + if cc < 0 || cc > RevisionContainerConcurrencyMax { + return apis.ErrInvalidValue(strconv.Itoa(int(cc)), "containerConcurrency") + } + + // Validate combinations of ConcurrencyModel and ContainerConcurrency + if cc == 0 && cm != RevisionRequestConcurrencyModelMulti && cm != RevisionRequestConcurrencyModelType("") { + return apis.ErrMultipleOneOf("containerConcurrency", "concurrencyModel") + } + if cc == 1 && cm != RevisionRequestConcurrencyModelSingle && cm != RevisionRequestConcurrencyModelType("") { + return apis.ErrMultipleOneOf("containerConcurrency", "concurrencyModel") + } + if cc > 1 && cm != RevisionRequestConcurrencyModelType("") { + return apis.ErrMultipleOneOf("containerConcurrency", "concurrencyModel") + } + + return nil +} + +func validateContainer(container corev1.Container) *apis.FieldError { if equality.Semantic.DeepEqual(container, corev1.Container{}) { - return errMissingField(currentField) + return apis.ErrMissingField(apis.CurrentField) } // Some corev1.Container fields are set by Knative Serving controller. We disallow them // here to avoid silently overwriting these fields and causing confusions for @@ -90,21 +118,54 @@ func validateContainer(container corev1.Container) *FieldError { if container.Lifecycle != nil { ignoredFields = append(ignoredFields, "lifecycle") } + var errs *apis.FieldError if len(ignoredFields) > 0 { // Complain about all ignored fields so that user can remove them all at once. - return errDisallowedFields(ignoredFields...) + errs = errs.Also(apis.ErrDisallowedFields(ignoredFields...)) } // Validate our probes - if err := validateProbe(container.ReadinessProbe); err != nil { - return err.ViaField("readinessProbe") + if err := validateProbe(container.ReadinessProbe).ViaField("readinessProbe"); err != nil { + errs = errs.Also(err) + } + if err := validateProbe(container.LivenessProbe).ViaField("livenessProbe"); err != nil { + errs = errs.Also(err) + } + return errs +} + +func validateBuildRef(buildRef *corev1.ObjectReference) *apis.FieldError { + if buildRef == nil { + return nil + } + if len(validation.IsQualifiedName(buildRef.APIVersion)) != 0 { + return apis.ErrInvalidValue(buildRef.APIVersion, "apiVersion") + } + if len(validation.IsCIdentifier(buildRef.Kind)) != 0 { + return apis.ErrInvalidValue(buildRef.Kind, "kind") + } + if len(validation.IsDNS1123Label(buildRef.Name)) != 0 { + return apis.ErrInvalidValue(buildRef.Name, "name") + } + var disallowedFields []string + if buildRef.Namespace != "" { + disallowedFields = append(disallowedFields, "namespace") + } + if buildRef.FieldPath != "" { + disallowedFields = append(disallowedFields, "fieldPath") + } + if buildRef.ResourceVersion != "" { + disallowedFields = append(disallowedFields, "resourceVersion") + } + if buildRef.UID != "" { + disallowedFields = append(disallowedFields, "uid") } - if err := validateProbe(container.LivenessProbe); err != nil { - return err.ViaField("livenessProbe") + if len(disallowedFields) != 0 { + return apis.ErrDisallowedFields(disallowedFields...) } return nil } -func validateProbe(p *corev1.Probe) *FieldError { +func validateProbe(p *corev1.Probe) *apis.FieldError { if p == nil { return nil } @@ -112,26 +173,24 @@ func validateProbe(p *corev1.Probe) *FieldError { switch { case p.Handler.HTTPGet != nil: if p.Handler.HTTPGet.Port != emptyPort { - return errDisallowedFields("httpGet.port") + return apis.ErrDisallowedFields("httpGet.port") } case p.Handler.TCPSocket != nil: if p.Handler.TCPSocket.Port != emptyPort { - return errDisallowedFields("tcpSocket.port") + return apis.ErrDisallowedFields("tcpSocket.port") } } return nil } -func (current *Revision) CheckImmutableFields(og HasImmutableFields) *FieldError { +func (current *Revision) CheckImmutableFields(og apis.Immutable) *apis.FieldError { original, ok := og.(*Revision) if !ok { - return &FieldError{Message: "The provided original was not a Revision"} + return &apis.FieldError{Message: "The provided original was not a Revision"} } - // The autoscaler is allowed to change ServingState, but consider the rest. - ignoreServingState := cmpopts.IgnoreFields(RevisionSpec{}, "ServingState") - if diff := cmp.Diff(original.Spec, current.Spec, ignoreServingState); diff != "" { - return &FieldError{ + if diff := cmp.Diff(original.Spec, current.Spec); diff != "" { + return &apis.FieldError{ Message: "Immutable fields changed (-old +new)", Paths: []string{"spec"}, Details: diff, diff --git a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/route_defaults.go b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/route_defaults.go index a385269be46..c9f0ec3bdc9 100644 --- a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/route_defaults.go +++ b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/route_defaults.go @@ -1,5 +1,6 @@ /* -Copyright 2017 The Knative Authors +Copyright 2018 The Knative 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 diff --git a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/route_types.go b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/route_types.go index 3a33ad03703..0dc3d678972 100644 --- a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/route_types.go +++ b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/route_types.go @@ -17,13 +17,14 @@ limitations under the License. package v1alpha1 import ( - "encoding/json" - "fmt" - "reflect" - "time" - corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + + "github.com/knative/pkg/apis" + duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" + "github.com/knative/pkg/kmeta" + "github.com/knative/serving/pkg/apis/networking/v1alpha1" ) // +genclient @@ -50,8 +51,14 @@ type Route struct { } // Check that Route may be validated and defaulted. -var _ Validatable = (*Route)(nil) -var _ Defaultable = (*Route)(nil) +var _ apis.Validatable = (*Route)(nil) +var _ apis.Defaultable = (*Route)(nil) + +// Check that we can create OwnerReferences to a Route. +var _ kmeta.OwnerRefable = (*Route)(nil) + +// Check that RouteStatus may have its conditions managed. +var _ duckv1alpha1.ConditionsAccessor = (*RouteStatus)(nil) // TrafficTarget holds a single entry of the routing table for a Route. type TrafficTarget struct { @@ -93,37 +100,23 @@ type RouteSpec struct { Traffic []TrafficTarget `json:"traffic,omitempty"` } -// RouteCondition defines a readiness condition. -// See: https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#typical-status-properties -type RouteCondition struct { - Type RouteConditionType `json:"type"` - - Status corev1.ConditionStatus `json:"status" description:"status of the condition, one of True, False, Unknown"` - - // +optional - LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" description:"last time the condition transit from one status to another"` - - // +optional - Reason string `json:"reason,omitempty" description:"one-word CamelCase reason for the condition's last transition"` - // +optional - Message string `json:"message,omitempty" description:"human-readable message indicating details about last transition"` -} - -// RouteConditionType is used to communicate the status of the reconciliation process. -// See also: https://github.com/knative/serving/blob/master/docs/spec/errors.md#error-conditions-and-reporting -type RouteConditionType string - const ( // RouteConditionReady is set when the service is configured // and has available backends ready to receive traffic. - RouteConditionReady RouteConditionType = "Ready" + RouteConditionReady = duckv1alpha1.ConditionReady // RouteConditionAllTrafficAssigned is set to False when the // service is not configured properly or has no available // backends ready to receive traffic. - RouteConditionAllTrafficAssigned RouteConditionType = "AllTrafficAssigned" + RouteConditionAllTrafficAssigned duckv1alpha1.ConditionType = "AllTrafficAssigned" + + // RouteConditionIngressReady is set to False when the + // ClusterIngress fails to become Ready. + RouteConditionIngressReady duckv1alpha1.ConditionType = "IngressReady" ) +var routeCondSet = duckv1alpha1.NewLivingConditionSet(RouteConditionAllTrafficAssigned, RouteConditionIngressReady) + // RouteStatus communicates the observed state of the Route (from the controller). type RouteStatus struct { // Domain holds the top-level domain that will distribute traffic over the provided targets. @@ -134,9 +127,14 @@ type RouteStatus struct { // DomainInternal holds the top-level domain that will distribute traffic over the provided // targets from inside the cluster. It generally has the form // {route-name}.{route-namespace}.svc.cluster.local + // DEPRECATED: Use Address instead. // +optional DomainInternal string `json:"domainInternal,omitempty"` + // Address holds the information needed for a Route to be the target of an event. + // +optional + Address *duckv1alpha1.Addressable `json:"address,omitempty"` + // Traffic holds the configured traffic distribution. // These entries will always contain RevisionName references. // When ConfigurationName appears in the spec, this will hold the @@ -148,7 +146,7 @@ type RouteStatus struct { // reconciliation processes that bring the "spec" inline with the observed // state of the world. // +optional - Conditions []RouteCondition `json:"conditions,omitempty"` + Conditions duckv1alpha1.Conditions `json:"conditions,omitempty"` // ObservedGeneration is the 'Generation' of the Configuration that // was last processed by the controller. The observed generation is updated @@ -167,177 +165,85 @@ type RouteList struct { Items []Route `json:"items"` } -func (r *Route) GetGeneration() int64 { - return r.Spec.Generation -} - -func (r *Route) SetGeneration(generation int64) { - r.Spec.Generation = generation -} - -func (r *Route) GetSpecJSON() ([]byte, error) { - return json.Marshal(r.Spec) +func (r *Route) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("Route") } func (rs *RouteStatus) IsReady() bool { - if c := rs.GetCondition(RouteConditionReady); c != nil { - return c.Status == corev1.ConditionTrue - } - return false + return routeCondSet.Manage(rs).IsHappy() } -func (rs *RouteStatus) GetCondition(t RouteConditionType) *RouteCondition { - for _, cond := range rs.Conditions { - if cond.Type == t { - return &cond - } - } - return nil -} - -func (rs *RouteStatus) setCondition(new *RouteCondition) { - if new == nil { - return - } - - t := new.Type - var conditions []RouteCondition - for _, cond := range rs.Conditions { - if cond.Type != t { - conditions = append(conditions, cond) - } else { - // If we'd only update the LastTransitionTime, then return. - new.LastTransitionTime = cond.LastTransitionTime - if reflect.DeepEqual(new, &cond) { - return - } - } - } - new.LastTransitionTime = metav1.NewTime(time.Now()) - conditions = append(conditions, *new) - rs.Conditions = conditions -} - -func (rs *RouteStatus) RemoveCondition(t RouteConditionType) { - var conditions []RouteCondition - for _, cond := range rs.Conditions { - if cond.Type != t { - conditions = append(conditions, cond) - } - } - rs.Conditions = conditions +func (rs *RouteStatus) GetCondition(t duckv1alpha1.ConditionType) *duckv1alpha1.Condition { + return routeCondSet.Manage(rs).GetCondition(t) } func (rs *RouteStatus) InitializeConditions() { - for _, cond := range []RouteConditionType{ - RouteConditionAllTrafficAssigned, - RouteConditionReady, - } { - if rc := rs.GetCondition(cond); rc == nil { - rs.setCondition(&RouteCondition{ - Type: cond, - Status: corev1.ConditionUnknown, - }) - } - } + routeCondSet.Manage(rs).InitializeConditions() } func (rs *RouteStatus) MarkTrafficAssigned() { - rs.setCondition(&RouteCondition{ - Type: RouteConditionAllTrafficAssigned, - Status: corev1.ConditionTrue, - }) - rs.checkAndMarkReady() -} - -func (rs *RouteStatus) markTrafficTargetNotReady(reason, msg string) { - rs.setCondition(&RouteCondition{ - Type: RouteConditionAllTrafficAssigned, - Status: corev1.ConditionUnknown, - Reason: reason, - Message: msg, - }) - // TODO(tcnghia): when we start with new RouteConditionReady every revision, - // uncomment the short-circuiting below. - // - // // Do not downgrade Ready condition. - // if c := rs.GetCondition(RouteConditionReady); c != nil && c.Status == corev1.ConditionFalse { - // return - // } - // - // For now, the following is harmless because RouteConditionAllTrafficAssigned - // is the only condition RouteConditionReady depends on. - rs.setCondition(&RouteCondition{ - Type: RouteConditionReady, - Status: corev1.ConditionUnknown, - Reason: reason, - Message: msg, - }) -} - -func (rs *RouteStatus) markTrafficTargetFailed(reason, msg string) { - for _, cond := range []RouteConditionType{ - RouteConditionAllTrafficAssigned, - RouteConditionReady, - } { - rs.setCondition(&RouteCondition{ - Type: cond, - Status: corev1.ConditionFalse, - Reason: reason, - Message: msg, - }) - } + routeCondSet.Manage(rs).MarkTrue(RouteConditionAllTrafficAssigned) } func (rs *RouteStatus) MarkUnknownTrafficError(msg string) { - rs.markTrafficTargetNotReady("Unknown", msg) + routeCondSet.Manage(rs).MarkUnknown(RouteConditionAllTrafficAssigned, "Unknown", msg) } func (rs *RouteStatus) MarkConfigurationNotReady(name string) { - reason := "RevisionMissing" - msg := fmt.Sprintf("Configuration %q is waiting for a Revision to become ready.", name) - rs.markTrafficTargetNotReady(reason, msg) + routeCondSet.Manage(rs).MarkUnknown(RouteConditionAllTrafficAssigned, + "RevisionMissing", + "Configuration %q is waiting for a Revision to become ready.", name) } func (rs *RouteStatus) MarkConfigurationFailed(name string) { - reason := "RevisionMissing" - msg := fmt.Sprintf("Configuration %q does not have any ready Revision.", name) - rs.markTrafficTargetFailed(reason, msg) + routeCondSet.Manage(rs).MarkFalse(RouteConditionAllTrafficAssigned, + "RevisionMissing", + "Configuration %q does not have any ready Revision.", name) } func (rs *RouteStatus) MarkRevisionNotReady(name string) { - reason := "RevisionMissing" - msg := fmt.Sprintf("Revision %q is not yet ready.", name) - rs.markTrafficTargetNotReady(reason, msg) + routeCondSet.Manage(rs).MarkUnknown(RouteConditionAllTrafficAssigned, + "RevisionMissing", + "Revision %q is not yet ready.", name) } func (rs *RouteStatus) MarkRevisionFailed(name string) { - reason := "RevisionMissing" - msg := fmt.Sprintf("Revision %q failed to become ready.", name) - rs.markTrafficTargetFailed(reason, msg) + routeCondSet.Manage(rs).MarkFalse(RouteConditionAllTrafficAssigned, + "RevisionMissing", + "Revision %q failed to become ready.", name) } func (rs *RouteStatus) MarkMissingTrafficTarget(kind, name string) { - reason := kind + "Missing" - msg := fmt.Sprintf("%s %q referenced in traffic not found.", kind, name) - rs.markTrafficTargetFailed(reason, msg) + routeCondSet.Manage(rs).MarkFalse(RouteConditionAllTrafficAssigned, + kind+"Missing", + "%s %q referenced in traffic not found.", kind, name) } -func (rs *RouteStatus) checkAndMarkReady() { - for _, cond := range []RouteConditionType{ - RouteConditionAllTrafficAssigned, - } { - ata := rs.GetCondition(cond) - if ata == nil || ata.Status != corev1.ConditionTrue { - return - } +// PropagateClusterIngressStatus update RouteConditionIngressReady condition +// in RouteStatus according to IngressStatus. +func (rs *RouteStatus) PropagateClusterIngressStatus(cs v1alpha1.IngressStatus) { + cc := cs.GetCondition(v1alpha1.ClusterIngressConditionReady) + if cc == nil { + return + } + switch { + case cc.Status == corev1.ConditionUnknown: + routeCondSet.Manage(rs).MarkUnknown(RouteConditionIngressReady, cc.Reason, cc.Message) + case cc.Status == corev1.ConditionTrue: + routeCondSet.Manage(rs).MarkTrue(RouteConditionIngressReady) + case cc.Status == corev1.ConditionFalse: + routeCondSet.Manage(rs).MarkFalse(RouteConditionIngressReady, cc.Reason, cc.Message) } - rs.markReady() } -func (rs *RouteStatus) markReady() { - rs.setCondition(&RouteCondition{ - Type: RouteConditionReady, - Status: corev1.ConditionTrue, - }) +// GetConditions returns the Conditions array. This enables generic handling of +// conditions by implementing the duckv1alpha1.Conditions interface. +func (rs *RouteStatus) GetConditions() duckv1alpha1.Conditions { + return rs.Conditions +} + +// SetConditions sets the Conditions array. This enables generic handling of +// conditions by implementing the duckv1alpha1.Conditions interface. +func (rs *RouteStatus) SetConditions(conditions duckv1alpha1.Conditions) { + rs.Conditions = conditions } diff --git a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/route_validation.go b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/route_validation.go index a4356d897e3..58f311fde59 100644 --- a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/route_validation.go +++ b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/route_validation.go @@ -1,5 +1,6 @@ /* -Copyright 2017 The Knative Authors +Copyright 2018 The Knative 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 @@ -19,15 +20,19 @@ import ( "fmt" "k8s.io/apimachinery/pkg/api/equality" + + "github.com/knative/pkg/apis" + "k8s.io/apimachinery/pkg/util/validation" ) -func (rt *Route) Validate() *FieldError { - return rt.Spec.Validate().ViaField("spec") +func (r *Route) Validate() *apis.FieldError { + return ValidateObjectMetadata(r.GetObjectMeta()).ViaField("metadata"). + Also(r.Spec.Validate().ViaField("spec")) } -func (rs *RouteSpec) Validate() *FieldError { +func (rs *RouteSpec) Validate() *apis.FieldError { if equality.Semantic.DeepEqual(rs, &RouteSpec{}) { - return errMissingField(currentField) + return apis.ErrMissingField(apis.CurrentField) } // Where a named traffic target points @@ -40,11 +45,11 @@ func (rs *RouteSpec) Validate() *FieldError { // Track the targets of named TrafficTarget entries (to detect duplicates). trafficMap := make(map[string]namedTarget) + var errs *apis.FieldError percentSum := 0 for i, tt := range rs.Traffic { - if err := tt.Validate(); err != nil { - return err.ViaField(fmt.Sprintf("traffic[%d]", i)) - } + errs = errs.Also(tt.Validate().ViaFieldIndex("traffic", i)) + percentSum += tt.Percent if tt.Name == "" { @@ -60,43 +65,43 @@ func (rs *RouteSpec) Validate() *FieldError { // No entry exists, so add ours trafficMap[tt.Name] = nt } else if ent.r != nt.r || ent.c != nt.c { - return &FieldError{ + errs = errs.Also(&apis.FieldError{ Message: fmt.Sprintf("Multiple definitions for %q", tt.Name), Paths: []string{ fmt.Sprintf("traffic[%d].name", ent.i), fmt.Sprintf("traffic[%d].name", nt.i), }, - } + }) } } if percentSum != 100 { - return &FieldError{ + errs = errs.Also(&apis.FieldError{ Message: fmt.Sprintf("Traffic targets sum to %d, want 100", percentSum), Paths: []string{"traffic"}, - } + }) } - return nil + return errs } -func (tt *TrafficTarget) Validate() *FieldError { +func (tt *TrafficTarget) Validate() *apis.FieldError { + var errs *apis.FieldError switch { case tt.RevisionName != "" && tt.ConfigurationName != "": - return &FieldError{ - Message: "Expected exactly one, got both", - Paths: []string{"revisionName", "configurationName"}, - } + errs = apis.ErrMultipleOneOf("revisionName", "configurationName") case tt.RevisionName != "": + if verrs := validation.IsQualifiedName(tt.RevisionName); len(verrs) > 0 { + errs = apis.ErrInvalidKeyName(tt.RevisionName, "revisionName", verrs...) + } case tt.ConfigurationName != "": - // These are fine. - default: - return &FieldError{ - Message: "Expected exactly one, got neither", - Paths: []string{"revisionName", "configurationName"}, + if verrs := validation.IsQualifiedName(tt.ConfigurationName); len(verrs) > 0 { + errs = apis.ErrInvalidKeyName(tt.ConfigurationName, "configurationName", verrs...) } + default: + errs = apis.ErrMissingOneOf("revisionName", "configurationName") } if tt.Percent < 0 || tt.Percent > 100 { - return errInvalidValue(fmt.Sprintf("%d", tt.Percent), "percent") + errs = errs.Also(apis.ErrInvalidValue(fmt.Sprintf("%d", tt.Percent), "percent")) } - return nil + return errs } diff --git a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/service_defaults.go b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/service_defaults.go index 3e46151cd2e..4f66f434545 100644 --- a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/service_defaults.go +++ b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/service_defaults.go @@ -1,5 +1,6 @@ /* -Copyright 2017 The Knative Authors +Copyright 2018 The Knative 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 @@ -24,5 +25,7 @@ func (ss *ServiceSpec) SetDefaults() { ss.RunLatest.Configuration.SetDefaults() } else if ss.Pinned != nil { ss.Pinned.Configuration.SetDefaults() + } else if ss.Release != nil { + ss.Release.Configuration.SetDefaults() } } diff --git a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/service_types.go b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/service_types.go index c9df581e63c..551456eef8f 100644 --- a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/service_types.go +++ b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/service_types.go @@ -17,12 +17,13 @@ limitations under the License. package v1alpha1 import ( - "encoding/json" - "reflect" - "time" - corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + + "github.com/knative/pkg/apis" + duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" + "github.com/knative/pkg/kmeta" ) // +genclient @@ -51,8 +52,14 @@ type Service struct { } // Check that Service may be validated and defaulted. -var _ Validatable = (*Service)(nil) -var _ Defaultable = (*Service)(nil) +var _ apis.Validatable = (*Service)(nil) +var _ apis.Defaultable = (*Service)(nil) + +// Check that we can create OwnerReferences to a Service. +var _ kmeta.OwnerRefable = (*Service)(nil) + +// Check that ServiceStatus may have its conditions managed. +var _ duckv1alpha1.ConditionsAccessor = (*ServiceStatus)(nil) // ServiceSpec represents the configuration for the Service object. Exactly one // of its members (other than Generation) must be specified. Services can either @@ -74,16 +81,59 @@ type ServiceSpec struct { // Pins this service to a specific revision name. The revision must // be owned by the configuration provided. + // PinnedType is DEPRECATED in favor of ReleaseType // +optional Pinned *PinnedType `json:"pinned,omitempty"` + + // Manual mode enables users to start managing the underlying Route and Configuration + // resources directly. This advanced usage is intended as a path for users to graduate + // from the limited capabilities of Service to the full power of Route. + // +optional + Manual *ManualType `json:"manual,omitempty"` + + // Release enables gradual promotion of new revisions by allowing traffic + // to be split between two revisions. This type replaces the deprecated Pinned type. + // +optional + Release *ReleaseType `json:"release,omitempty"` +} + +// ManualType contains the options for configuring a manual service. See ServiceSpec for +// more details. +type ManualType struct { + // Manual type does not contain a configuration as this type provides the + // user complete control over the configuration and route. +} + +// ReleaseType contains the options for slowly releasing revisions. See ServiceSpec for +// more details. +type ReleaseType struct { + // Revisions is an ordered list of 1 or 2 revisions. The first will + // have a TrafficTarget with a name of "current" and the second will have + // a name of "candidate". + // +optional + Revisions []string `json:"revisions,omitempty"` + + // RolloutPercent is the percent of traffic that should be sent to the "candidate" + // revision. Valid values are between 0 and 99 inclusive. + // +optional + RolloutPercent int `json:"rolloutPercent,omitempty"` + + // The configuration for this service. All revisions from this service must + // come from a single configuration. + // +optional + Configuration ConfigurationSpec `json:"configuration,omitempty"` } +// RunLatestType contains the options for always having a route to the latest configuration. See +// ServiceSpec for more details. type RunLatestType struct { // The configuration for this service. // +optional Configuration ConfigurationSpec `json:"configuration,omitempty"` } +// PinnedType is DEPRECATED. ReleaseType should be used instead. To get the behavior of PinnedType set +// ReleaseType.Revisions to []string{PinnedType.RevisionName} and ReleaseType.RolloutPercent to 0. type PinnedType struct { // The revision name to pin this service to until changed // to a different service type. @@ -95,38 +145,24 @@ type PinnedType struct { Configuration ConfigurationSpec `json:"configuration,omitempty"` } -type ServiceCondition struct { - Type ServiceConditionType `json:"type"` - - Status corev1.ConditionStatus `json:"status" description:"status of the condition, one of True, False, Unknown"` - - // +optional - LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty" description:"last time the condition transit from one status to another"` - - // +optional - Reason string `json:"reason,omitempty" description:"one-word CamelCase reason for the condition's last transition"` - // +optional - Message string `json:"message,omitempty" description:"human-readable message indicating details about last transition"` -} - -// ServiceConditionType represents an Service condition value -type ServiceConditionType string - +// ConditionType represents a Service condition value const ( // ServiceConditionReady is set when the service is configured // and has available backends ready to receive traffic. - ServiceConditionReady ServiceConditionType = "Ready" + ServiceConditionReady = duckv1alpha1.ConditionReady // ServiceConditionRoutesReady is set when the service's underlying // routes have reported readiness. - ServiceConditionRoutesReady ServiceConditionType = "RoutesReady" + ServiceConditionRoutesReady duckv1alpha1.ConditionType = "RoutesReady" // ServiceConditionConfigurationsReady is set when the service's underlying // configurations have reported readiness. - ServiceConditionConfigurationsReady ServiceConditionType = "ConfigurationsReady" + ServiceConditionConfigurationsReady duckv1alpha1.ConditionType = "ConfigurationsReady" ) +var serviceCondSet = duckv1alpha1.NewLivingConditionSet(ServiceConditionConfigurationsReady, ServiceConditionRoutesReady) + type ServiceStatus struct { // +optional - Conditions []ServiceCondition `json:"conditions,omitempty"` + Conditions duckv1alpha1.Conditions `json:"conditions,omitempty"` // From RouteStatus. // Domain holds the top-level domain that will distribute traffic over the provided targets. @@ -138,9 +174,14 @@ type ServiceStatus struct { // DomainInternal holds the top-level domain that will distribute traffic over the provided // targets from inside the cluster. It generally has the form // {route-name}.{route-namespace}.svc.cluster.local + // DEPRECATED: Use Address instead. // +optional DomainInternal string `json:"domainInternal,omitempty"` + // Address holds the information needed for a Route to be the target of an event. + // +optional + Address *duckv1alpha1.Addressable `json:"address,omitempty"` + // From RouteStatus. // Traffic holds the configured traffic distribution. // These entries will always contain RevisionName references. @@ -177,80 +218,20 @@ type ServiceList struct { Items []Service `json:"items"` } -func (s *Service) GetGeneration() int64 { - return s.Spec.Generation -} - -func (s *Service) SetGeneration(generation int64) { - s.Spec.Generation = generation -} - -func (s *Service) GetSpecJSON() ([]byte, error) { - return json.Marshal(s.Spec) +func (s *Service) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("Service") } func (ss *ServiceStatus) IsReady() bool { - if c := ss.GetCondition(ServiceConditionReady); c != nil { - return c.Status == corev1.ConditionTrue - } - return false -} - -func (ss *ServiceStatus) GetCondition(t ServiceConditionType) *ServiceCondition { - for _, cond := range ss.Conditions { - if cond.Type == t { - return &cond - } - } - return nil -} - -func (ss *ServiceStatus) setCondition(new *ServiceCondition) { - if new == nil { - return - } - - t := new.Type - var conditions []ServiceCondition - for _, cond := range ss.Conditions { - if cond.Type != t { - conditions = append(conditions, cond) - } else { - // If we'd only update the LastTransitionTime, then return. - new.LastTransitionTime = cond.LastTransitionTime - if reflect.DeepEqual(new, &cond) { - return - } - } - } - new.LastTransitionTime = metav1.NewTime(time.Now()) - conditions = append(conditions, *new) - ss.Conditions = conditions + return serviceCondSet.Manage(ss).IsHappy() } -func (ss *ServiceStatus) RemoveCondition(t ServiceConditionType) { - var conditions []ServiceCondition - for _, cond := range ss.Conditions { - if cond.Type != t { - conditions = append(conditions, cond) - } - } - ss.Conditions = conditions +func (ss *ServiceStatus) GetCondition(t duckv1alpha1.ConditionType) *duckv1alpha1.Condition { + return serviceCondSet.Manage(ss).GetCondition(t) } func (ss *ServiceStatus) InitializeConditions() { - for _, cond := range []ServiceConditionType{ - ServiceConditionReady, - ServiceConditionConfigurationsReady, - ServiceConditionRoutesReady, - } { - if rc := ss.GetCondition(cond); rc == nil { - ss.setCondition(&ServiceCondition{ - Type: cond, - Status: corev1.ConditionUnknown, - }) - } - } + serviceCondSet.Manage(ss).InitializeConditions() } func (ss *ServiceStatus) PropagateConfigurationStatus(cs ConfigurationStatus) { @@ -261,67 +242,65 @@ func (ss *ServiceStatus) PropagateConfigurationStatus(cs ConfigurationStatus) { if cc == nil { return } - sct := []ServiceConditionType{ServiceConditionConfigurationsReady} - // If the underlying Configuration reported not ready, then bubble it up. - if cc.Status != corev1.ConditionTrue { - sct = append(sct, ServiceConditionReady) - } - for _, cond := range sct { - ss.setCondition(&ServiceCondition{ - Type: cond, - Status: cc.Status, - Reason: cc.Reason, - Message: cc.Message, - }) - } - if cc.Status == corev1.ConditionTrue { - ss.checkAndMarkReady() + switch { + case cc.Status == corev1.ConditionUnknown: + serviceCondSet.Manage(ss).MarkUnknown(ServiceConditionConfigurationsReady, cc.Reason, cc.Message) + case cc.Status == corev1.ConditionTrue: + serviceCondSet.Manage(ss).MarkTrue(ServiceConditionConfigurationsReady) + case cc.Status == corev1.ConditionFalse: + serviceCondSet.Manage(ss).MarkFalse(ServiceConditionConfigurationsReady, cc.Reason, cc.Message) } } func (ss *ServiceStatus) PropagateRouteStatus(rs RouteStatus) { ss.Domain = rs.Domain ss.DomainInternal = rs.DomainInternal + ss.Address = rs.Address ss.Traffic = rs.Traffic rc := rs.GetCondition(RouteConditionReady) if rc == nil { return } - sct := []ServiceConditionType{ServiceConditionRoutesReady} - // If the underlying Route reported not ready, then bubble it up. - if rc.Status != corev1.ConditionTrue { - sct = append(sct, ServiceConditionReady) - } - for _, cond := range sct { - ss.setCondition(&ServiceCondition{ - Type: cond, - Status: rc.Status, - Reason: rc.Reason, - Message: rc.Message, - }) - } - if rc.Status == corev1.ConditionTrue { - ss.checkAndMarkReady() + switch { + case rc.Status == corev1.ConditionUnknown: + serviceCondSet.Manage(ss).MarkUnknown(ServiceConditionRoutesReady, rc.Reason, rc.Message) + case rc.Status == corev1.ConditionTrue: + serviceCondSet.Manage(ss).MarkTrue(ServiceConditionRoutesReady) + case rc.Status == corev1.ConditionFalse: + serviceCondSet.Manage(ss).MarkFalse(ServiceConditionRoutesReady, rc.Reason, rc.Message) } } -func (ss *ServiceStatus) checkAndMarkReady() { - for _, cond := range []ServiceConditionType{ - ServiceConditionConfigurationsReady, - ServiceConditionRoutesReady, - } { - c := ss.GetCondition(cond) - if c == nil || c.Status != corev1.ConditionTrue { - return - } - } - ss.markReady() +// SetManualStatus updates the service conditions to unknown as the underlying Route +// can have TrafficTargets to Configurations not owned by the service. We do not want to falsely +// report Ready. +func (ss *ServiceStatus) SetManualStatus() { + reason := "Manual" + message := "Service is set to Manual, and is not managing underlying resources." + + // Clear our fields by creating a new status and copying over only the fields and conditions we want + newStatus := &ServiceStatus{} + newStatus.InitializeConditions() + serviceCondSet.Manage(newStatus).MarkUnknown(ServiceConditionConfigurationsReady, reason, message) + serviceCondSet.Manage(newStatus).MarkUnknown(ServiceConditionRoutesReady, reason, message) + + newStatus.Address = ss.Address + newStatus.Domain = ss.Domain + newStatus.DomainInternal = ss.DomainInternal + + *ss = *newStatus + } -func (ss *ServiceStatus) markReady() { - ss.setCondition(&ServiceCondition{ - Type: ServiceConditionReady, - Status: corev1.ConditionTrue, - }) +// GetConditions returns the Conditions array. This enables generic handling of +// conditions by implementing the duckv1alpha1.Conditions interface. +func (ss *ServiceStatus) GetConditions() duckv1alpha1.Conditions { + return ss.Conditions +} + +// SetConditions sets the Conditions array. This enables generic handling of +// conditions by implementing the duckv1alpha1.Conditions interface. +func (ss *ServiceStatus) SetConditions(conditions duckv1alpha1.Conditions) { + ss.Conditions = conditions } diff --git a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/service_validation.go b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/service_validation.go index 8cc2c9b3cd8..8ff4ff3a8cf 100644 --- a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/service_validation.go +++ b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/service_validation.go @@ -1,5 +1,6 @@ /* -Copyright 2017 The Knative Authors +Copyright 2018 The Knative 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 @@ -15,43 +16,99 @@ limitations under the License. package v1alpha1 -func (s *Service) Validate() *FieldError { - return s.Spec.Validate().ViaField("spec") +import ( + "fmt" + "github.com/knative/pkg/apis" +) + +// Validate validates the fields belonging to Service +func (s *Service) Validate() *apis.FieldError { + return ValidateObjectMetadata(s.GetObjectMeta()).ViaField("metadata"). + Also(s.Spec.Validate().ViaField("spec")) } -func (ss *ServiceSpec) Validate() *FieldError { +// Validate validates the fields belonging to ServiceSpec recursively +func (ss *ServiceSpec) Validate() *apis.FieldError { // We would do this semantic DeepEqual, but the spec is comprised // entirely of a oneof, the validation for which produces a clearer // error message. // if equality.Semantic.DeepEqual(ss, &ServiceSpec{}) { - // return errMissingField(currentField) + // return apis.ErrMissingField(currentField) // } - switch { - case ss.RunLatest != nil && ss.Pinned != nil: - return &FieldError{ - Message: "Expected exactly one, got both", - Paths: []string{"runLatest", "pinned"}, - } - case ss.RunLatest != nil: - return ss.RunLatest.Validate().ViaField("runLatest") - case ss.Pinned != nil: - return ss.Pinned.Validate().ViaField("pinned") - default: - return &FieldError{ - Message: "Expected exactly one, got neither", - Paths: []string{"runLatest", "pinned"}, - } + var errs *apis.FieldError + set := []string{} + + if ss.RunLatest != nil { + set = append(set, "runLatest") + errs = errs.Also(ss.RunLatest.Validate().ViaField("runLatest")) + } + if ss.Release != nil { + set = append(set, "release") + errs = errs.Also(ss.Release.Validate().ViaField("release")) } + if ss.Manual != nil { + set = append(set, "manual") + errs = errs.Also(ss.Manual.Validate().ViaField("manual")) + } + if ss.Pinned != nil { + set = append(set, "pinned") + errs = errs.Also(ss.Pinned.Validate().ViaField("pinned")) + } + + if len(set) > 1 { + errs = errs.Also(apis.ErrMultipleOneOf(set...)) + } else if len(set) == 0 { + errs = errs.Also(apis.ErrMissingOneOf("runLatest", "release", "manual", "pinned")) + } + return errs } -func (pt *PinnedType) Validate() *FieldError { +// Validate validates the fields belonging to PinnedType +func (pt *PinnedType) Validate() *apis.FieldError { + var errs *apis.FieldError if pt.RevisionName == "" { - return errMissingField("revisionName") + errs = apis.ErrMissingField("revisionName") } - return pt.Configuration.Validate().ViaField("configuration") + return errs.Also(pt.Configuration.Validate().ViaField("configuration")) } -func (rlt *RunLatestType) Validate() *FieldError { +// Validate validates the fields belonging to RunLatestType +func (rlt *RunLatestType) Validate() *apis.FieldError { return rlt.Configuration.Validate().ViaField("configuration") } + +// Validate validates the fields belonging to ManualType +func (m *ManualType) Validate() *apis.FieldError { + return nil +} + +// Validate validates the fields belonging to ReleaseType +func (rt *ReleaseType) Validate() *apis.FieldError { + var errs *apis.FieldError + minRevisions := 1 + maxRevisions := 2 + + numRevisions := len(rt.Revisions) + if numRevisions < minRevisions { + errs = errs.Also(apis.ErrMissingField("revisions")) + } + + if numRevisions > maxRevisions { + outOfRange := &apis.FieldError{ + Message: fmt.Sprintf("expected number of elements in range [%v, %v], got %v", minRevisions, maxRevisions, numRevisions), + Paths: []string{"revisions"}, + } + errs = errs.Also(outOfRange) + } + + if numRevisions < 2 && rt.RolloutPercent != 0 { + errs = errs.Also(apis.ErrInvalidValue(fmt.Sprintf("%v", rt.RolloutPercent), "rolloutPercent")) + } + + if rt.RolloutPercent < 0 || rt.RolloutPercent > 99 { + errs = errs.Also(apis.ErrInvalidValue(fmt.Sprintf("%v", rt.RolloutPercent), "rolloutPercent")) + } + + return errs.Also(rt.Configuration.Validate().ViaField("configuration")) +} diff --git a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/zz_generated.deepcopy.go b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/zz_generated.deepcopy.go index 62e5b279e2e..3504d03a30a 100644 --- a/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/zz_generated.deepcopy.go +++ b/vendor/github.com/knative/serving/pkg/apis/serving/v1alpha1/zz_generated.deepcopy.go @@ -22,6 +22,8 @@ package v1alpha1 import ( build_v1alpha1 "github.com/knative/build/pkg/apis/build/v1alpha1" + duck_v1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" + v1 "k8s.io/api/core/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) @@ -54,23 +56,6 @@ func (in *Configuration) DeepCopyObject() runtime.Object { } } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ConfigurationCondition) DeepCopyInto(out *ConfigurationCondition) { - *out = *in - in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConfigurationCondition. -func (in *ConfigurationCondition) DeepCopy() *ConfigurationCondition { - if in == nil { - return nil - } - out := new(ConfigurationCondition) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ConfigurationList) DeepCopyInto(out *ConfigurationList) { *out = *in @@ -113,7 +98,7 @@ func (in *ConfigurationSpec) DeepCopyInto(out *ConfigurationSpec) { if *in == nil { *out = nil } else { - *out = new(build_v1alpha1.BuildSpec) + *out = new(RawExtension) (*in).DeepCopyInto(*out) } } @@ -136,7 +121,7 @@ func (in *ConfigurationStatus) DeepCopyInto(out *ConfigurationStatus) { *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make([]ConfigurationCondition, len(*in)) + *out = make(duck_v1alpha1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -154,6 +139,22 @@ func (in *ConfigurationStatus) DeepCopy() *ConfigurationStatus { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ManualType) DeepCopyInto(out *ManualType) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ManualType. +func (in *ManualType) DeepCopy() *ManualType { + if in == nil { + return nil + } + out := new(ManualType) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PinnedType) DeepCopyInto(out *PinnedType) { *out = *in @@ -171,6 +172,63 @@ func (in *PinnedType) DeepCopy() *PinnedType { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RawExtension) DeepCopyInto(out *RawExtension) { + *out = *in + if in.Raw != nil { + in, out := &in.Raw, &out.Raw + *out = make([]byte, len(*in)) + copy(*out, *in) + } + if in.Object == nil { + out.Object = nil + } else { + out.Object = in.Object.DeepCopyObject() + } + if in.BuildSpec != nil { + in, out := &in.BuildSpec, &out.BuildSpec + if *in == nil { + *out = nil + } else { + *out = new(build_v1alpha1.BuildSpec) + (*in).DeepCopyInto(*out) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RawExtension. +func (in *RawExtension) DeepCopy() *RawExtension { + if in == nil { + return nil + } + out := new(RawExtension) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ReleaseType) DeepCopyInto(out *ReleaseType) { + *out = *in + if in.Revisions != nil { + in, out := &in.Revisions, &out.Revisions + *out = make([]string, len(*in)) + copy(*out, *in) + } + in.Configuration.DeepCopyInto(&out.Configuration) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ReleaseType. +func (in *ReleaseType) DeepCopy() *ReleaseType { + if in == nil { + return nil + } + out := new(ReleaseType) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Revision) DeepCopyInto(out *Revision) { *out = *in @@ -200,23 +258,6 @@ func (in *Revision) DeepCopyObject() runtime.Object { } } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *RevisionCondition) DeepCopyInto(out *RevisionCondition) { - *out = *in - in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RevisionCondition. -func (in *RevisionCondition) DeepCopy() *RevisionCondition { - if in == nil { - return nil - } - out := new(RevisionCondition) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RevisionList) DeepCopyInto(out *RevisionList) { *out = *in @@ -254,6 +295,15 @@ func (in *RevisionList) DeepCopyObject() runtime.Object { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RevisionSpec) DeepCopyInto(out *RevisionSpec) { *out = *in + if in.BuildRef != nil { + in, out := &in.BuildRef, &out.BuildRef + if *in == nil { + *out = nil + } else { + *out = new(v1.ObjectReference) + **out = **in + } + } in.Container.DeepCopyInto(&out.Container) return } @@ -273,7 +323,7 @@ func (in *RevisionStatus) DeepCopyInto(out *RevisionStatus) { *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make([]RevisionCondition, len(*in)) + *out = make(duck_v1alpha1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -338,23 +388,6 @@ func (in *Route) DeepCopyObject() runtime.Object { } } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *RouteCondition) DeepCopyInto(out *RouteCondition) { - *out = *in - in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RouteCondition. -func (in *RouteCondition) DeepCopy() *RouteCondition { - if in == nil { - return nil - } - out := new(RouteCondition) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RouteList) DeepCopyInto(out *RouteList) { *out = *in @@ -413,6 +446,15 @@ func (in *RouteSpec) DeepCopy() *RouteSpec { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RouteStatus) DeepCopyInto(out *RouteStatus) { *out = *in + if in.Address != nil { + in, out := &in.Address, &out.Address + if *in == nil { + *out = nil + } else { + *out = new(duck_v1alpha1.Addressable) + **out = **in + } + } if in.Traffic != nil { in, out := &in.Traffic, &out.Traffic *out = make([]TrafficTarget, len(*in)) @@ -420,7 +462,7 @@ func (in *RouteStatus) DeepCopyInto(out *RouteStatus) { } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make([]RouteCondition, len(*in)) + *out = make(duck_v1alpha1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -484,23 +526,6 @@ func (in *Service) DeepCopyObject() runtime.Object { } } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ServiceCondition) DeepCopyInto(out *ServiceCondition) { - *out = *in - in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServiceCondition. -func (in *ServiceCondition) DeepCopy() *ServiceCondition { - if in == nil { - return nil - } - out := new(ServiceCondition) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ServiceList) DeepCopyInto(out *ServiceList) { *out = *in @@ -556,6 +581,24 @@ func (in *ServiceSpec) DeepCopyInto(out *ServiceSpec) { (*in).DeepCopyInto(*out) } } + if in.Manual != nil { + in, out := &in.Manual, &out.Manual + if *in == nil { + *out = nil + } else { + *out = new(ManualType) + **out = **in + } + } + if in.Release != nil { + in, out := &in.Release, &out.Release + if *in == nil { + *out = nil + } else { + *out = new(ReleaseType) + (*in).DeepCopyInto(*out) + } + } return } @@ -574,11 +617,20 @@ func (in *ServiceStatus) DeepCopyInto(out *ServiceStatus) { *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make([]ServiceCondition, len(*in)) + *out = make(duck_v1alpha1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } + if in.Address != nil { + in, out := &in.Address, &out.Address + if *in == nil { + *out = nil + } else { + *out = new(duck_v1alpha1.Addressable) + **out = **in + } + } if in.Traffic != nil { in, out := &in.Traffic, &out.Traffic *out = make([]TrafficTarget, len(*in)) diff --git a/vendor/github.com/knative/serving/pkg/client/clientset/versioned/clientset.go b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/clientset.go index 2041ea8b12e..3a8f4a4d858 100644 --- a/vendor/github.com/knative/serving/pkg/client/clientset/versioned/clientset.go +++ b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/clientset.go @@ -16,8 +16,8 @@ limitations under the License. package versioned import ( - glog "github.com/golang/glog" - networkingv1alpha3 "github.com/knative/serving/pkg/client/clientset/versioned/typed/istio/v1alpha3" + autoscalingv1alpha1 "github.com/knative/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1" + networkingv1alpha1 "github.com/knative/serving/pkg/client/clientset/versioned/typed/networking/v1alpha1" servingv1alpha1 "github.com/knative/serving/pkg/client/clientset/versioned/typed/serving/v1alpha1" discovery "k8s.io/client-go/discovery" rest "k8s.io/client-go/rest" @@ -26,9 +26,12 @@ import ( type Interface interface { Discovery() discovery.DiscoveryInterface - NetworkingV1alpha3() networkingv1alpha3.NetworkingV1alpha3Interface + AutoscalingV1alpha1() autoscalingv1alpha1.AutoscalingV1alpha1Interface // Deprecated: please explicitly pick a version if possible. - Networking() networkingv1alpha3.NetworkingV1alpha3Interface + Autoscaling() autoscalingv1alpha1.AutoscalingV1alpha1Interface + NetworkingV1alpha1() networkingv1alpha1.NetworkingV1alpha1Interface + // Deprecated: please explicitly pick a version if possible. + Networking() networkingv1alpha1.NetworkingV1alpha1Interface ServingV1alpha1() servingv1alpha1.ServingV1alpha1Interface // Deprecated: please explicitly pick a version if possible. Serving() servingv1alpha1.ServingV1alpha1Interface @@ -38,19 +41,31 @@ type Interface interface { // version included in a Clientset. type Clientset struct { *discovery.DiscoveryClient - networkingV1alpha3 *networkingv1alpha3.NetworkingV1alpha3Client - servingV1alpha1 *servingv1alpha1.ServingV1alpha1Client + autoscalingV1alpha1 *autoscalingv1alpha1.AutoscalingV1alpha1Client + networkingV1alpha1 *networkingv1alpha1.NetworkingV1alpha1Client + servingV1alpha1 *servingv1alpha1.ServingV1alpha1Client } -// NetworkingV1alpha3 retrieves the NetworkingV1alpha3Client -func (c *Clientset) NetworkingV1alpha3() networkingv1alpha3.NetworkingV1alpha3Interface { - return c.networkingV1alpha3 +// AutoscalingV1alpha1 retrieves the AutoscalingV1alpha1Client +func (c *Clientset) AutoscalingV1alpha1() autoscalingv1alpha1.AutoscalingV1alpha1Interface { + return c.autoscalingV1alpha1 +} + +// Deprecated: Autoscaling retrieves the default version of AutoscalingClient. +// Please explicitly pick a version. +func (c *Clientset) Autoscaling() autoscalingv1alpha1.AutoscalingV1alpha1Interface { + return c.autoscalingV1alpha1 +} + +// NetworkingV1alpha1 retrieves the NetworkingV1alpha1Client +func (c *Clientset) NetworkingV1alpha1() networkingv1alpha1.NetworkingV1alpha1Interface { + return c.networkingV1alpha1 } // Deprecated: Networking retrieves the default version of NetworkingClient. // Please explicitly pick a version. -func (c *Clientset) Networking() networkingv1alpha3.NetworkingV1alpha3Interface { - return c.networkingV1alpha3 +func (c *Clientset) Networking() networkingv1alpha1.NetworkingV1alpha1Interface { + return c.networkingV1alpha1 } // ServingV1alpha1 retrieves the ServingV1alpha1Client @@ -80,7 +95,11 @@ func NewForConfig(c *rest.Config) (*Clientset, error) { } var cs Clientset var err error - cs.networkingV1alpha3, err = networkingv1alpha3.NewForConfig(&configShallowCopy) + cs.autoscalingV1alpha1, err = autoscalingv1alpha1.NewForConfig(&configShallowCopy) + if err != nil { + return nil, err + } + cs.networkingV1alpha1, err = networkingv1alpha1.NewForConfig(&configShallowCopy) if err != nil { return nil, err } @@ -91,7 +110,6 @@ func NewForConfig(c *rest.Config) (*Clientset, error) { cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy) if err != nil { - glog.Errorf("failed to create the DiscoveryClient: %v", err) return nil, err } return &cs, nil @@ -101,7 +119,8 @@ func NewForConfig(c *rest.Config) (*Clientset, error) { // panics if there is an error in the config. func NewForConfigOrDie(c *rest.Config) *Clientset { var cs Clientset - cs.networkingV1alpha3 = networkingv1alpha3.NewForConfigOrDie(c) + cs.autoscalingV1alpha1 = autoscalingv1alpha1.NewForConfigOrDie(c) + cs.networkingV1alpha1 = networkingv1alpha1.NewForConfigOrDie(c) cs.servingV1alpha1 = servingv1alpha1.NewForConfigOrDie(c) cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c) @@ -111,7 +130,8 @@ func NewForConfigOrDie(c *rest.Config) *Clientset { // New creates a new Clientset for the given RESTClient. func New(c rest.Interface) *Clientset { var cs Clientset - cs.networkingV1alpha3 = networkingv1alpha3.New(c) + cs.autoscalingV1alpha1 = autoscalingv1alpha1.New(c) + cs.networkingV1alpha1 = networkingv1alpha1.New(c) cs.servingV1alpha1 = servingv1alpha1.New(c) cs.DiscoveryClient = discovery.NewDiscoveryClient(c) diff --git a/vendor/github.com/knative/serving/pkg/client/clientset/versioned/scheme/register.go b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/scheme/register.go index f9745bd9766..9d38af8707a 100644 --- a/vendor/github.com/knative/serving/pkg/client/clientset/versioned/scheme/register.go +++ b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/scheme/register.go @@ -16,7 +16,8 @@ limitations under the License. package scheme import ( - networkingv1alpha3 "github.com/knative/serving/pkg/apis/istio/v1alpha3" + autoscalingv1alpha1 "github.com/knative/serving/pkg/apis/autoscaling/v1alpha1" + networkingv1alpha1 "github.com/knative/serving/pkg/apis/networking/v1alpha1" servingv1alpha1 "github.com/knative/serving/pkg/apis/serving/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" @@ -48,6 +49,7 @@ func init() { // After this, RawExtensions in Kubernetes types will serialize kube-aggregator types // correctly. func AddToScheme(scheme *runtime.Scheme) { - networkingv1alpha3.AddToScheme(scheme) + autoscalingv1alpha1.AddToScheme(scheme) + networkingv1alpha1.AddToScheme(scheme) servingv1alpha1.AddToScheme(scheme) } diff --git a/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/istio/v1alpha3/istio_client.go b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/autoscaling_client.go similarity index 57% rename from vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/istio/v1alpha3/istio_client.go rename to vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/autoscaling_client.go index e2869ab0b29..04623c09ef3 100644 --- a/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/istio/v1alpha3/istio_client.go +++ b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/autoscaling_client.go @@ -13,36 +13,31 @@ 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 v1alpha3 +package v1alpha1 import ( - v1alpha3 "github.com/knative/serving/pkg/apis/istio/v1alpha3" + v1alpha1 "github.com/knative/serving/pkg/apis/autoscaling/v1alpha1" "github.com/knative/serving/pkg/client/clientset/versioned/scheme" serializer "k8s.io/apimachinery/pkg/runtime/serializer" rest "k8s.io/client-go/rest" ) -type NetworkingV1alpha3Interface interface { +type AutoscalingV1alpha1Interface interface { RESTClient() rest.Interface - GatewaysGetter - VirtualServicesGetter + PodAutoscalersGetter } -// NetworkingV1alpha3Client is used to interact with features provided by the networking.istio.io group. -type NetworkingV1alpha3Client struct { +// AutoscalingV1alpha1Client is used to interact with features provided by the autoscaling.internal.knative.dev group. +type AutoscalingV1alpha1Client struct { restClient rest.Interface } -func (c *NetworkingV1alpha3Client) Gateways(namespace string) GatewayInterface { - return newGateways(c, namespace) +func (c *AutoscalingV1alpha1Client) PodAutoscalers(namespace string) PodAutoscalerInterface { + return newPodAutoscalers(c, namespace) } -func (c *NetworkingV1alpha3Client) VirtualServices(namespace string) VirtualServiceInterface { - return newVirtualServices(c, namespace) -} - -// NewForConfig creates a new NetworkingV1alpha3Client for the given config. -func NewForConfig(c *rest.Config) (*NetworkingV1alpha3Client, error) { +// NewForConfig creates a new AutoscalingV1alpha1Client for the given config. +func NewForConfig(c *rest.Config) (*AutoscalingV1alpha1Client, error) { config := *c if err := setConfigDefaults(&config); err != nil { return nil, err @@ -51,12 +46,12 @@ func NewForConfig(c *rest.Config) (*NetworkingV1alpha3Client, error) { if err != nil { return nil, err } - return &NetworkingV1alpha3Client{client}, nil + return &AutoscalingV1alpha1Client{client}, nil } -// NewForConfigOrDie creates a new NetworkingV1alpha3Client for the given config and +// NewForConfigOrDie creates a new AutoscalingV1alpha1Client for the given config and // panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *NetworkingV1alpha3Client { +func NewForConfigOrDie(c *rest.Config) *AutoscalingV1alpha1Client { client, err := NewForConfig(c) if err != nil { panic(err) @@ -64,13 +59,13 @@ func NewForConfigOrDie(c *rest.Config) *NetworkingV1alpha3Client { return client } -// New creates a new NetworkingV1alpha3Client for the given RESTClient. -func New(c rest.Interface) *NetworkingV1alpha3Client { - return &NetworkingV1alpha3Client{c} +// New creates a new AutoscalingV1alpha1Client for the given RESTClient. +func New(c rest.Interface) *AutoscalingV1alpha1Client { + return &AutoscalingV1alpha1Client{c} } func setConfigDefaults(config *rest.Config) error { - gv := v1alpha3.SchemeGroupVersion + gv := v1alpha1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs} @@ -84,7 +79,7 @@ func setConfigDefaults(config *rest.Config) error { // RESTClient returns a RESTClient that is used to communicate // with API server by this client implementation. -func (c *NetworkingV1alpha3Client) RESTClient() rest.Interface { +func (c *AutoscalingV1alpha1Client) RESTClient() rest.Interface { if c == nil { return nil } diff --git a/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/istio/v1alpha3/doc.go b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/doc.go similarity index 97% rename from vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/istio/v1alpha3/doc.go rename to vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/doc.go index d1909a47d81..10ede9da2f0 100644 --- a/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/istio/v1alpha3/doc.go +++ b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/doc.go @@ -14,4 +14,4 @@ See the License for the specific language governing permissions and limitations under the License. */ // This package has the automatically generated typed clients. -package v1alpha3 +package v1alpha1 diff --git a/pkg/apis/flows/register.go b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/generated_expansion.go similarity index 90% rename from pkg/apis/flows/register.go rename to vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/generated_expansion.go index bf9e7baf01c..933bb688f91 100644 --- a/pkg/apis/flows/register.go +++ b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/generated_expansion.go @@ -13,9 +13,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ +package v1alpha1 -package flows - -const ( - GroupName = "flows.knative.dev" -) +type PodAutoscalerExpansion interface{} diff --git a/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/podautoscaler.go b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/podautoscaler.go new file mode 100644 index 00000000000..687cda122cd --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/autoscaling/v1alpha1/podautoscaler.go @@ -0,0 +1,171 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package v1alpha1 + +import ( + v1alpha1 "github.com/knative/serving/pkg/apis/autoscaling/v1alpha1" + scheme "github.com/knative/serving/pkg/client/clientset/versioned/scheme" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" +) + +// PodAutoscalersGetter has a method to return a PodAutoscalerInterface. +// A group's client should implement this interface. +type PodAutoscalersGetter interface { + PodAutoscalers(namespace string) PodAutoscalerInterface +} + +// PodAutoscalerInterface has methods to work with PodAutoscaler resources. +type PodAutoscalerInterface interface { + Create(*v1alpha1.PodAutoscaler) (*v1alpha1.PodAutoscaler, error) + Update(*v1alpha1.PodAutoscaler) (*v1alpha1.PodAutoscaler, error) + UpdateStatus(*v1alpha1.PodAutoscaler) (*v1alpha1.PodAutoscaler, error) + Delete(name string, options *v1.DeleteOptions) error + DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error + Get(name string, options v1.GetOptions) (*v1alpha1.PodAutoscaler, error) + List(opts v1.ListOptions) (*v1alpha1.PodAutoscalerList, error) + Watch(opts v1.ListOptions) (watch.Interface, error) + Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.PodAutoscaler, err error) + PodAutoscalerExpansion +} + +// podAutoscalers implements PodAutoscalerInterface +type podAutoscalers struct { + client rest.Interface + ns string +} + +// newPodAutoscalers returns a PodAutoscalers +func newPodAutoscalers(c *AutoscalingV1alpha1Client, namespace string) *podAutoscalers { + return &podAutoscalers{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the podAutoscaler, and returns the corresponding podAutoscaler object, and an error if there is any. +func (c *podAutoscalers) Get(name string, options v1.GetOptions) (result *v1alpha1.PodAutoscaler, err error) { + result = &v1alpha1.PodAutoscaler{} + err = c.client.Get(). + Namespace(c.ns). + Resource("podautoscalers"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of PodAutoscalers that match those selectors. +func (c *podAutoscalers) List(opts v1.ListOptions) (result *v1alpha1.PodAutoscalerList, err error) { + result = &v1alpha1.PodAutoscalerList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("podautoscalers"). + VersionedParams(&opts, scheme.ParameterCodec). + Do(). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested podAutoscalers. +func (c *podAutoscalers) Watch(opts v1.ListOptions) (watch.Interface, error) { + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("podautoscalers"). + VersionedParams(&opts, scheme.ParameterCodec). + Watch() +} + +// Create takes the representation of a podAutoscaler and creates it. Returns the server's representation of the podAutoscaler, and an error, if there is any. +func (c *podAutoscalers) Create(podAutoscaler *v1alpha1.PodAutoscaler) (result *v1alpha1.PodAutoscaler, err error) { + result = &v1alpha1.PodAutoscaler{} + err = c.client.Post(). + Namespace(c.ns). + Resource("podautoscalers"). + Body(podAutoscaler). + Do(). + Into(result) + return +} + +// Update takes the representation of a podAutoscaler and updates it. Returns the server's representation of the podAutoscaler, and an error, if there is any. +func (c *podAutoscalers) Update(podAutoscaler *v1alpha1.PodAutoscaler) (result *v1alpha1.PodAutoscaler, err error) { + result = &v1alpha1.PodAutoscaler{} + err = c.client.Put(). + Namespace(c.ns). + Resource("podautoscalers"). + Name(podAutoscaler.Name). + Body(podAutoscaler). + Do(). + Into(result) + return +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + +func (c *podAutoscalers) UpdateStatus(podAutoscaler *v1alpha1.PodAutoscaler) (result *v1alpha1.PodAutoscaler, err error) { + result = &v1alpha1.PodAutoscaler{} + err = c.client.Put(). + Namespace(c.ns). + Resource("podautoscalers"). + Name(podAutoscaler.Name). + SubResource("status"). + Body(podAutoscaler). + Do(). + Into(result) + return +} + +// Delete takes name of the podAutoscaler and deletes it. Returns an error if one occurs. +func (c *podAutoscalers) Delete(name string, options *v1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("podautoscalers"). + Name(name). + Body(options). + Do(). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *podAutoscalers) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("podautoscalers"). + VersionedParams(&listOptions, scheme.ParameterCodec). + Body(options). + Do(). + Error() +} + +// Patch applies the patch and returns the patched podAutoscaler. +func (c *podAutoscalers) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.PodAutoscaler, err error) { + result = &v1alpha1.PodAutoscaler{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("podautoscalers"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/istio/v1alpha3/gateway.go b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/istio/v1alpha3/gateway.go deleted file mode 100644 index 70ccd02d145..00000000000 --- a/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/istio/v1alpha3/gateway.go +++ /dev/null @@ -1,154 +0,0 @@ -/* -Copyright 2018 The Knative 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 v1alpha3 - -import ( - v1alpha3 "github.com/knative/serving/pkg/apis/istio/v1alpha3" - scheme "github.com/knative/serving/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// GatewaysGetter has a method to return a GatewayInterface. -// A group's client should implement this interface. -type GatewaysGetter interface { - Gateways(namespace string) GatewayInterface -} - -// GatewayInterface has methods to work with Gateway resources. -type GatewayInterface interface { - Create(*v1alpha3.Gateway) (*v1alpha3.Gateway, error) - Update(*v1alpha3.Gateway) (*v1alpha3.Gateway, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha3.Gateway, error) - List(opts v1.ListOptions) (*v1alpha3.GatewayList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha3.Gateway, err error) - GatewayExpansion -} - -// gateways implements GatewayInterface -type gateways struct { - client rest.Interface - ns string -} - -// newGateways returns a Gateways -func newGateways(c *NetworkingV1alpha3Client, namespace string) *gateways { - return &gateways{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the gateway, and returns the corresponding gateway object, and an error if there is any. -func (c *gateways) Get(name string, options v1.GetOptions) (result *v1alpha3.Gateway, err error) { - result = &v1alpha3.Gateway{} - err = c.client.Get(). - Namespace(c.ns). - Resource("gateways"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of Gateways that match those selectors. -func (c *gateways) List(opts v1.ListOptions) (result *v1alpha3.GatewayList, err error) { - result = &v1alpha3.GatewayList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("gateways"). - VersionedParams(&opts, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested gateways. -func (c *gateways) Watch(opts v1.ListOptions) (watch.Interface, error) { - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("gateways"). - VersionedParams(&opts, scheme.ParameterCodec). - Watch() -} - -// Create takes the representation of a gateway and creates it. Returns the server's representation of the gateway, and an error, if there is any. -func (c *gateways) Create(gateway *v1alpha3.Gateway) (result *v1alpha3.Gateway, err error) { - result = &v1alpha3.Gateway{} - err = c.client.Post(). - Namespace(c.ns). - Resource("gateways"). - Body(gateway). - Do(). - Into(result) - return -} - -// Update takes the representation of a gateway and updates it. Returns the server's representation of the gateway, and an error, if there is any. -func (c *gateways) Update(gateway *v1alpha3.Gateway) (result *v1alpha3.Gateway, err error) { - result = &v1alpha3.Gateway{} - err = c.client.Put(). - Namespace(c.ns). - Resource("gateways"). - Name(gateway.Name). - Body(gateway). - Do(). - Into(result) - return -} - -// Delete takes name of the gateway and deletes it. Returns an error if one occurs. -func (c *gateways) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("gateways"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *gateways) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("gateways"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched gateway. -func (c *gateways) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha3.Gateway, err error) { - result = &v1alpha3.Gateway{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("gateways"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/istio/v1alpha3/generated_expansion.go b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/istio/v1alpha3/generated_expansion.go deleted file mode 100644 index c746b14b13e..00000000000 --- a/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/istio/v1alpha3/generated_expansion.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2018 The Knative 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 v1alpha3 - -type GatewayExpansion interface{} - -type VirtualServiceExpansion interface{} diff --git a/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/istio/v1alpha3/virtualservice.go b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/istio/v1alpha3/virtualservice.go deleted file mode 100644 index feec0590710..00000000000 --- a/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/istio/v1alpha3/virtualservice.go +++ /dev/null @@ -1,154 +0,0 @@ -/* -Copyright 2018 The Knative 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 v1alpha3 - -import ( - v1alpha3 "github.com/knative/serving/pkg/apis/istio/v1alpha3" - scheme "github.com/knative/serving/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// VirtualServicesGetter has a method to return a VirtualServiceInterface. -// A group's client should implement this interface. -type VirtualServicesGetter interface { - VirtualServices(namespace string) VirtualServiceInterface -} - -// VirtualServiceInterface has methods to work with VirtualService resources. -type VirtualServiceInterface interface { - Create(*v1alpha3.VirtualService) (*v1alpha3.VirtualService, error) - Update(*v1alpha3.VirtualService) (*v1alpha3.VirtualService, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha3.VirtualService, error) - List(opts v1.ListOptions) (*v1alpha3.VirtualServiceList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha3.VirtualService, err error) - VirtualServiceExpansion -} - -// virtualServices implements VirtualServiceInterface -type virtualServices struct { - client rest.Interface - ns string -} - -// newVirtualServices returns a VirtualServices -func newVirtualServices(c *NetworkingV1alpha3Client, namespace string) *virtualServices { - return &virtualServices{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the virtualService, and returns the corresponding virtualService object, and an error if there is any. -func (c *virtualServices) Get(name string, options v1.GetOptions) (result *v1alpha3.VirtualService, err error) { - result = &v1alpha3.VirtualService{} - err = c.client.Get(). - Namespace(c.ns). - Resource("virtualservices"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of VirtualServices that match those selectors. -func (c *virtualServices) List(opts v1.ListOptions) (result *v1alpha3.VirtualServiceList, err error) { - result = &v1alpha3.VirtualServiceList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("virtualservices"). - VersionedParams(&opts, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested virtualServices. -func (c *virtualServices) Watch(opts v1.ListOptions) (watch.Interface, error) { - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("virtualservices"). - VersionedParams(&opts, scheme.ParameterCodec). - Watch() -} - -// Create takes the representation of a virtualService and creates it. Returns the server's representation of the virtualService, and an error, if there is any. -func (c *virtualServices) Create(virtualService *v1alpha3.VirtualService) (result *v1alpha3.VirtualService, err error) { - result = &v1alpha3.VirtualService{} - err = c.client.Post(). - Namespace(c.ns). - Resource("virtualservices"). - Body(virtualService). - Do(). - Into(result) - return -} - -// Update takes the representation of a virtualService and updates it. Returns the server's representation of the virtualService, and an error, if there is any. -func (c *virtualServices) Update(virtualService *v1alpha3.VirtualService) (result *v1alpha3.VirtualService, err error) { - result = &v1alpha3.VirtualService{} - err = c.client.Put(). - Namespace(c.ns). - Resource("virtualservices"). - Name(virtualService.Name). - Body(virtualService). - Do(). - Into(result) - return -} - -// Delete takes name of the virtualService and deletes it. Returns an error if one occurs. -func (c *virtualServices) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("virtualservices"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *virtualServices) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("virtualservices"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched virtualService. -func (c *virtualServices) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha3.VirtualService, err error) { - result = &v1alpha3.VirtualService{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("virtualservices"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/networking/v1alpha1/clusteringress.go b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/networking/v1alpha1/clusteringress.go new file mode 100644 index 00000000000..18231946ba8 --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/networking/v1alpha1/clusteringress.go @@ -0,0 +1,160 @@ +/* +Copyright 2018 The Knative Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package v1alpha1 + +import ( + v1alpha1 "github.com/knative/serving/pkg/apis/networking/v1alpha1" + scheme "github.com/knative/serving/pkg/client/clientset/versioned/scheme" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" +) + +// ClusterIngressesGetter has a method to return a ClusterIngressInterface. +// A group's client should implement this interface. +type ClusterIngressesGetter interface { + ClusterIngresses() ClusterIngressInterface +} + +// ClusterIngressInterface has methods to work with ClusterIngress resources. +type ClusterIngressInterface interface { + Create(*v1alpha1.ClusterIngress) (*v1alpha1.ClusterIngress, error) + Update(*v1alpha1.ClusterIngress) (*v1alpha1.ClusterIngress, error) + UpdateStatus(*v1alpha1.ClusterIngress) (*v1alpha1.ClusterIngress, error) + Delete(name string, options *v1.DeleteOptions) error + DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error + Get(name string, options v1.GetOptions) (*v1alpha1.ClusterIngress, error) + List(opts v1.ListOptions) (*v1alpha1.ClusterIngressList, error) + Watch(opts v1.ListOptions) (watch.Interface, error) + Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterIngress, err error) + ClusterIngressExpansion +} + +// clusterIngresses implements ClusterIngressInterface +type clusterIngresses struct { + client rest.Interface +} + +// newClusterIngresses returns a ClusterIngresses +func newClusterIngresses(c *NetworkingV1alpha1Client) *clusterIngresses { + return &clusterIngresses{ + client: c.RESTClient(), + } +} + +// Get takes name of the clusterIngress, and returns the corresponding clusterIngress object, and an error if there is any. +func (c *clusterIngresses) Get(name string, options v1.GetOptions) (result *v1alpha1.ClusterIngress, err error) { + result = &v1alpha1.ClusterIngress{} + err = c.client.Get(). + Resource("clusteringresses"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of ClusterIngresses that match those selectors. +func (c *clusterIngresses) List(opts v1.ListOptions) (result *v1alpha1.ClusterIngressList, err error) { + result = &v1alpha1.ClusterIngressList{} + err = c.client.Get(). + Resource("clusteringresses"). + VersionedParams(&opts, scheme.ParameterCodec). + Do(). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested clusterIngresses. +func (c *clusterIngresses) Watch(opts v1.ListOptions) (watch.Interface, error) { + opts.Watch = true + return c.client.Get(). + Resource("clusteringresses"). + VersionedParams(&opts, scheme.ParameterCodec). + Watch() +} + +// Create takes the representation of a clusterIngress and creates it. Returns the server's representation of the clusterIngress, and an error, if there is any. +func (c *clusterIngresses) Create(clusterIngress *v1alpha1.ClusterIngress) (result *v1alpha1.ClusterIngress, err error) { + result = &v1alpha1.ClusterIngress{} + err = c.client.Post(). + Resource("clusteringresses"). + Body(clusterIngress). + Do(). + Into(result) + return +} + +// Update takes the representation of a clusterIngress and updates it. Returns the server's representation of the clusterIngress, and an error, if there is any. +func (c *clusterIngresses) Update(clusterIngress *v1alpha1.ClusterIngress) (result *v1alpha1.ClusterIngress, err error) { + result = &v1alpha1.ClusterIngress{} + err = c.client.Put(). + Resource("clusteringresses"). + Name(clusterIngress.Name). + Body(clusterIngress). + Do(). + Into(result) + return +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + +func (c *clusterIngresses) UpdateStatus(clusterIngress *v1alpha1.ClusterIngress) (result *v1alpha1.ClusterIngress, err error) { + result = &v1alpha1.ClusterIngress{} + err = c.client.Put(). + Resource("clusteringresses"). + Name(clusterIngress.Name). + SubResource("status"). + Body(clusterIngress). + Do(). + Into(result) + return +} + +// Delete takes name of the clusterIngress and deletes it. Returns an error if one occurs. +func (c *clusterIngresses) Delete(name string, options *v1.DeleteOptions) error { + return c.client.Delete(). + Resource("clusteringresses"). + Name(name). + Body(options). + Do(). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *clusterIngresses) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + return c.client.Delete(). + Resource("clusteringresses"). + VersionedParams(&listOptions, scheme.ParameterCodec). + Body(options). + Do(). + Error() +} + +// Patch applies the patch and returns the patched clusterIngress. +func (c *clusterIngresses) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.ClusterIngress, err error) { + result = &v1alpha1.ClusterIngress{} + err = c.client.Patch(pt). + Resource("clusteringresses"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/doc.go b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/networking/v1alpha1/doc.go similarity index 93% rename from pkg/client/clientset/versioned/typed/feeds/v1alpha1/doc.go rename to vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/networking/v1alpha1/doc.go index 75445c17900..10ede9da2f0 100644 --- a/pkg/client/clientset/versioned/typed/feeds/v1alpha1/doc.go +++ b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/networking/v1alpha1/doc.go @@ -13,8 +13,5 @@ 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. */ - -// Code generated by client-gen. DO NOT EDIT. - // This package has the automatically generated typed clients. package v1alpha1 diff --git a/pkg/apis/feeds/register.go b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/networking/v1alpha1/generated_expansion.go similarity index 90% rename from pkg/apis/feeds/register.go rename to vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/networking/v1alpha1/generated_expansion.go index b47f805856a..73063b5d3de 100644 --- a/pkg/apis/feeds/register.go +++ b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/networking/v1alpha1/generated_expansion.go @@ -13,9 +13,6 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ +package v1alpha1 -package feeds - -const ( - GroupName = "feeds.knative.dev" -) +type ClusterIngressExpansion interface{} diff --git a/pkg/client/clientset/versioned/typed/flows/v1alpha1/flows_client.go b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/networking/v1alpha1/networking_client.go similarity index 59% rename from pkg/client/clientset/versioned/typed/flows/v1alpha1/flows_client.go rename to vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/networking/v1alpha1/networking_client.go index 961c1d1972b..3fb18887b2f 100644 --- a/pkg/client/clientset/versioned/typed/flows/v1alpha1/flows_client.go +++ b/vendor/github.com/knative/serving/pkg/client/clientset/versioned/typed/networking/v1alpha1/networking_client.go @@ -13,34 +13,31 @@ 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. */ - -// Code generated by client-gen. DO NOT EDIT. - package v1alpha1 import ( - v1alpha1 "github.com/knative/eventing/pkg/apis/flows/v1alpha1" - "github.com/knative/eventing/pkg/client/clientset/versioned/scheme" + v1alpha1 "github.com/knative/serving/pkg/apis/networking/v1alpha1" + "github.com/knative/serving/pkg/client/clientset/versioned/scheme" serializer "k8s.io/apimachinery/pkg/runtime/serializer" rest "k8s.io/client-go/rest" ) -type FlowsV1alpha1Interface interface { +type NetworkingV1alpha1Interface interface { RESTClient() rest.Interface - FlowsGetter + ClusterIngressesGetter } -// FlowsV1alpha1Client is used to interact with features provided by the flows.knative.dev group. -type FlowsV1alpha1Client struct { +// NetworkingV1alpha1Client is used to interact with features provided by the networking.internal.knative.dev group. +type NetworkingV1alpha1Client struct { restClient rest.Interface } -func (c *FlowsV1alpha1Client) Flows(namespace string) FlowInterface { - return newFlows(c, namespace) +func (c *NetworkingV1alpha1Client) ClusterIngresses() ClusterIngressInterface { + return newClusterIngresses(c) } -// NewForConfig creates a new FlowsV1alpha1Client for the given config. -func NewForConfig(c *rest.Config) (*FlowsV1alpha1Client, error) { +// NewForConfig creates a new NetworkingV1alpha1Client for the given config. +func NewForConfig(c *rest.Config) (*NetworkingV1alpha1Client, error) { config := *c if err := setConfigDefaults(&config); err != nil { return nil, err @@ -49,12 +46,12 @@ func NewForConfig(c *rest.Config) (*FlowsV1alpha1Client, error) { if err != nil { return nil, err } - return &FlowsV1alpha1Client{client}, nil + return &NetworkingV1alpha1Client{client}, nil } -// NewForConfigOrDie creates a new FlowsV1alpha1Client for the given config and +// NewForConfigOrDie creates a new NetworkingV1alpha1Client for the given config and // panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *FlowsV1alpha1Client { +func NewForConfigOrDie(c *rest.Config) *NetworkingV1alpha1Client { client, err := NewForConfig(c) if err != nil { panic(err) @@ -62,9 +59,9 @@ func NewForConfigOrDie(c *rest.Config) *FlowsV1alpha1Client { return client } -// New creates a new FlowsV1alpha1Client for the given RESTClient. -func New(c rest.Interface) *FlowsV1alpha1Client { - return &FlowsV1alpha1Client{c} +// New creates a new NetworkingV1alpha1Client for the given RESTClient. +func New(c rest.Interface) *NetworkingV1alpha1Client { + return &NetworkingV1alpha1Client{c} } func setConfigDefaults(config *rest.Config) error { @@ -82,7 +79,7 @@ func setConfigDefaults(config *rest.Config) error { // RESTClient returns a RESTClient that is used to communicate // with API server by this client implementation. -func (c *FlowsV1alpha1Client) RESTClient() rest.Interface { +func (c *NetworkingV1alpha1Client) RESTClient() rest.Interface { if c == nil { return nil } diff --git a/vendor/github.com/knative/serving/pkg/controller/revision/config/testdata/config-controller.yaml b/vendor/github.com/knative/serving/pkg/controller/revision/config/testdata/config-controller.yaml deleted file mode 120000 index f1afbe74ee7..00000000000 --- a/vendor/github.com/knative/serving/pkg/controller/revision/config/testdata/config-controller.yaml +++ /dev/null @@ -1 +0,0 @@ -../../../../../config/config-controller.yaml \ No newline at end of file diff --git a/vendor/github.com/knative/serving/pkg/controller/revision/config/testdata/config-network.yaml b/vendor/github.com/knative/serving/pkg/controller/revision/config/testdata/config-network.yaml deleted file mode 120000 index b774d24cbb4..00000000000 --- a/vendor/github.com/knative/serving/pkg/controller/revision/config/testdata/config-network.yaml +++ /dev/null @@ -1 +0,0 @@ -../../../../../config/config-network.yaml \ No newline at end of file diff --git a/vendor/github.com/knative/serving/pkg/controller/revision/config/testdata/config-observability.yaml b/vendor/github.com/knative/serving/pkg/controller/revision/config/testdata/config-observability.yaml deleted file mode 120000 index ecbbeaaee73..00000000000 --- a/vendor/github.com/knative/serving/pkg/controller/revision/config/testdata/config-observability.yaml +++ /dev/null @@ -1 +0,0 @@ -../../../../../config/config-observability.yaml \ No newline at end of file diff --git a/vendor/github.com/knative/serving/pkg/controller/route/config/testdata/config-domain.yaml b/vendor/github.com/knative/serving/pkg/controller/route/config/testdata/config-domain.yaml deleted file mode 120000 index fd6402b7c48..00000000000 --- a/vendor/github.com/knative/serving/pkg/controller/route/config/testdata/config-domain.yaml +++ /dev/null @@ -1 +0,0 @@ -../../../../../config/config-domain.yaml \ No newline at end of file diff --git a/vendor/github.com/knative/serving/pkg/gc/testdata/config-gc.yaml b/vendor/github.com/knative/serving/pkg/gc/testdata/config-gc.yaml new file mode 120000 index 00000000000..f6ee95a3269 --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/gc/testdata/config-gc.yaml @@ -0,0 +1 @@ +../../../config/config-gc.yaml \ No newline at end of file diff --git a/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/configuration/config/testdata/config-gc.yaml b/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/configuration/config/testdata/config-gc.yaml new file mode 120000 index 00000000000..dc98107b5c4 --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/configuration/config/testdata/config-gc.yaml @@ -0,0 +1 @@ +../../../../../../config/config-gc.yaml \ No newline at end of file diff --git a/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/revision/config/testdata/config-autoscaler.yaml b/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/revision/config/testdata/config-autoscaler.yaml new file mode 120000 index 00000000000..17e4b72c26e --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/revision/config/testdata/config-autoscaler.yaml @@ -0,0 +1 @@ +../../../../../../config/config-autoscaler.yaml \ No newline at end of file diff --git a/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/revision/config/testdata/config-controller.yaml b/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/revision/config/testdata/config-controller.yaml new file mode 120000 index 00000000000..b8047a772b9 --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/revision/config/testdata/config-controller.yaml @@ -0,0 +1 @@ +../../../../../../config/config-controller.yaml \ No newline at end of file diff --git a/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/revision/config/testdata/config-logging.yaml b/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/revision/config/testdata/config-logging.yaml new file mode 120000 index 00000000000..cd048f0179d --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/revision/config/testdata/config-logging.yaml @@ -0,0 +1 @@ +../../../../../../config/config-logging.yaml \ No newline at end of file diff --git a/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/revision/config/testdata/config-network.yaml b/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/revision/config/testdata/config-network.yaml new file mode 120000 index 00000000000..f17cdcd38ac --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/revision/config/testdata/config-network.yaml @@ -0,0 +1 @@ +../../../../../../config/config-network.yaml \ No newline at end of file diff --git a/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/revision/config/testdata/config-observability.yaml b/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/revision/config/testdata/config-observability.yaml new file mode 120000 index 00000000000..a89f2a95310 --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/revision/config/testdata/config-observability.yaml @@ -0,0 +1 @@ +../../../../../../config/config-observability.yaml \ No newline at end of file diff --git a/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/route/config/testdata/config-domain.yaml b/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/route/config/testdata/config-domain.yaml new file mode 120000 index 00000000000..41119172560 --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/route/config/testdata/config-domain.yaml @@ -0,0 +1 @@ +../../../../../../config/config-domain.yaml \ No newline at end of file diff --git a/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/route/config/testdata/config-gc.yaml b/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/route/config/testdata/config-gc.yaml new file mode 120000 index 00000000000..dc98107b5c4 --- /dev/null +++ b/vendor/github.com/knative/serving/pkg/reconciler/v1alpha1/route/config/testdata/config-gc.yaml @@ -0,0 +1 @@ +../../../../../../config/config-gc.yaml \ No newline at end of file diff --git a/vendor/github.com/knative/serving/third_party/config/monitoring/common/kubernetes/LICENSE b/vendor/github.com/knative/serving/third_party/config/monitoring/logging/elasticsearch/LICENSE similarity index 100% rename from vendor/github.com/knative/serving/third_party/config/monitoring/common/kubernetes/LICENSE rename to vendor/github.com/knative/serving/third_party/config/monitoring/logging/elasticsearch/LICENSE diff --git a/vendor/github.com/knative/serving/third_party/config/monitoring/common/istio/LICENSE b/vendor/github.com/knative/serving/third_party/config/monitoring/metrics/prometheus/istio/LICENSE similarity index 100% rename from vendor/github.com/knative/serving/third_party/config/monitoring/common/istio/LICENSE rename to vendor/github.com/knative/serving/third_party/config/monitoring/metrics/prometheus/istio/LICENSE diff --git a/vendor/github.com/knative/serving/third_party/config/monitoring/elasticsearch/LICENSE b/vendor/github.com/knative/serving/third_party/config/monitoring/metrics/prometheus/kubernetes/LICENSE similarity index 100% rename from vendor/github.com/knative/serving/third_party/config/monitoring/elasticsearch/LICENSE rename to vendor/github.com/knative/serving/third_party/config/monitoring/metrics/prometheus/kubernetes/LICENSE diff --git a/vendor/github.com/knative/serving/third_party/config/monitoring/common/prometheus-operator/LICENSE b/vendor/github.com/knative/serving/third_party/config/monitoring/metrics/prometheus/prometheus-operator/LICENSE similarity index 100% rename from vendor/github.com/knative/serving/third_party/config/monitoring/common/prometheus-operator/LICENSE rename to vendor/github.com/knative/serving/third_party/config/monitoring/metrics/prometheus/prometheus-operator/LICENSE diff --git a/vendor/github.com/knative/serving/third_party/config/monitoring/common/prometheus-operator/NOTICE b/vendor/github.com/knative/serving/third_party/config/monitoring/metrics/prometheus/prometheus-operator/NOTICE similarity index 100% rename from vendor/github.com/knative/serving/third_party/config/monitoring/common/prometheus-operator/NOTICE rename to vendor/github.com/knative/serving/third_party/config/monitoring/metrics/prometheus/prometheus-operator/NOTICE diff --git a/vendor/github.com/knative/test-infra/LICENSE b/vendor/github.com/knative/test-infra/LICENSE new file mode 100644 index 00000000000..d6456956733 --- /dev/null +++ b/vendor/github.com/knative/test-infra/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/vendor/github.com/knative/test-infra/scripts/README.md b/vendor/github.com/knative/test-infra/scripts/README.md index 5ff9ccbce21..083f2353293 100644 --- a/vendor/github.com/knative/test-infra/scripts/README.md +++ b/vendor/github.com/knative/test-infra/scripts/README.md @@ -1,3 +1,197 @@ # Helper scripts -This directory contains helper scripts used by Prow test jobs, as well and local development scripts. +This directory contains helper scripts used by Prow test jobs, as well and +local development scripts. + +## Using the `presubmit-tests.sh` helper script + +This is a helper script to run the presubmit tests. To use it: + +1. Source this script. + +1. Define the functions `build_tests()` and `unit_tests()`. They should run all +tests (i.e., not fail fast), and return 0 if all passed, 1 if a failure +occurred. The environment variables `RUN_BUILD_TESTS`, `RUN_UNIT_TESTS` and +`RUN_INTEGRATION_TESTS` are set to 0 (false) or 1 (true) accordingly. If +`--emit-metrics` is passed, `EMIT_METRICS` will be set to 1. + +1. [optional] Define the function `integration_tests()`, just like the previous +ones. If you don't define this function, the default action for running the +integration tests is to call the `./test/e2e-tests.sh` script (passing the +`--emit-metrics` flag if necessary). + +1. [optional] Define the functions `pre_integration_tests()` or +`post_integration_tests()`. These functions will be called before or after the +integration tests (either your custom one or the default action) and will cause +the test to fail if they don't return success. + +1. Call the `main()` function passing `$@` (without quotes). + +Running the script without parameters, or with the `--all-tests` flag causes +all tests to be executed, in the right order (i.e., build, then unit, then +integration tests). + +Use the flags `--build-tests`, `--unit-tests` and `--integration-tests` to run +a specific set of tests. The flag `--emit-metrics` is used to emit metrics when +running the tests, and is automatically handled by the default action (see +above). + +### Sample presubmit test script + +```bash +source vendor/github.com/knative/test-infra/scripts/presubmit-tests.sh + +function build_tests() { + go build . +} + +function unit_tests() { + report_go_test . +} + +function pre_integration_tests() { + echo "Cleaning up before integration tests" + rm -fr ./staging-area +} + +# We use the default integration test runner. + +main $@ +``` + +## Using the `e2e-tests.sh` helper script + +This is a helper script for Knative E2E test scripts. To use it: + +1. Source the script. + +1. [optional] Write the `teardown()` function, which will tear down your test +resources. + +1. [optional] Write the `dump_extra_cluster_state()` function. It will be +called when a test fails, and can dump extra information about the current state +of the cluster (tipically using `kubectl`). + +1. [optional] Write the `parse_flags()` function. It will be called whenever an +unrecognized flag is passed to the script, allowing you to define your own flags. +The function must return 0 if the flag is unrecognized, or the number of items +to skip in the command line if the flag was parsed successfully. For example, +return 1 for a simple flag, and 2 for a flag with a parameter. + +1. Call the `initialize()` function passing `$@` (without quotes). + +1. Write logic for the end-to-end tests. Run all go tests using `go_test_e2e()` +(or `report_go_test()` if you need a more fine-grained control) and call +`fail_test()` or `success()` if any of them failed. The environment variables +`DOCKER_REPO_OVERRIDE`, `K8S_CLUSTER_OVERRIDE` and `K8S_USER_OVERRIDE` will be set +according to the test cluster. You can also use the following boolean (0 is false, +1 is true) environment variables for the logic: + * `EMIT_METRICS`: true if `--emit-metrics` was passed. + * `USING_EXISTING_CLUSTER`: true if the test cluster is an already existing one, +and not a temporary cluster created by `kubetest`. + + All environment variables above are marked read-only. + +**Notes:** + +1. Calling your script without arguments will create a new cluster in the GCP +project `$PROJECT_ID` and run the tests against it. + +1. Calling your script with `--run-tests` and the variables `K8S_CLUSTER_OVERRIDE`, +`K8S_USER_OVERRIDE` and `DOCKER_REPO_OVERRIDE` set will immediately start the +tests against the cluster. + +### Sample end-to-end test script + +This script will test that the latest Knative Serving nightly release works. It +defines a special flag (`--no-knative-wait`) that causes the script not to +wait for Knative Serving to be up before running the tests. + +```bash +source vendor/github.com/knative/test-infra/scripts/e2e-tests.sh + +function teardown() { + echo "TODO: tear down test resources" +} + +function parse_flags() { + if [[ "$1" == "--no-knative-wait" ]]; then + WAIT_FOR_KNATIVE=0 + return 1 + fi + return 0 +} + +WAIT_FOR_KNATIVE=1 + +initialize $@ + +start_latest_knative_serving + +if (( WAIT_FOR_KNATIVE )); then + wait_until_pods_running knative-serving || fail_test "Knative Serving is not up" +fi + +# TODO: use go_test_e2e to run the tests. +kubectl get pods || fail_test + +success +``` + +## Using the `release.sh` helper script + +This is a helper script for Knative release scripts. To use it: + +1. Source the script. + +1. Call the `initialize()` function passing `$@` (without quotes). + +1. Call the `run_validation_tests()` function passing the script or executable that +runs the release validation tests. It will call the script to run the tests unless +`--skip_tests` was passed. + +1. Write logic for the release process. Call `publish_yaml()` to publish the manifest(s), +`tag_releases_in_yaml()` to tag the generated images, `branch_release()` to branch +named releases. Use the following boolean (0 is false, 1 is true) and string environment +variables for the logic: + * `RELEASE_VERSION`: contains the release version if `--version` was passed. This +also overrides the value of the `TAG` variable as `v`. + * `RELEASE_BRANCH`: contains the release branch if `--branch` was passed. Otherwise +it's empty and `master` HEAD will be considered the release branch. + * `RELEASE_NOTES`: contains the filename with the release notes if `--release-notes` +was passed. The release notes is a simple markdown file. + * `SKIP_TESTS`: true if `--skip-tests` was passed. This is handled automatically +by the run_validation_tests() function. + * `TAG_RELEASE`: true if `--tag-release` was passed. In this case, the environment +variable `TAG` will contain the release tag in the form `vYYYYMMDD-`. + * `PUBLISH_RELEASE`: true if `--publish` was passed. In this case, the environment +variable `KO_FLAGS` will be updated with the `-L` option. + * `BRANCH_RELEASE`: true if both `--version` and `--publish-release` were passed. + + All boolean environment variables default to false for safety. + + All environment variables above, except `KO_FLAGS`, are marked read-only once +`initialize()` is called. + +### Sample release script + +```bash +source vendor/github.com/knative/test-infra/scripts/release.sh + +initialize $@ + +run_validation_tests ./test/presubmit-tests.sh + +# config/ contains the manifests +KO_DOCKER_REPO=gcr.io/knative-foo +ko resolve ${KO_FLAGS} -f config/ > release.yaml + +tag_images_in_yaml release.yaml $KO_DOCKER_REPO $TAG + +if (( PUBLISH_RELEASE )); then + # gs://knative-foo hosts the manifest + publish_yaml release.yaml knative-foo $TAG +fi + +branch_release "Knative Foo" release.yaml +``` diff --git a/pkg/apis/eventing/v1alpha1/source_defaults_test.go b/vendor/github.com/knative/test-infra/scripts/dummy.go similarity index 65% rename from pkg/apis/eventing/v1alpha1/source_defaults_test.go rename to vendor/github.com/knative/test-infra/scripts/dummy.go index 2373f9a70c8..e6cc380fd7b 100644 --- a/pkg/apis/eventing/v1alpha1/source_defaults_test.go +++ b/vendor/github.com/knative/test-infra/scripts/dummy.go @@ -5,7 +5,7 @@ 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 + https://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, @@ -14,14 +14,13 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1alpha1 +package scripts import ( - "testing" + "fmt" ) -// No-op test because method does nothing. -func TestSourceSetDefaults(t *testing.T) { - s := Source{} - s.SetDefaults() +func main() { + fmt.Println("This is a dummy go file so `go dep` can be used with knative/test-infra/scripts") + fmt.Println("This file can be safely removed if one day this directory contains real, useful go code") } diff --git a/vendor/github.com/knative/test-infra/scripts/e2e-tests.sh b/vendor/github.com/knative/test-infra/scripts/e2e-tests.sh index 7c921048254..e276b7ba117 100755 --- a/vendor/github.com/knative/test-infra/scripts/e2e-tests.sh +++ b/vendor/github.com/knative/test-infra/scripts/e2e-tests.sh @@ -14,29 +14,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -# This is a helper script for Knative E2E test scripts. To use it: -# 1. Source this script. -# 2. [optional] Write the teardown() function, which will tear down your test -# resources. -# 3. [optional] Write the dump_extra_cluster_state() function. It will be called -# when a test fails, and can dump extra information about the current state of -# the cluster (tipically using kubectl). -# 4. Call the initialize() function passing $@ (without quotes). -# 5. Write logic for the end-to-end tests. Run all go tests using report_go_test() -# and call fail_test() or success() if any of them failed. The envitronment -# variables DOCKER_REPO_OVERRIDE, K8S_CLUSTER_OVERRIDE and K8S_USER_OVERRIDE -# will be set accordingly to the test cluster. You can also use the following -# boolean (0 is false, 1 is true) environment variables for the logic: -# EMIT_METRICS: true if --emit-metrics is passed. -# USING_EXISTING_CLUSTER: true if the test cluster is an already existing one, -# and not a temporary cluster created by kubetest. -# All environment variables above are marked read-only. -# Notes: -# 1. Calling your script without arguments will create a new cluster in the GCP -# project $PROJECT_ID and run the tests against it. -# 2. Calling your script with --run-tests and the variables K8S_CLUSTER_OVERRIDE, -# K8S_USER_OVERRIDE and DOCKER_REPO_OVERRIDE set will immediately start the -# tests against the cluster. +# This is a helper script for Knative E2E test scripts. +# See README.md for instructions on how to use it. source $(dirname ${BASH_SOURCE})/library.sh @@ -51,7 +30,9 @@ function build_resource_name() { if [[ -n "${suffix}" ]]; then suffix=${suffix:${#suffix}<20?0:-20} fi - echo "${prefix:0:20}${suffix}" + local name="${prefix:0:20}${suffix}" + # Ensure name doesn't end with "-" + echo "${name%-}" } # Test cluster parameters @@ -68,7 +49,7 @@ readonly TEST_RESULT_FILE=/tmp/${E2E_BASE_NAME}-e2e-result function teardown_test_resources() { header "Tearing down test environment" # Free resources in GCP project. - if (( ! USING_EXISTING_CLUSTER )) && [[ "$(type -t teardown)" == "function" ]]; then + if (( ! USING_EXISTING_CLUSTER )) && function_exists teardown; then teardown fi @@ -91,6 +72,16 @@ function fail_test() { exit 1 } +# Run the given E2E tests. Assume tests are tagged e2e, unless `-tags=XXX` is passed. +# Parameters: $1..$n - any go test flags, then directories containing the tests to run. +function go_test_e2e() { + local test_options="" + local go_options="" + (( EMIT_METRICS )) && test_options="-emitmetrics" + [[ ! " $@" == *" -tags="* ]] && go_options="-tags=e2e" + report_go_test -v -count=1 ${go_options} $@ ${test_options} +} + # Download the k8s binaries required by kubetest. function download_k8s() { local version=${SERVING_GKE_VERSION} @@ -143,7 +134,7 @@ function dump_cluster_state() { kubectl get services --all-namespaces echo ">>> Events:" kubectl get events --all-namespaces - [[ "$(type -t dump_extra_cluster_state)" == "function" ]] && dump_extra_cluster_state + function_exists dump_extra_cluster_state && dump_extra_cluster_state echo "***************************************" echo "*** TEST FAILED ***" echo "*** End of information dump ***" @@ -195,7 +186,8 @@ function create_test_cluster() { # Don't fail test for kubetest, as it might incorrectly report test failure # if teardown fails (for details, see success() below) set +o errexit - kubetest "${CLUSTER_CREATION_ARGS[@]}" \ + run_go_tool k8s.io/test-infra/kubetest \ + kubetest "${CLUSTER_CREATION_ARGS[@]}" \ --up \ --down \ --extract local \ @@ -259,7 +251,7 @@ function setup_test_cluster() { trap teardown_test_resources EXIT - if (( USING_EXISTING_CLUSTER )) && [[ "$(type -t teardown)" == "function" ]]; then + if (( USING_EXISTING_CLUSTER )) && function_exists teardown; then echo "Deleting any previous SUT instance" teardown fi @@ -300,7 +292,19 @@ function initialize() { readonly E2E_SCRIPT cd ${REPO_ROOT_DIR} - for parameter in $@; do + while [[ $# -ne 0 ]]; do + local parameter=$1 + # Try parsing flag as a custom one. + if function_exists parse_flags; then + parse_flags $@ + local skip=$? + if [[ ${skip} -ne 0 ]]; then + # Skip parsed flag (and possibly argument) and continue + shift ${skip} + continue + fi + fi + # Try parsing flag as a standard one. case $parameter in --run-tests) RUN_TESTS=1 ;; --emit-metrics) EMIT_METRICS=1 ;; diff --git a/vendor/github.com/knative/test-infra/scripts/library.sh b/vendor/github.com/knative/test-infra/scripts/library.sh index a330f4dbc3d..95acac29a58 100755 --- a/vendor/github.com/knative/test-infra/scripts/library.sh +++ b/vendor/github.com/knative/test-infra/scripts/library.sh @@ -23,6 +23,7 @@ readonly SERVING_GKE_VERSION=latest readonly SERVING_GKE_IMAGE=cos # Public images and yaml files. +readonly KNATIVE_ISTIO_CRD_YAML=https://storage.googleapis.com/knative-releases/serving/latest/istio-crds.yaml readonly KNATIVE_ISTIO_YAML=https://storage.googleapis.com/knative-releases/serving/latest/istio.yaml readonly KNATIVE_SERVING_RELEASE=https://storage.googleapis.com/knative-releases/serving/latest/release.yaml readonly KNATIVE_BUILD_RELEASE=https://storage.googleapis.com/knative-releases/build/latest/release.yaml @@ -66,6 +67,11 @@ function warning() { make_banner "!" "$1" } +# Checks whether the given function exists. +function function_exists() { + [[ "$(type -t $1)" == "function" ]] +} + # Remove ALL images in the given GCR repository. # Parameters: $1 - GCR repository. function delete_gcr_images() { @@ -94,7 +100,7 @@ function wait_until_object_does_not_exist() { fi echo -n "Waiting until ${DESCRIPTION} does not exist" for i in {1..150}; do # timeout after 5 minutes - kubectl ${KUBECTL_ARGS} 2>&1 > /dev/null || return 0 + kubectl ${KUBECTL_ARGS} > /dev/null 2>&1 || return 0 echo -n "." sleep 2 done @@ -172,7 +178,7 @@ function wait_until_routable() { return 1 } -# Returns the name of the pod of the given app. +# Returns the name of the first pod of the given app. # Parameters: $1 - app name. # $2 - namespace (optional). function get_app_pod() { @@ -181,6 +187,15 @@ function get_app_pod() { kubectl get pods ${namespace} --selector=app=$1 --output=jsonpath="{.items[0].metadata.name}" } +# Returns the name of all pods of the given app. +# Parameters: $1 - app name. +# $2 - namespace (optional). +function get_app_pods() { + local namespace="" + [[ -n $2 ]] && namespace="-n $2" + kubectl get pods ${namespace} --selector=app=$1 --output=jsonpath="{.items[*].metadata.name}" +} + # Sets the given user as cluster admin. # Parameters: $1 - user # $2 - cluster name @@ -235,9 +250,11 @@ function report_go_test() { echo "Finished run, return code is ${failed}" # Tests didn't run. [[ ! -s ${report} ]] && return 1 - # Create WORKSPACE file, required to use bazel + # Create WORKSPACE file, required to use bazel, if necessary. touch WORKSPACE local targets="" + local last_run="" + local test_files="" # Parse the report and generate fake tests for each passing/failing test. echo "Start parsing results, summary:" while read line ; do @@ -245,16 +262,35 @@ function report_go_test() { local field0="${fields[0]}" local field1="${fields[1]}" local name="${fields[2]}" + # Deal with a SIGQUIT log entry (usually a test timeout). + # This is a fallback in case there's no kill signal log entry. + # SIGQUIT: quit + if [[ "${field0}" == "SIGQUIT:" ]]; then + name="${last_run}" + field1="FAIL:" + error="${fields[@]}" + fi # Ignore subtests (those containing slashes) if [[ -n "${name##*/*}" ]]; then local error="" + # Deal with a kill signal log entry (usually a test timeout). + # *** Test killed with quit: ran too long (10m0s). + if [[ "${field0}" == "***" ]]; then + name="${last_run}" + field1="FAIL:" + error="${fields[@]:1}" + fi # Deal with a fatal log entry, which has a different format: # fatal TestFoo foo_test.go:275 Expected "foo" but got "bar" if [[ "${field0}" == "fatal" ]]; then - name="${fields[1]}" + name="${field1}" field1="FAIL:" error="${fields[@]:3}" fi + # Keep track of the test currently running. + if [[ "${field1}" == "RUN" ]]; then + last_run="${name}" + fi # Handle regular go test pass/fail entry for a test. if [[ "${field1}" == "PASS:" || "${field1}" == "FAIL:" ]]; then echo "- ${name} :${field1}" @@ -269,13 +305,14 @@ function report_go_test() { echo "exit 1" >> ${src} fi chmod +x ${src} + test_files="${test_files} ${src}" # Populate BUILD.bazel echo "sh_test(name=\"${name}\", srcs=[\"${src}\"])" >> BUILD.bazel elif [[ "${field0}" == "FAIL" || "${field0}" == "ok" ]] && [[ -n "${field1}" ]]; then echo "- ${field0} ${field1}" # Create the package structure, move tests and BUILD file local package=${field1/github.com\//} - local bazel_files="$(ls -1 *.sh BUILD.bazel 2> /dev/null)" + local bazel_files="$(ls -1 ${test_files} BUILD.bazel 2> /dev/null)" if [[ -n "${bazel_files}" ]]; then mkdir -p ${package} targets="${targets} //${package}/..." @@ -283,6 +320,7 @@ function report_go_test() { else echo "*** INTERNAL ERROR: missing tests for ${package}, got [${bazel_files/$'\n'/, }]" fi + test_files="" fi fi done < ${report} @@ -291,11 +329,15 @@ function report_go_test() { # Otherwise, we already shown the summary. # Exception: when emitting metrics, dump the full report. if (( failed )) || [[ "$@" == *" -emitmetrics"* ]]; then - echo "At least one test failed, full log:" + if (( failed )); then + echo "At least one test failed, full log:" + else + echo "Dumping full log as metrics were requested:" + fi cat ${report} fi # Always generate the junit summary. - bazel test ${targets} > /dev/null 2>&1 + bazel test ${targets} > /dev/null 2>&1 || true return ${failed} } @@ -303,6 +345,7 @@ function report_go_test() { function start_latest_knative_serving() { header "Starting Knative Serving" subheader "Installing Istio" + kubectl apply -f ${KNATIVE_ISTIO_CRD_YAML} || return 1 kubectl apply -f ${KNATIVE_ISTIO_YAML} || return 1 wait_until_pods_running istio-system || return 1 kubectl label namespace default istio-injection=enabled || return 1 @@ -323,14 +366,19 @@ function start_latest_knative_build() { wait_until_pods_running knative-build || return 1 } -# Run dep-collector, installing it first if necessary. -# Parameters: $1..$n - parameters passed to dep-collector. -function run_dep_collector() { - local local_dep_collector="$(which dep-collector)" - if [[ -z ${local_dep_collector} ]]; then - go get -u github.com/mattmoor/dep-collector +# Run a go tool, installing it first if necessary. +# Parameters: $1 - tool package/dir for go get/install. +# $2 - tool to run. +# $3..$n - parameters passed to the tool. +function run_go_tool() { + local tool=$2 + if [[ -z "$(which ${tool})" ]]; then + local action=get + [[ $1 =~ ^[\./].* ]] && action=install + go ${action} $1 fi - dep-collector $@ + shift 2 + ${tool} "$@" } # Run dep-collector to update licenses. @@ -340,7 +388,7 @@ function update_licenses() { cd ${REPO_ROOT_DIR} || return 1 local dst=$1 shift - run_dep_collector $@ > ./${dst} + run_go_tool ./vendor/github.com/knative/test-infra/tools/dep-collector dep-collector $@ > ./${dst} } # Run dep-collector to check for forbidden liceses. @@ -349,7 +397,7 @@ function check_licenses() { # Fetch the google/licenseclassifier for its license db go get -u github.com/google/licenseclassifier # Check that we don't have any forbidden licenses in our images. - run_dep_collector -check $@ + run_go_tool ./vendor/github.com/knative/test-infra/tools/dep-collector dep-collector -check $@ } # Run the given linter on the given files, checking it exists first. diff --git a/vendor/github.com/knative/test-infra/scripts/presubmit-tests.sh b/vendor/github.com/knative/test-infra/scripts/presubmit-tests.sh index b6116817ca6..db78f3d0ca1 100755 --- a/vendor/github.com/knative/test-infra/scripts/presubmit-tests.sh +++ b/vendor/github.com/knative/test-infra/scripts/presubmit-tests.sh @@ -14,21 +14,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -# This is a helper script to run the presubmit tests. To use it: -# 1. Source this script. -# 2. Define the functions build_tests(), unit_tests() and -# integration_tests(). They should run all tests (i.e., not fail -# fast), and return 0 if all passed, 1 if a failure occurred. -# The environment variables RUN_BUILD_TESTS, RUN_UNIT_TESTS and -# RUN_INTEGRATION_TESTS are set to 0 (false) or 1 (true) accordingly. -# If --emit-metrics is passed, EMIT_METRICS will be set to 1. -# 3. Call the main() function passing $@ (without quotes). -# -# Running the script without parameters, or with the --all-tests -# flag, causes all tests to be executed, in the right order. -# Use the flags --build-tests, --unit-tests and --integration-tests -# to run a specific set of tests. The flag --emit-metrics is used -# to emit metrics when running the tests. +# This is a helper script for Knative presubmit test scripts. +# See README.md for instructions on how to use it. source $(dirname ${BASH_SOURCE})/library.sh @@ -65,6 +52,19 @@ function exit_if_presubmit_not_required() { function main() { exit_if_presubmit_not_required + # Show the version of the tools we're using + if (( IS_PROW )); then + # Disable gcloud update notifications + gcloud config set component_manager/disable_update_check true + header "Current test setup" + echo ">> gcloud SDK version" + gcloud version + echo ">> kubectl version" + kubectl version + echo ">> go version" + go version + fi + local all_parameters=$@ [[ -z $1 ]] && all_parameters="--all-tests" @@ -108,15 +108,29 @@ function main() { # Tests to be performed, in the right order if --all-tests is passed. - local result=0 + local failed=0 if (( RUN_BUILD_TESTS )); then - build_tests || result=1 + build_tests || failed=1 fi if (( RUN_UNIT_TESTS )); then - unit_tests || result=1 + unit_tests || failed=1 fi if (( RUN_INTEGRATION_TESTS )); then - integration_tests || result=1 + if function_exists pre_integration_tests; then + pre_integration_tests || failed=1 + fi + if (( ! failed )); then + if function_exists integration_tests; then + integration_tests || failed=1 + else + local options="" + (( EMIT_METRICS )) && options="--emit-metrics" + ./test/e2e-tests.sh ${options} || failed=1 + fi + fi + if (( ! failed )) && function_exists post_integration_tests; then + post_integration_tests || failed=1 + fi fi - exit ${result} + exit ${failed} } diff --git a/vendor/github.com/knative/test-infra/scripts/release.sh b/vendor/github.com/knative/test-infra/scripts/release.sh index abf89ddf418..3e41bdda9d1 100755 --- a/vendor/github.com/knative/test-infra/scripts/release.sh +++ b/vendor/github.com/knative/test-infra/scripts/release.sh @@ -14,27 +14,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -# This is a helper script for Knative release scripts. To use it: -# 1. Source this script. -# 2. Call the parse_flags() function passing $@ (without quotes). -# 3. Call the run_validation_tests() passing the script or executable that -# runs the release validation tests. -# 4. Write logic for the release process. Use the following boolean (0 is -# false, 1 is true) environment variables for the logic: -# SKIP_TESTS: true if --skip-tests is passed. This is handled automatically -# by the run_validation_tests() function. -# TAG_RELEASE: true if --tag-release is passed. In this case, the -# environment variable TAG will contain the release tag in the -# form vYYYYMMDD-. -# PUBLISH_RELEASE: true if --publish is passed. In this case, the environment -# variable KO_FLAGS will be updated with the -L option. -# SKIP_TESTS, TAG_RELEASE and PUBLISH_RELEASE default to false for safety. -# All environment variables above, except KO_FLAGS, are marked read-only once -# parse_flags() is called. +# This is a helper script for Knative release scripts. +# See README.md for instructions on how to use it. source $(dirname ${BASH_SOURCE})/library.sh # Simple banner for logging purposes. +# Parameters: $1 - message to display. function banner() { make_banner "@" "$1" } @@ -57,43 +43,70 @@ function tag_images_in_yaml() { # $3 - tag to apply (optional). function publish_yaml() { gsutil cp $1 gs://$2/latest/ - [[ -n $3 ]] && gsutil cp $1 gs://$2/previous/$3/ + [[ -n $3 ]] && gsutil cp $1 gs://$2/previous/$3/ || true } +# These are global environment variables. SKIP_TESTS=0 TAG_RELEASE=0 PUBLISH_RELEASE=0 +BRANCH_RELEASE=0 TAG="" -KO_FLAGS="-P -L" +RELEASE_VERSION="" +RELEASE_NOTES="" +RELEASE_BRANCH="" +KO_FLAGS="" + +function abort() { + echo "error: $@" + exit 1 +} # Parses flags and sets environment variables accordingly. function parse_flags() { + TAG="" + RELEASE_VERSION="" + RELEASE_NOTES="" + RELEASE_BRANCH="" + KO_FLAGS="-P" cd ${REPO_ROOT_DIR} - for parameter in $@; do + while [[ $# -ne 0 ]]; do + local parameter=$1 case $parameter in --skip-tests) SKIP_TESTS=1 ;; --tag-release) TAG_RELEASE=1 ;; --notag-release) TAG_RELEASE=0 ;; - --publish) - PUBLISH_RELEASE=1 - # Remove -L from ko flags - KO_FLAGS="${KO_FLAGS/-L}" + --publish) PUBLISH_RELEASE=1 ;; + --nopublish) PUBLISH_RELEASE=0 ;; + --version) + shift + [[ $# -ge 1 ]] || abort "missing version after --version" + [[ $1 =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || abort "version format must be '[0-9].[0-9].[0-9]'" + RELEASE_VERSION=$1 ;; - --nopublish) - PUBLISH_RELEASE=0 - # Add -L to ko flags - KO_FLAGS="-L ${KO_FLAGS}" + --branch) shift + [[ $# -ge 1 ]] || abort "missing branch after --commit" + [[ $1 =~ ^release-[0-9]+\.[0-9]+$ ]] || abort "branch name must be 'release-[0-9].[0-9]'" + RELEASE_BRANCH=$1 ;; - *) - echo "error: unknown option ${parameter}" - exit 1 + --release-notes) + shift + [[ $# -ge 1 ]] || abort "missing release notes file after --release-notes" + [[ ! -f "$1" ]] && abort "file $1 doesn't exist" + RELEASE_NOTES=$1 ;; + *) abort "unknown option ${parameter}" ;; esac shift done - TAG="" + # Update KO_DOCKER_REPO and KO_FLAGS if we're not publishing. + if (( ! PUBLISH_RELEASE )); then + KO_DOCKER_REPO="ko.local" + KO_FLAGS="-L ${KO_FLAGS}" + fi + if (( TAG_RELEASE )); then # Currently we're not considering the tags in refs/tags namespace. commit=$(git describe --always --dirty) @@ -101,10 +114,20 @@ function parse_flags() { TAG="v$(date +%Y%m%d)-${commit}" fi + if [[ -n "${RELEASE_VERSION}" ]]; then + TAG="v${RELEASE_VERSION}" + fi + + [[ -n "${RELEASE_VERSION}" ]] && (( PUBLISH_RELEASE )) && BRANCH_RELEASE=1 + readonly SKIP_TESTS readonly TAG_RELEASE readonly PUBLISH_RELEASE + readonly BRANCH_RELEASE readonly TAG + readonly RELEASE_VERSION + readonly RELEASE_NOTES + readonly RELEASE_BRANCH } # Run tests (unless --skip-tests was passed). Conveniently displays a banner indicating so. @@ -113,6 +136,46 @@ function run_validation_tests() { if (( ! SKIP_TESTS )); then banner "Running release validation tests" # Run tests. - $1 + if ! $1; then + banner "Release validation tests failed, aborting" + exit 1 + fi + fi +} + +# Initialize everything (flags, workspace, etc) for a release. +function initialize() { + parse_flags $@ + # Checkout specific branch, if necessary + if (( BRANCH_RELEASE )); then + git checkout upstream/${RELEASE_BRANCH} || abort "cannot checkout branch ${RELEASE_BRANCH}" + fi +} + +# Create a new release on GitHub, also git tagging it (unless this is not a versioned release). +# Parameters: $1 - Module name (e.g., "Knative Serving"). +# $2 - YAML files to add to the release, space separated. +function branch_release() { + (( BRANCH_RELEASE )) || return 0 + local title="$1 release ${TAG}" + local attachments=() + local description="$(mktemp)" + local attachments_dir="$(mktemp -d)" + # Copy each YAML to a separate dir + for yaml in $2; do + cp ${yaml} ${attachments_dir}/ + attachments+=("--attach=${yaml}#$(basename ${yaml})") + done + echo -e "${title}\n" > ${description} + if [[ -n "${RELEASE_NOTES}" ]]; then + cat ${RELEASE_NOTES} >> ${description} fi + git tag -a ${TAG} -m "${title}" + git push $(git remote get-url upstream) tag ${TAG} + run_go_tool github.com/github/hub hub release create \ + --prerelease \ + ${attachments[@]} \ + --file=${description} \ + --commitish=${RELEASE_BRANCH} \ + ${TAG} } diff --git a/vendor/github.com/knative/test-infra/tools/dep-collector/README.md b/vendor/github.com/knative/test-infra/tools/dep-collector/README.md new file mode 100644 index 00000000000..9acf6cef809 --- /dev/null +++ b/vendor/github.com/knative/test-infra/tools/dep-collector/README.md @@ -0,0 +1,88 @@ +# dep-collector + +`dep-collector` is a tool for gathering up a collection of licenses for Go +dependencies that have been pulled into the idiomatic `vendor/` directory. +The resulting file from running `dep-collector` is intended for inclusion +in container images to respect the licenses of the included software. + +### Basic Usage + +You can run `dep-collector` on one or more Go import paths as entrypoints, +and it will: +1. Walk the transitive dependencies to identify vendored software packages, +1. Search for licenses for each vendored dependency, +1. Dump a file containing the licenses for each vendored import. + +For example (single import path): +```shell +$ dep-collector . +=========================================================== +Import: github.com/mattmoor/dep-collector/vendor/github.com/google/licenseclassifier + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ +... + +``` + +For example (multiple import paths): + +```shell +$ dep-collector ./cmd/controller ./cmd/sleeper + +=========================================================== +Import: github.com/mattmoor/warm-image/vendor/cloud.google.com/go + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ +``` + +### CSV Usage + +You can also run `dep-collector` in a mode that produces CSV output, +including basic classification of the license. + +> In order to run dep-collector in this mode, you must first run: +> go get github.com/google/licenseclassifier + +For example: + +```shell +$ dep-collector -csv . +github.com/google/licenseclassifier,Static,,https://github.com/mattmoor/dep-collector/blob/master/vendor/github.com/google/licenseclassifier/LICENSE,Apache-2.0 +github.com/google/licenseclassifier/stringclassifier,Static,,https://github.com/mattmoor/dep-collector/blob/master/vendor/github.com/google/licenseclassifier/stringclassifier/LICENSE,Apache-2.0 +github.com/sergi/go-diff,Static,,https://github.com/mattmoor/dep-collector/blob/master/vendor/github.com/sergi/go-diff/LICENSE,MIT + +``` + +The columns here are: +* Import Path, +* How the dependency is linked in (always reports "static"), +* A column for whether any modifications have been made (always empty), +* The URL by which to access the license file (assumes `master`), +* A classification of what license this is ([using this](https://github.com/google/licenseclassifier)). + + +### Check mode + +`dep-collector` also includes a mode that will check for "forbidden" licenses. + +> In order to run dep-collector in this mode, you must first run: +> go get github.com/google/licenseclassifier + +For example (failing): +```shell +$ dep-collector -check ./foo/bar/baz +2018/07/20 22:01:29 Error checking license collection: Errors validating licenses: +Found matching forbidden license in "foo.io/bar/vendor/github.com/BurntSushi/toml": WTFPL +``` + +For example (passing): + +```shell +$ dep-collector -check . +2018/07/20 22:29:09 No errors found. +``` diff --git a/vendor/github.com/knative/test-infra/tools/dep-collector/imports.go b/vendor/github.com/knative/test-infra/tools/dep-collector/imports.go new file mode 100644 index 00000000000..924ce410228 --- /dev/null +++ b/vendor/github.com/knative/test-infra/tools/dep-collector/imports.go @@ -0,0 +1,94 @@ +/* +Copyright 2018 The Knative 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 main + +import ( + "fmt" + gb "go/build" + "path/filepath" + "sort" + "strings" +) + +func CollectTransitiveImports(binaries []string) ([]string, error) { + // Perform a simple DFS to collect the binaries' transitive dependencies. + visited := make(map[string]struct{}) + for _, importpath := range binaries { + if gb.IsLocalImport(importpath) { + ip, err := qualifyLocalImport(importpath) + if err != nil { + return nil, err + } + importpath = ip + } + + pkg, err := gb.Import(importpath, WorkingDir, gb.ImportComment) + if err != nil { + return nil, err + } + if err := visit(pkg, visited); err != nil { + return nil, err + } + } + + // Sort the dependencies deterministically. + var list sort.StringSlice + for ip := range visited { + if !strings.Contains(ip, "/vendor/") { + // Skip files outside of vendor + continue + } + list = append(list, ip) + } + list.Sort() + + return list, nil +} + +func qualifyLocalImport(ip string) (string, error) { + gopathsrc := filepath.Join(gb.Default.GOPATH, "src") + if !strings.HasPrefix(WorkingDir, gopathsrc) { + return "", fmt.Errorf("working directory must be on ${GOPATH}/src = ", gopathsrc) + } + return filepath.Join(strings.TrimPrefix(WorkingDir, gopathsrc+string(filepath.Separator)), ip), nil +} + +func visit(pkg *gb.Package, visited map[string]struct{}) error { + if _, ok := visited[pkg.ImportPath]; ok { + return nil + } + visited[pkg.ImportPath] = struct{}{} + + for _, ip := range pkg.Imports { + if ip == "C" { + // skip cgo + continue + } + subpkg, err := gb.Import(ip, WorkingDir, gb.ImportComment) + if err != nil { + return fmt.Errorf("%v\n -> %v", pkg.ImportPath, err) + } + if !strings.HasPrefix(subpkg.Dir, WorkingDir) { + // Skip import paths outside of our workspace (std library) + continue + } + if err := visit(subpkg, visited); err != nil { + return fmt.Errorf("%v (%v)\n -> %v", pkg.ImportPath, pkg.Dir, err) + } + } + return nil +} diff --git a/vendor/github.com/knative/test-infra/tools/dep-collector/licenses.go b/vendor/github.com/knative/test-infra/tools/dep-collector/licenses.go new file mode 100644 index 00000000000..cb1df9ab748 --- /dev/null +++ b/vendor/github.com/knative/test-infra/tools/dep-collector/licenses.go @@ -0,0 +1,203 @@ +/* +Copyright 2018 The Knative 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 main + +import ( + "fmt" + gb "go/build" + "io/ioutil" + "os" + "path/filepath" + "sort" + "strings" + + "github.com/google/licenseclassifier" +) + +var LicenseNames = []string{ + "LICENCE", + "LICENSE", + "LICENSE.code", + "LICENSE.md", + "LICENSE.txt", + "COPYING", + "copyright", +} + +const MatchThreshold = 0.9 + +type LicenseFile struct { + EnclosingImportPath string + LicensePath string +} + +func (lf *LicenseFile) Body() (string, error) { + body, err := ioutil.ReadFile(lf.LicensePath) + if err != nil { + return "", err + } + return string(body), nil +} + +func (lt *LicenseFile) Classify(classifier *licenseclassifier.License) (string, error) { + body, err := lt.Body() + if err != nil { + return "", err + } + m := classifier.NearestMatch(body) + if m == nil { + return "", fmt.Errorf("unable to classify license: %v", lt.EnclosingImportPath) + } + return m.Name, nil +} + +func (lt *LicenseFile) Check(classifier *licenseclassifier.License) error { + body, err := lt.Body() + if err != nil { + return err + } + ms := classifier.MultipleMatch(body, false) + for _, m := range ms { + return fmt.Errorf("Found matching forbidden license in %q: %v", lt.EnclosingImportPath, m.Name) + } + return nil +} + +func (lt *LicenseFile) Entry() (string, error) { + body, err := lt.Body() + if err != nil { + return "", err + } + return fmt.Sprintf(` +=========================================================== +Import: %s + +%s +`, lt.EnclosingImportPath, body), nil +} + +func (lt *LicenseFile) CSVRow(classifier *licenseclassifier.License) (string, error) { + classification, err := lt.Classify(classifier) + if err != nil { + return "", err + } + parts := strings.Split(lt.EnclosingImportPath, "/vendor/") + if len(parts) != 2 { + return "", fmt.Errorf("wrong number of parts splitting import path on %q : %q", "/vendor/", lt.EnclosingImportPath) + } + return strings.Join([]string{ + parts[1], + "Static", + "", // TODO(mattmoor): Modifications? + "https://" + parts[0] + "/blob/master/vendor/" + parts[1] + "/" + filepath.Base(lt.LicensePath), + classification, + }, ","), nil +} + +func findLicense(ip string) (*LicenseFile, error) { + pkg, err := gb.Import(ip, WorkingDir, gb.ImportComment) + if err != nil { + return nil, err + } + dir := pkg.Dir + + for { + // When we reach the root of our workspace, stop searching. + if dir == WorkingDir { + return nil, fmt.Errorf("unable to find license for %q", pkg.ImportPath) + } + + for _, name := range LicenseNames { + p := filepath.Join(dir, name) + if _, err := os.Stat(p); err != nil { + continue + } + + return &LicenseFile{ + EnclosingImportPath: ip, + LicensePath: p, + }, nil + } + + // Walk to the parent directory / import path + dir = filepath.Dir(dir) + ip = filepath.Dir(ip) + } +} + +type LicenseCollection []*LicenseFile + +func (lc LicenseCollection) Entries() (string, error) { + sections := make([]string, 0, len(lc)) + for _, key := range lc { + entry, err := key.Entry() + if err != nil { + return "", err + } + sections = append(sections, entry) + } + return strings.Join(sections, "\n"), nil +} + +func (lc LicenseCollection) CSV(classifier *licenseclassifier.License) (string, error) { + sections := make([]string, 0, len(lc)) + for _, entry := range lc { + row, err := entry.CSVRow(classifier) + if err != nil { + return "", err + } + sections = append(sections, row) + } + return strings.Join(sections, "\n"), nil +} + +func (lc LicenseCollection) Check(classifier *licenseclassifier.License) error { + errors := []string{} + for _, entry := range lc { + if err := entry.Check(classifier); err != nil { + errors = append(errors, err.Error()) + } + } + if len(errors) == 0 { + return nil + } + return fmt.Errorf("Errors validating licenses:\n%v", strings.Join(errors, "\n")) +} + +func CollectLicenses(imports []string) (LicenseCollection, error) { + // for each of the import paths, search for a license file. + licenseFiles := make(map[string]*LicenseFile) + for _, ip := range imports { + lf, err := findLicense(ip) + if err != nil { + return nil, err + } + licenseFiles[lf.EnclosingImportPath] = lf + } + + order := sort.StringSlice{} + for key := range licenseFiles { + order = append(order, key) + } + order.Sort() + + licenseTypes := LicenseCollection{} + for _, key := range order { + licenseTypes = append(licenseTypes, licenseFiles[key]) + } + return licenseTypes, nil +} diff --git a/vendor/github.com/knative/test-infra/tools/dep-collector/main.go b/vendor/github.com/knative/test-infra/tools/dep-collector/main.go new file mode 100644 index 00000000000..4532942751d --- /dev/null +++ b/vendor/github.com/knative/test-infra/tools/dep-collector/main.go @@ -0,0 +1,81 @@ +/* +Copyright 2018 The Knative 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 main + +import ( + "flag" + "log" + "os" + + "github.com/google/licenseclassifier" +) + +var WorkingDir, _ = os.Getwd() + +var ( + csv = flag.Bool("csv", false, "Whether to print in CSV format (with slow classification).") + check = flag.Bool("check", false, "Whether to just check license files for forbidden licenses.") +) + +func main() { + flag.Parse() + if flag.NArg() == 0 { + log.Fatalf("Expected a list of import paths, got: %v", flag.Args()) + } + + // Perform a simple DFS to collect the binaries' transitive dependencies. + transitiveImports, err := CollectTransitiveImports(flag.Args()) + if err != nil { + log.Fatalf("Error collecting transitive dependencies: %v", err) + } + + // Gather all of the license data from the imports. + collection, err := CollectLicenses(transitiveImports) + if err != nil { + log.Fatalf("Error identifying licenses for transitive dependencies: %v", err) + } + + if *check { + classifier, err := licenseclassifier.NewWithForbiddenLicenses(MatchThreshold) + if err != nil { + log.Fatalf("Error creating license classifier: %v", err) + } + if err := collection.Check(classifier); err != nil { + log.Fatalf("Error checking license collection: %v", err) + } + log.Printf("No errors found.") + return + } + + if *csv { + classifier, err := licenseclassifier.New(MatchThreshold) + if err != nil { + log.Fatalf("Error creating license classifier: %v", err) + } + output, err := collection.CSV(classifier) + if err != nil { + log.Fatalf("Error generating CSV: %v", err) + } + os.Stdout.Write([]byte(output)) + } else { + entries, err := collection.Entries() + if err != nil { + log.Fatalf("Error generating entries: %v", err) + } + os.Stdout.Write([]byte(entries)) + } +} diff --git a/vendor/github.com/markbates/inflect/LICENCE b/vendor/github.com/markbates/inflect/LICENCE new file mode 100644 index 00000000000..8a36b944a5e --- /dev/null +++ b/vendor/github.com/markbates/inflect/LICENCE @@ -0,0 +1,7 @@ +Copyright (c) 2011 Chris Farmiloe + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/markbates/inflect/helpers.go b/vendor/github.com/markbates/inflect/helpers.go new file mode 100644 index 00000000000..24050c70a04 --- /dev/null +++ b/vendor/github.com/markbates/inflect/helpers.go @@ -0,0 +1,19 @@ +package inflect + +//Helpers is a map of the helper names with its corresponding inflect function +var Helpers = map[string]interface{}{ + "asciffy": Asciify, + "camelize": Camelize, + "camelize_down_first": CamelizeDownFirst, + "capitalize": Capitalize, + "dasherize": Dasherize, + "humanize": Humanize, + "ordinalize": Ordinalize, + "parameterize": Parameterize, + "pluralize": Pluralize, + "pluralize_with_size": PluralizeWithSize, + "singularize": Singularize, + "tableize": Tableize, + "typeify": Typeify, + "underscore": Underscore, +} diff --git a/vendor/github.com/markbates/inflect/inflect.go b/vendor/github.com/markbates/inflect/inflect.go new file mode 100644 index 00000000000..9b6776c191c --- /dev/null +++ b/vendor/github.com/markbates/inflect/inflect.go @@ -0,0 +1,892 @@ +package inflect + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "unicode" + "unicode/utf8" +) + +// baseAcronyms comes from https://en.wikipedia.org/wiki/List_of_information_technology_acronymss +const baseAcronyms = `JSON,JWT,ID,UUID,SQL,ACK,ACL,ADSL,AES,ANSI,API,ARP,ATM,BGP,BSS,CAT,CCITT,CHAP,CIDR,CIR,CLI,CPE,CPU,CRC,CRT,CSMA,CMOS,DCE,DEC,DES,DHCP,DNS,DRAM,DSL,DSLAM,DTE,DMI,EHA,EIA,EIGRP,EOF,ESS,FCC,FCS,FDDI,FTP,GBIC,gbps,GEPOF,HDLC,HTTP,HTTPS,IANA,ICMP,IDF,IDS,IEEE,IETF,IMAP,IP,IPS,ISDN,ISP,kbps,LACP,LAN,LAPB,LAPF,LLC,MAC,MAN,Mbps,MC,MDF,MIB,MoCA,MPLS,MTU,NAC,NAT,NBMA,NIC,NRZ,NRZI,NVRAM,OSI,OSPF,OUI,PAP,PAT,PC,PIM,PIM,PCM,PDU,POP3,POP,POTS,PPP,PPTP,PTT,PVST,RADIUS,RAM,RARP,RFC,RIP,RLL,ROM,RSTP,RTP,RCP,SDLC,SFD,SFP,SLARP,SLIP,SMTP,SNA,SNAP,SNMP,SOF,SRAM,SSH,SSID,STP,SYN,TDM,TFTP,TIA,TOFU,UDP,URL,URI,USB,UTP,VC,VLAN,VLSM,VPN,W3C,WAN,WEP,WiFi,WPA,WWW` + +// Rule used by rulesets +type Rule struct { + suffix string + replacement string + exact bool +} + +// Ruleset a Ruleset is the config of pluralization rules +// you can extend the rules with the Add* methods +type Ruleset struct { + uncountables map[string]bool + plurals []*Rule + singulars []*Rule + humans []*Rule + acronyms []*Rule +} + +// NewRuleset creates a blank ruleset. Unless you are going to +// build your own rules from scratch you probably +// won't need this and can just use the defaultRuleset +// via the global inflect.* methods +func NewRuleset() *Ruleset { + rs := new(Ruleset) + rs.uncountables = make(map[string]bool) + rs.plurals = make([]*Rule, 0) + rs.singulars = make([]*Rule, 0) + rs.humans = make([]*Rule, 0) + rs.acronyms = make([]*Rule, 0) + return rs +} + +// NewDefaultRuleset creates a new ruleset and load it with the default +// set of common English pluralization rules +func NewDefaultRuleset() *Ruleset { + rs := NewRuleset() + rs.AddPlural("movie", "movies") + rs.AddPlural("s", "s") + rs.AddPlural("testis", "testes") + rs.AddPlural("axis", "axes") + rs.AddPlural("octopus", "octopi") + rs.AddPlural("virus", "viri") + rs.AddPlural("octopi", "octopi") + rs.AddPlural("viri", "viri") + rs.AddPlural("alias", "aliases") + rs.AddPlural("status", "statuses") + rs.AddPlural("Status", "Statuses") + rs.AddPlural("campus", "campuses") + rs.AddPlural("bus", "buses") + rs.AddPlural("buffalo", "buffaloes") + rs.AddPlural("tomato", "tomatoes") + rs.AddPlural("tum", "ta") + rs.AddPlural("ium", "ia") + rs.AddPlural("ta", "ta") + rs.AddPlural("ia", "ia") + rs.AddPlural("sis", "ses") + rs.AddPlural("lf", "lves") + rs.AddPlural("rf", "rves") + rs.AddPlural("afe", "aves") + rs.AddPlural("bfe", "bves") + rs.AddPlural("cfe", "cves") + rs.AddPlural("dfe", "dves") + rs.AddPlural("efe", "eves") + rs.AddPlural("gfe", "gves") + rs.AddPlural("hfe", "hves") + rs.AddPlural("ife", "ives") + rs.AddPlural("jfe", "jves") + rs.AddPlural("kfe", "kves") + rs.AddPlural("lfe", "lves") + rs.AddPlural("mfe", "mves") + rs.AddPlural("nfe", "nves") + rs.AddPlural("ofe", "oves") + rs.AddPlural("pfe", "pves") + rs.AddPlural("qfe", "qves") + rs.AddPlural("rfe", "rves") + rs.AddPlural("sfe", "sves") + rs.AddPlural("tfe", "tves") + rs.AddPlural("ufe", "uves") + rs.AddPlural("vfe", "vves") + rs.AddPlural("wfe", "wves") + rs.AddPlural("xfe", "xves") + rs.AddPlural("yfe", "yves") + rs.AddPlural("zfe", "zves") + rs.AddPlural("hive", "hives") + rs.AddPlural("quy", "quies") + rs.AddPlural("by", "bies") + rs.AddPlural("cy", "cies") + rs.AddPlural("dy", "dies") + rs.AddPlural("fy", "fies") + rs.AddPlural("gy", "gies") + rs.AddPlural("hy", "hies") + rs.AddPlural("jy", "jies") + rs.AddPlural("ky", "kies") + rs.AddPlural("ly", "lies") + rs.AddPlural("my", "mies") + rs.AddPlural("ny", "nies") + rs.AddPlural("py", "pies") + rs.AddPlural("qy", "qies") + rs.AddPlural("ry", "ries") + rs.AddPlural("sy", "sies") + rs.AddPlural("ty", "ties") + rs.AddPlural("vy", "vies") + rs.AddPlural("wy", "wies") + rs.AddPlural("xy", "xies") + rs.AddPlural("zy", "zies") + rs.AddPlural("x", "xes") + rs.AddPlural("ch", "ches") + rs.AddPlural("ss", "sses") + rs.AddPlural("sh", "shes") + rs.AddPlural("matrix", "matrices") + rs.AddPlural("vertix", "vertices") + rs.AddPlural("indix", "indices") + rs.AddPlural("matrex", "matrices") + rs.AddPlural("vertex", "vertices") + rs.AddPlural("index", "indices") + rs.AddPlural("mouse", "mice") + rs.AddPlural("louse", "lice") + rs.AddPlural("mice", "mice") + rs.AddPlural("lice", "lice") + rs.AddPlural("ress", "resses") + rs.AddPluralExact("ox", "oxen", true) + rs.AddPluralExact("oxen", "oxen", true) + rs.AddPluralExact("quiz", "quizzes", true) + rs.AddSingular("s", "") + rs.AddSingular("ss", "ss") + rs.AddSingular("news", "news") + rs.AddSingular("ta", "tum") + rs.AddSingular("ia", "ium") + rs.AddSingular("analyses", "analysis") + rs.AddSingular("bases", "basis") + rs.AddSingularExact("basis", "basis", true) + rs.AddSingular("diagnoses", "diagnosis") + rs.AddSingularExact("diagnosis", "diagnosis", true) + rs.AddSingular("parentheses", "parenthesis") + rs.AddSingular("prognoses", "prognosis") + rs.AddSingular("synopses", "synopsis") + rs.AddSingular("theses", "thesis") + rs.AddSingular("analyses", "analysis") + rs.AddSingularExact("analysis", "analysis", true) + rs.AddSingular("ovies", "ovie") + rs.AddSingular("aves", "afe") + rs.AddSingular("bves", "bfe") + rs.AddSingular("cves", "cfe") + rs.AddSingular("dves", "dfe") + rs.AddSingular("eves", "efe") + rs.AddSingular("gves", "gfe") + rs.AddSingular("hves", "hfe") + rs.AddSingular("ives", "ife") + rs.AddSingular("jves", "jfe") + rs.AddSingular("kves", "kfe") + rs.AddSingular("lves", "lfe") + rs.AddSingular("mves", "mfe") + rs.AddSingular("nves", "nfe") + rs.AddSingular("oves", "ofe") + rs.AddSingular("pves", "pfe") + rs.AddSingular("qves", "qfe") + rs.AddSingular("rves", "rfe") + rs.AddSingular("sves", "sfe") + rs.AddSingular("tves", "tfe") + rs.AddSingular("uves", "ufe") + rs.AddSingular("vves", "vfe") + rs.AddSingular("wves", "wfe") + rs.AddSingular("xves", "xfe") + rs.AddSingular("yves", "yfe") + rs.AddSingular("zves", "zfe") + rs.AddSingular("hives", "hive") + rs.AddSingular("tives", "tive") + rs.AddSingular("lves", "lf") + rs.AddSingular("rves", "rf") + rs.AddSingular("quies", "quy") + rs.AddSingular("bies", "by") + rs.AddSingular("cies", "cy") + rs.AddSingular("dies", "dy") + rs.AddSingular("fies", "fy") + rs.AddSingular("gies", "gy") + rs.AddSingular("hies", "hy") + rs.AddSingular("jies", "jy") + rs.AddSingular("kies", "ky") + rs.AddSingular("lies", "ly") + rs.AddSingular("mies", "my") + rs.AddSingular("nies", "ny") + rs.AddSingular("pies", "py") + rs.AddSingular("qies", "qy") + rs.AddSingular("ries", "ry") + rs.AddSingular("sies", "sy") + rs.AddSingular("ties", "ty") + // rs.AddSingular("vies", "vy") + rs.AddSingular("wies", "wy") + rs.AddSingular("xies", "xy") + rs.AddSingular("zies", "zy") + rs.AddSingular("series", "series") + rs.AddSingular("xes", "x") + rs.AddSingular("ches", "ch") + rs.AddSingular("sses", "ss") + rs.AddSingular("shes", "sh") + rs.AddSingular("mice", "mouse") + rs.AddSingular("lice", "louse") + rs.AddSingular("buses", "bus") + rs.AddSingularExact("bus", "bus", true) + rs.AddSingular("oes", "o") + rs.AddSingular("shoes", "shoe") + rs.AddSingular("crises", "crisis") + rs.AddSingularExact("crisis", "crisis", true) + rs.AddSingular("axes", "axis") + rs.AddSingularExact("axis", "axis", true) + rs.AddSingular("testes", "testis") + rs.AddSingularExact("testis", "testis", true) + rs.AddSingular("octopi", "octopus") + rs.AddSingularExact("octopus", "octopus", true) + rs.AddSingular("viri", "virus") + rs.AddSingularExact("virus", "virus", true) + rs.AddSingular("statuses", "status") + rs.AddSingular("Statuses", "Status") + rs.AddSingular("campuses", "campus") + rs.AddSingularExact("status", "status", true) + rs.AddSingularExact("Status", "Status", true) + rs.AddSingularExact("campus", "campus", true) + rs.AddSingular("aliases", "alias") + rs.AddSingularExact("alias", "alias", true) + rs.AddSingularExact("oxen", "ox", true) + rs.AddSingular("vertices", "vertex") + rs.AddSingular("indices", "index") + rs.AddSingular("matrices", "matrix") + rs.AddSingularExact("quizzes", "quiz", true) + rs.AddSingular("databases", "database") + rs.AddSingular("resses", "ress") + rs.AddSingular("ress", "ress") + rs.AddIrregular("person", "people") + rs.AddIrregular("man", "men") + rs.AddIrregular("child", "children") + rs.AddIrregular("sex", "sexes") + rs.AddIrregular("move", "moves") + rs.AddIrregular("zombie", "zombies") + rs.AddIrregular("Status", "Statuses") + rs.AddIrregular("status", "statuses") + rs.AddIrregular("campus", "campuses") + rs.AddIrregular("human", "humans") + rs.AddUncountable("equipment") + rs.AddUncountable("information") + rs.AddUncountable("rice") + rs.AddUncountable("money") + rs.AddUncountable("species") + rs.AddUncountable("series") + rs.AddUncountable("fish") + rs.AddUncountable("sheep") + rs.AddUncountable("jeans") + rs.AddUncountable("police") + + acronyms := strings.Split(baseAcronyms, ",") + for _, acr := range acronyms { + rs.AddAcronym(acr) + } + + return rs +} + +// Uncountables returns a map of uncountables in the ruleset +func (rs *Ruleset) Uncountables() map[string]bool { + return rs.uncountables +} + +// AddPlural add a pluralization rule +func (rs *Ruleset) AddPlural(suffix, replacement string) { + rs.AddPluralExact(suffix, replacement, false) +} + +// AddPluralExact add a pluralization rule with full string match +func (rs *Ruleset) AddPluralExact(suffix, replacement string, exact bool) { + // remove uncountable + delete(rs.uncountables, suffix) + // create rule + r := new(Rule) + r.suffix = suffix + r.replacement = replacement + r.exact = exact + // prepend + rs.plurals = append([]*Rule{r}, rs.plurals...) +} + +// AddSingular add a singular rule +func (rs *Ruleset) AddSingular(suffix, replacement string) { + rs.AddSingularExact(suffix, replacement, false) +} + +// AddSingularExact same as AddSingular but you can set `exact` to force +// a full string match +func (rs *Ruleset) AddSingularExact(suffix, replacement string, exact bool) { + // remove from uncountable + delete(rs.uncountables, suffix) + // create rule + r := new(Rule) + r.suffix = suffix + r.replacement = replacement + r.exact = exact + rs.singulars = append([]*Rule{r}, rs.singulars...) +} + +// AddHuman Human rules are applied by humanize to show more friendly +// versions of words +func (rs *Ruleset) AddHuman(suffix, replacement string) { + r := new(Rule) + r.suffix = suffix + r.replacement = replacement + rs.humans = append([]*Rule{r}, rs.humans...) +} + +// AddIrregular Add any inconsistent pluralizing/singularizing rules +// to the set here. +func (rs *Ruleset) AddIrregular(singular, plural string) { + delete(rs.uncountables, singular) + delete(rs.uncountables, plural) + rs.AddPlural(singular, plural) + rs.AddPlural(plural, plural) + rs.AddSingular(plural, singular) +} + +// AddAcronym if you use acronym you may need to add them to the ruleset +// to prevent Underscored words of things like "HTML" coming out +// as "h_t_m_l" +func (rs *Ruleset) AddAcronym(word string) { + r := new(Rule) + r.suffix = word + r.replacement = rs.Titleize(strings.ToLower(word)) + rs.acronyms = append(rs.acronyms, r) +} + +// AddUncountable add a word to this ruleset that has the same singular and plural form +// for example: "rice" +func (rs *Ruleset) AddUncountable(word string) { + rs.uncountables[strings.ToLower(word)] = true +} + +func (rs *Ruleset) isUncountable(word string) bool { + // handle multiple words by using the last one + words := strings.Split(word, " ") + if _, exists := rs.uncountables[strings.ToLower(words[len(words)-1])]; exists { + return true + } + return false +} + +//isAcronym returns if a word is acronym or not. +func (rs *Ruleset) isAcronym(word string) bool { + for _, rule := range rs.acronyms { + if strings.ToUpper(rule.suffix) == strings.ToUpper(word) { + return true + } + } + + return false +} + +//PluralizeWithSize pluralize with taking number into account +func (rs *Ruleset) PluralizeWithSize(word string, size int) string { + if size == 1 { + return rs.Singularize(word) + } + return rs.Pluralize(word) +} + +// Pluralize returns the plural form of a singular word +func (rs *Ruleset) Pluralize(word string) string { + if len(word) == 0 { + return word + } + lWord := strings.ToLower(word) + if rs.isUncountable(lWord) { + return word + } + + var candidate string + for _, rule := range rs.plurals { + if rule.exact { + if lWord == rule.suffix { + // Capitalized word + if lWord[0] != word[0] && lWord[1:] == word[1:] { + return rs.Capitalize(rule.replacement) + } + return rule.replacement + } + continue + } + + if strings.EqualFold(word, rule.suffix) { + candidate = rule.replacement + } + + if strings.HasSuffix(word, rule.suffix) { + return replaceLast(word, rule.suffix, rule.replacement) + } + } + + if candidate != "" { + return candidate + } + return word + "s" +} + +//Singularize returns the singular form of a plural word +func (rs *Ruleset) Singularize(word string) string { + if len(word) <= 1 { + return word + } + lWord := strings.ToLower(word) + if rs.isUncountable(lWord) { + return word + } + + var candidate string + + for _, rule := range rs.singulars { + if rule.exact { + if lWord == rule.suffix { + // Capitalized word + if lWord[0] != word[0] && lWord[1:] == word[1:] { + return rs.Capitalize(rule.replacement) + } + return rule.replacement + } + continue + } + + if strings.EqualFold(word, rule.suffix) { + candidate = rule.replacement + } + + if strings.HasSuffix(word, rule.suffix) { + return replaceLast(word, rule.suffix, rule.replacement) + } + } + + if candidate != "" { + return candidate + } + + return word +} + +//Capitalize uppercase first character +func (rs *Ruleset) Capitalize(word string) string { + if rs.isAcronym(word) { + return strings.ToUpper(word) + } + return strings.ToUpper(word[:1]) + word[1:] +} + +//Camelize "dino_party" -> "DinoParty" +func (rs *Ruleset) Camelize(word string) string { + if rs.isAcronym(word) { + return strings.ToUpper(word) + } + words := splitAtCaseChangeWithTitlecase(word) + return strings.Join(words, "") +} + +//CamelizeDownFirst same as Camelcase but with first letter downcased +func (rs *Ruleset) CamelizeDownFirst(word string) string { + word = Camelize(word) + return strings.ToLower(word[:1]) + word[1:] +} + +//Titleize Capitalize every word in sentence "hello there" -> "Hello There" +func (rs *Ruleset) Titleize(word string) string { + words := splitAtCaseChangeWithTitlecase(word) + result := strings.Join(words, " ") + + var acronymWords []string + for index, word := range words { + if len(word) == 1 { + acronymWords = append(acronymWords, word) + } + + if len(word) > 1 || index == len(words)-1 || len(acronymWords) > 1 { + acronym := strings.Join(acronymWords, "") + if !rs.isAcronym(acronym) { + acronymWords = acronymWords[:len(acronymWords)] + continue + } + + result = strings.Replace(result, strings.Join(acronymWords, " "), acronym, 1) + acronymWords = []string{} + } + } + + return result +} + +func (rs *Ruleset) safeCaseAcronyms(word string) string { + // convert an acronym like HTML into Html + for _, rule := range rs.acronyms { + word = strings.Replace(word, rule.suffix, rule.replacement, -1) + } + return word +} + +func (rs *Ruleset) separatedWords(word, sep string) string { + word = rs.safeCaseAcronyms(word) + words := splitAtCaseChange(word) + return strings.Join(words, sep) +} + +//Underscore lowercase underscore version "BigBen" -> "big_ben" +func (rs *Ruleset) Underscore(word string) string { + return rs.separatedWords(word, "_") +} + +//Humanize First letter of sentence capitalized +// Uses custom friendly replacements via AddHuman() +func (rs *Ruleset) Humanize(word string) string { + word = replaceLast(word, "_id", "") // strip foreign key kinds + // replace and strings in humans list + for _, rule := range rs.humans { + word = strings.Replace(word, rule.suffix, rule.replacement, -1) + } + sentence := rs.separatedWords(word, " ") + + r, n := utf8.DecodeRuneInString(sentence) + return string(unicode.ToUpper(r)) + sentence[n:] +} + +//ForeignKey an underscored foreign key name "Person" -> "person_id" +func (rs *Ruleset) ForeignKey(word string) string { + return rs.Underscore(rs.Singularize(word)) + "_id" +} + +//ForeignKeyCondensed a foreign key (with an underscore) "Person" -> "personid" +func (rs *Ruleset) ForeignKeyCondensed(word string) string { + return rs.Underscore(word) + "id" +} + +//Tableize Rails style pluralized table names: "SuperPerson" -> "super_people" +func (rs *Ruleset) Tableize(word string) string { + return rs.Pluralize(rs.Underscore(rs.Typeify(word))) +} + +var notUrlSafe *regexp.Regexp = regexp.MustCompile(`[^\w\d\-_ ]`) + +//Parameterize param safe dasherized names like "my-param" +func (rs *Ruleset) Parameterize(word string) string { + return ParameterizeJoin(word, "-") +} + +//ParameterizeJoin param safe dasherized names with custom separator +func (rs *Ruleset) ParameterizeJoin(word, sep string) string { + word = strings.ToLower(word) + word = rs.Asciify(word) + word = notUrlSafe.ReplaceAllString(word, "") + word = strings.Replace(word, " ", sep, -1) + if len(sep) > 0 { + squash, err := regexp.Compile(sep + "+") + if err == nil { + word = squash.ReplaceAllString(word, sep) + } + } + word = strings.Trim(word, sep+" ") + return word +} + +var lookalikes = map[string]*regexp.Regexp{ + "A": regexp.MustCompile(`À|Á|Â|Ã|Ä|Å`), + "AE": regexp.MustCompile(`Æ`), + "C": regexp.MustCompile(`Ç`), + "E": regexp.MustCompile(`È|É|Ê|Ë`), + "G": regexp.MustCompile(`Ğ`), + "I": regexp.MustCompile(`Ì|Í|Î|Ï|İ`), + "N": regexp.MustCompile(`Ñ`), + "O": regexp.MustCompile(`Ò|Ó|Ô|Õ|Ö|Ø`), + "S": regexp.MustCompile(`Ş`), + "U": regexp.MustCompile(`Ù|Ú|Û|Ü`), + "Y": regexp.MustCompile(`Ý`), + "ss": regexp.MustCompile(`ß`), + "a": regexp.MustCompile(`à|á|â|ã|ä|å`), + "ae": regexp.MustCompile(`æ`), + "c": regexp.MustCompile(`ç`), + "e": regexp.MustCompile(`è|é|ê|ë`), + "g": regexp.MustCompile(`ğ`), + "i": regexp.MustCompile(`ì|í|î|ï|ı`), + "n": regexp.MustCompile(`ñ`), + "o": regexp.MustCompile(`ò|ó|ô|õ|ö|ø`), + "s": regexp.MustCompile(`ş`), + "u": regexp.MustCompile(`ù|ú|û|ü|ũ|ū|ŭ|ů|ű|ų`), + "y": regexp.MustCompile(`ý|ÿ`), +} + +//Asciify transforms Latin characters like é -> e +func (rs *Ruleset) Asciify(word string) string { + for repl, regex := range lookalikes { + word = regex.ReplaceAllString(word, repl) + } + return word +} + +var tablePrefix = regexp.MustCompile(`^[^.]*\.`) + +//Typeify "something_like_this" -> "SomethingLikeThis" +func (rs *Ruleset) Typeify(word string) string { + word = tablePrefix.ReplaceAllString(word, "") + return rs.Camelize(rs.Singularize(word)) +} + +//Dasherize "SomeText" -> "some-text" +func (rs *Ruleset) Dasherize(word string) string { + return rs.separatedWords(word, "-") +} + +//Ordinalize "1031" -> "1031st" +func (rs *Ruleset) Ordinalize(str string) string { + number, err := strconv.Atoi(str) + if err != nil { + return str + } + switch abs(number) % 100 { + case 11, 12, 13: + return fmt.Sprintf("%dth", number) + default: + switch abs(number) % 10 { + case 1: + return fmt.Sprintf("%dst", number) + case 2: + return fmt.Sprintf("%dnd", number) + case 3: + return fmt.Sprintf("%drd", number) + } + } + return fmt.Sprintf("%dth", number) +} + +//ForeignKeyToAttribute returns the attribute name from the foreign key +func (rs *Ruleset) ForeignKeyToAttribute(str string) string { + w := rs.Camelize(str) + if strings.HasSuffix(w, "Id") { + return strings.TrimSuffix(w, "Id") + "ID" + } + return w +} + +//LoadReader loads rules from io.Reader param +func (rs *Ruleset) LoadReader(r io.Reader) error { + m := map[string]string{} + err := json.NewDecoder(r).Decode(&m) + if err != nil { + return fmt.Errorf("could not decode inflection JSON from reader: %s", err) + } + for s, p := range m { + defaultRuleset.AddIrregular(s, p) + } + return nil +} + +///////////////////////////////////////// +// the default global ruleset +////////////////////////////////////////// + +var defaultRuleset *Ruleset + +//LoadReader loads rules from io.Reader param +func LoadReader(r io.Reader) error { + return defaultRuleset.LoadReader(r) +} + +func init() { + defaultRuleset = NewDefaultRuleset() + + pwd, _ := os.Getwd() + cfg := filepath.Join(pwd, "inflections.json") + if p := os.Getenv("INFLECT_PATH"); p != "" { + cfg = p + } + if _, err := os.Stat(cfg); err == nil { + b, err := ioutil.ReadFile(cfg) + if err != nil { + fmt.Printf("could not read inflection file %s (%s)\n", cfg, err) + return + } + if err = defaultRuleset.LoadReader(bytes.NewReader(b)); err != nil { + fmt.Println(err) + } + } +} + +//Uncountables returns a list of uncountables rules +func Uncountables() map[string]bool { + return defaultRuleset.Uncountables() +} + +//AddPlural adds plural to the ruleset +func AddPlural(suffix, replacement string) { + defaultRuleset.AddPlural(suffix, replacement) +} + +//AddSingular adds singular to the ruleset +func AddSingular(suffix, replacement string) { + defaultRuleset.AddSingular(suffix, replacement) +} + +//AddHuman adds human +func AddHuman(suffix, replacement string) { + defaultRuleset.AddHuman(suffix, replacement) +} + +func AddIrregular(singular, plural string) { + defaultRuleset.AddIrregular(singular, plural) +} + +func AddAcronym(word string) { + defaultRuleset.AddAcronym(word) +} + +func AddUncountable(word string) { + defaultRuleset.AddUncountable(word) +} + +func Pluralize(word string) string { + return defaultRuleset.Pluralize(word) +} + +func PluralizeWithSize(word string, size int) string { + return defaultRuleset.PluralizeWithSize(word, size) +} + +func Singularize(word string) string { + return defaultRuleset.Singularize(word) +} + +func Capitalize(word string) string { + return defaultRuleset.Capitalize(word) +} + +func Camelize(word string) string { + return defaultRuleset.Camelize(word) +} + +func CamelizeDownFirst(word string) string { + return defaultRuleset.CamelizeDownFirst(word) +} + +func Titleize(word string) string { + return defaultRuleset.Titleize(word) +} + +func Underscore(word string) string { + return defaultRuleset.Underscore(word) +} + +func Humanize(word string) string { + return defaultRuleset.Humanize(word) +} + +func ForeignKey(word string) string { + return defaultRuleset.ForeignKey(word) +} + +func ForeignKeyCondensed(word string) string { + return defaultRuleset.ForeignKeyCondensed(word) +} + +func Tableize(word string) string { + return defaultRuleset.Tableize(word) +} + +func Parameterize(word string) string { + return defaultRuleset.Parameterize(word) +} + +func ParameterizeJoin(word, sep string) string { + return defaultRuleset.ParameterizeJoin(word, sep) +} + +func Typeify(word string) string { + return defaultRuleset.Typeify(word) +} + +func Dasherize(word string) string { + return defaultRuleset.Dasherize(word) +} + +func Ordinalize(word string) string { + return defaultRuleset.Ordinalize(word) +} + +func Asciify(word string) string { + return defaultRuleset.Asciify(word) +} + +func ForeignKeyToAttribute(word string) string { + return defaultRuleset.ForeignKeyToAttribute(word) +} + +// helper funcs + +func reverse(s string) string { + o := make([]rune, utf8.RuneCountInString(s)) + i := len(o) + for _, c := range s { + i-- + o[i] = c + } + return string(o) +} + +func isSpacerChar(c rune) bool { + switch { + case c == rune("_"[0]): + return true + case c == rune(" "[0]): + return true + case c == rune(":"[0]): + return true + case c == rune("-"[0]): + return true + } + return false +} + +func splitAtCaseChange(s string) []string { + words := make([]string, 0) + word := make([]rune, 0) + for _, c := range s { + spacer := isSpacerChar(c) + if len(word) > 0 { + if unicode.IsUpper(c) || spacer { + words = append(words, string(word)) + word = make([]rune, 0) + } + } + if !spacer { + word = append(word, unicode.ToLower(c)) + } + } + words = append(words, string(word)) + return words +} + +func splitAtCaseChangeWithTitlecase(s string) []string { + words := make([]string, 0) + word := make([]rune, 0) + + for _, c := range s { + spacer := isSpacerChar(c) + if len(word) > 0 { + if unicode.IsUpper(c) || spacer { + words = append(words, string(word)) + word = make([]rune, 0) + } + } + if !spacer { + if len(word) > 0 { + word = append(word, unicode.ToLower(c)) + } else { + word = append(word, unicode.ToUpper(c)) + } + } + } + + words = append(words, string(word)) + return words +} + +func replaceLast(s, match, repl string) string { + // reverse strings + srev := reverse(s) + mrev := reverse(match) + rrev := reverse(repl) + // match first and reverse back + return reverse(strings.Replace(srev, mrev, rrev, 1)) +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} diff --git a/vendor/github.com/markbates/inflect/name.go b/vendor/github.com/markbates/inflect/name.go new file mode 100644 index 00000000000..e6863e28a68 --- /dev/null +++ b/vendor/github.com/markbates/inflect/name.go @@ -0,0 +1,163 @@ +package inflect + +import ( + "fmt" + "path/filepath" + "strings" + + "github.com/gobuffalo/envy" +) + +// Name is a string that represents the "name" of a thing, like an app, model, etc... +type Name string + +// Title version of a name. ie. "foo_bar" => "Foo Bar" +func (n Name) Title() string { + x := strings.Split(string(n), "/") + for i, s := range x { + x[i] = Titleize(s) + } + + return strings.Join(x, " ") +} + +// Underscore version of a name. ie. "FooBar" => "foo_bar" +func (n Name) Underscore() string { + w := string(n) + if strings.ToUpper(w) == w { + return strings.ToLower(w) + } + return Underscore(w) +} + +// Plural version of a name +func (n Name) Plural() string { + return Pluralize(string(n)) +} + +// Singular version of a name +func (n Name) Singular() string { + return Singularize(string(n)) +} + +// Camel version of a name +func (n Name) Camel() string { + c := Camelize(string(n)) + if strings.HasSuffix(c, "Id") { + c = strings.TrimSuffix(c, "Id") + c += "ID" + } + return c +} + +// Model version of a name. ie. "user" => "User" +func (n Name) Model() string { + x := strings.Split(string(n), "/") + for i, s := range x { + x[i] = Camelize(Singularize(s)) + } + + return strings.Join(x, "") +} + +// Resource version of a name +func (n Name) Resource() string { + name := n.Underscore() + x := strings.FieldsFunc(name, func(r rune) bool { + return r == '_' || r == '/' + }) + + for i, w := range x { + if i == len(x)-1 { + x[i] = Camelize(Pluralize(strings.ToLower(w))) + continue + } + + x[i] = Camelize(w) + } + + return strings.Join(x, "") +} + +// ModelPlural version of a name. ie. "user" => "Users" +func (n Name) ModelPlural() string { + return Camelize(Pluralize(n.Model())) +} + +// File version of a name +func (n Name) File() string { + return Underscore(Camelize(string(n))) +} + +// Table version of a name +func (n Name) Table() string { + return Underscore(Pluralize(string(n))) +} + +// UnderSingular version of a name +func (n Name) UnderSingular() string { + return Underscore(Singularize(string(n))) +} + +// PluralCamel version of a name +func (n Name) PluralCamel() string { + return Pluralize(Camelize(string(n))) +} + +// PluralUnder version of a name +func (n Name) PluralUnder() string { + return Pluralize(Underscore(string(n))) +} + +// URL version of a name +func (n Name) URL() string { + return n.PluralUnder() +} + +// CamelSingular version of a name +func (n Name) CamelSingular() string { + return Camelize(Singularize(string(n))) +} + +// VarCaseSingular version of a name. ie. "FooBar" => "fooBar" +func (n Name) VarCaseSingular() string { + return CamelizeDownFirst(Singularize(Underscore(n.Resource()))) +} + +// VarCasePlural version of a name. ie. "FooBar" => "fooBar" +func (n Name) VarCasePlural() string { + return CamelizeDownFirst(n.Resource()) +} + +// Lower case version of a string +func (n Name) Lower() string { + return strings.ToLower(string(n)) +} + +// ParamID returns foo_bar_id +func (n Name) ParamID() string { + return fmt.Sprintf("%s_id", strings.Replace(n.UnderSingular(), "/", "_", -1)) +} + +// Package returns go package +func (n Name) Package() string { + key := string(n) + + for _, gp := range envy.GoPaths() { + key = strings.TrimPrefix(key, filepath.Join(gp, "src")) + key = strings.TrimPrefix(key, gp) + } + key = strings.TrimPrefix(key, string(filepath.Separator)) + + key = strings.Replace(key, "\\", "/", -1) + return key +} + +// Char returns first character in lower case, this is useful for methods inside a struct. +func (n Name) Char() string { + return strings.ToLower(string(n[0])) +} + +func (n Name) String() string { + return string(n) +} diff --git a/vendor/github.com/markbates/inflect/version.go b/vendor/github.com/markbates/inflect/version.go new file mode 100644 index 00000000000..a1674498419 --- /dev/null +++ b/vendor/github.com/markbates/inflect/version.go @@ -0,0 +1,3 @@ +package inflect + +const Version = "v1.0.4" diff --git a/vendor/github.com/pierrec/lz4/block.go b/vendor/github.com/pierrec/lz4/block.go index ef24f17e57a..00b1111b92b 100644 --- a/vendor/github.com/pierrec/lz4/block.go +++ b/vendor/github.com/pierrec/lz4/block.go @@ -286,7 +286,7 @@ func CompressBlockHC(src, dst []byte, depth int) (di int, err error) { for ml < sn-si && src[next+ml] == src[si+ml] { ml++ } - if ml+1 < minMatch || ml <= mLen { + if ml < minMatch || ml <= mLen { // Match too small (>8), byte(h32>>16), byte(h32>>24)) -} - -// Reset resets the Hash to its initial state. -func (xxh *XXH) Reset() { - seed := xxh.seed - xxh.v1 = seed + prime32_1plus2 - xxh.v2 = seed + prime32_2 - xxh.v3 = seed - xxh.v4 = seed - prime32_1 - xxh.totalLen = 0 - xxh.bufused = 0 -} - -// Size returns the number of bytes returned by Sum(). -func (xxh *XXH) Size() int { - return 4 -} - -// BlockSize gives the minimum number of bytes accepted by Write(). -func (xxh *XXH) BlockSize() int { - return 1 -} - -// Write adds input bytes to the Hash. -// It never returns an error. -func (xxh *XXH) Write(input []byte) (int, error) { - n := len(input) - m := xxh.bufused - - xxh.totalLen += uint64(n) - - r := len(xxh.buf) - m - if n < r { - copy(xxh.buf[m:], input) - xxh.bufused += len(input) - return n, nil - } - - // Causes compiler to work directly from registers instead of stack: - v1, v2, v3, v4 := xxh.v1, xxh.v2, xxh.v3, xxh.v4 - p := 0 - if m > 0 { - // some data left from previous update - copy(xxh.buf[xxh.bufused:], input[:r]) - xxh.bufused += len(input) - r - - // fast rotl(13) - buf := xxh.buf[:16] // BCE hint. - xxh.v1 = rol13(v1+binary.LittleEndian.Uint32(buf[:])*prime32_2) * prime32_1 - xxh.v2 = rol13(v2+binary.LittleEndian.Uint32(buf[4:])*prime32_2) * prime32_1 - xxh.v3 = rol13(v3+binary.LittleEndian.Uint32(buf[8:])*prime32_2) * prime32_1 - xxh.v4 = rol13(v4+binary.LittleEndian.Uint32(buf[12:])*prime32_2) * prime32_1 - p = r - xxh.bufused = 0 - } - - for n := n - 16; p <= n; p += 16 { - sub := input[p:][:16] //BCE hint for compiler - v1 = rol13(v1+binary.LittleEndian.Uint32(sub[:])*prime32_2) * prime32_1 - v2 = rol13(v2+binary.LittleEndian.Uint32(sub[4:])*prime32_2) * prime32_1 - v3 = rol13(v3+binary.LittleEndian.Uint32(sub[8:])*prime32_2) * prime32_1 - v4 = rol13(v4+binary.LittleEndian.Uint32(sub[12:])*prime32_2) * prime32_1 - } - xxh.v1, xxh.v2, xxh.v3, xxh.v4 = v1, v2, v3, v4 - - copy(xxh.buf[xxh.bufused:], input[p:]) - xxh.bufused += len(input) - p - - return n, nil -} - -// Sum32 returns the 32 bits Hash value. -func (xxh *XXH) Sum32() uint32 { - h32 := uint32(xxh.totalLen) - if h32 >= 16 { - h32 += rol1(xxh.v1) + rol7(xxh.v2) + rol12(xxh.v3) + rol18(xxh.v4) - } else { - h32 += xxh.seed + prime32_5 - } - - p := 0 - n := xxh.bufused - buf := xxh.buf - for n := n - 4; p <= n; p += 4 { - h32 += binary.LittleEndian.Uint32(buf[p:p+4]) * prime32_3 - h32 = rol17(h32) * prime32_4 - } - for ; p < n; p++ { - h32 += uint32(buf[p]) * prime32_5 - h32 = rol11(h32) * prime32_1 - } - - h32 ^= h32 >> 15 - h32 *= prime32_2 - h32 ^= h32 >> 13 - h32 *= prime32_3 - h32 ^= h32 >> 16 - - return h32 -} - -// Checksum returns the 32bits Hash value. -func Checksum(input []byte, seed uint32) uint32 { - n := len(input) - h32 := uint32(n) - - if n < 16 { - h32 += seed + prime32_5 - } else { - v1 := seed + prime32_1 + prime32_2 - v2 := seed + prime32_2 - v3 := seed - v4 := seed - prime32_1 - p := 0 - for n := n - 16; p <= n; p += 16 { - sub := input[p:][:16] //BCE hint for compiler - v1 = rol13(v1+binary.LittleEndian.Uint32(sub[:])*prime32_2) * prime32_1 - v2 = rol13(v2+binary.LittleEndian.Uint32(sub[4:])*prime32_2) * prime32_1 - v3 = rol13(v3+binary.LittleEndian.Uint32(sub[8:])*prime32_2) * prime32_1 - v4 = rol13(v4+binary.LittleEndian.Uint32(sub[12:])*prime32_2) * prime32_1 - } - input = input[p:] - n -= p - h32 += rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) - } - - p := 0 - for n := n - 4; p <= n; p += 4 { - h32 += binary.LittleEndian.Uint32(input[p:p+4]) * prime32_3 - h32 = rol17(h32) * prime32_4 - } - for p < n { - h32 += uint32(input[p]) * prime32_5 - h32 = rol11(h32) * prime32_1 - p++ - } - - h32 ^= h32 >> 15 - h32 *= prime32_2 - h32 ^= h32 >> 13 - h32 *= prime32_3 - h32 ^= h32 >> 16 - - return h32 -} - -func rol1(u uint32) uint32 { - return u<<1 | u>>31 -} - -func rol7(u uint32) uint32 { - return u<<7 | u>>25 -} - -func rol11(u uint32) uint32 { - return u<<11 | u>>21 -} - -func rol12(u uint32) uint32 { - return u<<12 | u>>20 -} - -func rol13(u uint32) uint32 { - return u<<13 | u>>19 -} - -func rol17(u uint32) uint32 { - return u<<17 | u>>15 -} - -func rol18(u uint32) uint32 { - return u<<18 | u>>14 -} - -// Uint32 hashes x with the given seed. -func Uint32(x, seed uint32) uint32 { - h := seed + prime32_5 + 4 + x*prime32_3 - h = rol17(h) * prime32_4 - h ^= h >> 15 - h *= prime32_2 - h ^= h >> 13 - h *= prime32_3 - h ^= h >> 16 - return h -} diff --git a/vendor/github.com/pierrec/lz4/internal/xxh32/xxh32zero.go b/vendor/github.com/pierrec/lz4/internal/xxh32/xxh32zero.go index 6eff850a626..850a6fdf614 100644 --- a/vendor/github.com/pierrec/lz4/internal/xxh32/xxh32zero.go +++ b/vendor/github.com/pierrec/lz4/internal/xxh32/xxh32zero.go @@ -6,6 +6,17 @@ import ( "encoding/binary" ) +const ( + prime32_1 uint32 = 2654435761 + prime32_2 uint32 = 2246822519 + prime32_3 uint32 = 3266489917 + prime32_4 uint32 = 668265263 + prime32_5 uint32 = 374761393 + + prime32_1plus2 uint32 = 606290984 + prime32_minus1 uint32 = 1640531535 +) + // XXHZero represents an xxhash32 object with seed 0. type XXHZero struct { v1 uint32 @@ -47,6 +58,9 @@ func (xxh *XXHZero) BlockSize() int { // Write adds input bytes to the Hash. // It never returns an error. func (xxh *XXHZero) Write(input []byte) (int, error) { + if xxh.totalLen == 0 { + xxh.Reset() + } n := len(input) m := xxh.bufused @@ -59,9 +73,9 @@ func (xxh *XXHZero) Write(input []byte) (int, error) { return n, nil } + p := 0 // Causes compiler to work directly from registers instead of stack: v1, v2, v3, v4 := xxh.v1, xxh.v2, xxh.v3, xxh.v4 - p := 0 if m > 0 { // some data left from previous update copy(xxh.buf[xxh.bufused:], input[:r]) @@ -69,10 +83,10 @@ func (xxh *XXHZero) Write(input []byte) (int, error) { // fast rotl(13) buf := xxh.buf[:16] // BCE hint. - xxh.v1 = rol13(v1+binary.LittleEndian.Uint32(buf[:])*prime32_2) * prime32_1 - xxh.v2 = rol13(v2+binary.LittleEndian.Uint32(buf[4:])*prime32_2) * prime32_1 - xxh.v3 = rol13(v3+binary.LittleEndian.Uint32(buf[8:])*prime32_2) * prime32_1 - xxh.v4 = rol13(v4+binary.LittleEndian.Uint32(buf[12:])*prime32_2) * prime32_1 + v1 = rol13(v1+binary.LittleEndian.Uint32(buf[:])*prime32_2) * prime32_1 + v2 = rol13(v2+binary.LittleEndian.Uint32(buf[4:])*prime32_2) * prime32_1 + v3 = rol13(v3+binary.LittleEndian.Uint32(buf[8:])*prime32_2) * prime32_1 + v4 = rol13(v4+binary.LittleEndian.Uint32(buf[12:])*prime32_2) * prime32_1 p = r xxh.bufused = 0 } @@ -178,3 +192,31 @@ func Uint32Zero(x uint32) uint32 { h ^= h >> 16 return h } + +func rol1(u uint32) uint32 { + return u<<1 | u>>31 +} + +func rol7(u uint32) uint32 { + return u<<7 | u>>25 +} + +func rol11(u uint32) uint32 { + return u<<11 | u>>21 +} + +func rol12(u uint32) uint32 { + return u<<12 | u>>20 +} + +func rol13(u uint32) uint32 { + return u<<13 | u>>19 +} + +func rol17(u uint32) uint32 { + return u<<17 | u>>15 +} + +func rol18(u uint32) uint32 { + return u<<18 | u>>14 +} diff --git a/vendor/github.com/pierrec/lz4/reader.go b/vendor/github.com/pierrec/lz4/reader.go index c7656760198..f08db47df7b 100644 --- a/vendor/github.com/pierrec/lz4/reader.go +++ b/vendor/github.com/pierrec/lz4/reader.go @@ -94,7 +94,9 @@ func (z *Reader) readHeader(first bool) error { if n := 2 * bSize; cap(z.zdata) < n { z.zdata = make([]byte, n, n) } - debug("header block max size id=%d size=%d", bmsID, bSize) + if debugFlag { + debug("header block max size id=%d size=%d", bmsID, bSize) + } z.zdata = z.zdata[:bSize] z.data = z.zdata[:cap(z.zdata)][bSize:] z.idx = len(z.data) @@ -121,7 +123,9 @@ func (z *Reader) readHeader(first bool) error { } z.Header.done = true - debug("header read: %v", z.Header) + if debugFlag { + debug("header read: %v", z.Header) + } return nil } @@ -132,13 +136,17 @@ func (z *Reader) readHeader(first bool) error { // change between calls to Read(). If that is the case, no data is actually read from // the underlying io.Reader, to allow for potential input buffer resizing. func (z *Reader) Read(buf []byte) (int, error) { - debug("Read buf len=%d", len(buf)) + if debugFlag { + debug("Read buf len=%d", len(buf)) + } if !z.Header.done { if err := z.readHeader(true); err != nil { return 0, err } - debug("header read OK compressed buffer %d / %d uncompressed buffer %d : %d index=%d", - len(z.zdata), cap(z.zdata), len(z.data), cap(z.data), z.idx) + if debugFlag { + debug("header read OK compressed buffer %d / %d uncompressed buffer %d : %d index=%d", + len(z.zdata), cap(z.zdata), len(z.data), cap(z.data), z.idx) + } } if len(buf) == 0 { @@ -147,7 +155,9 @@ func (z *Reader) Read(buf []byte) (int, error) { if z.idx == len(z.data) { // No data ready for reading, process the next block. - debug("reading block from writer") + if debugFlag { + debug("reading block from writer") + } // Block length: 0 = end of frame, highest bit set: uncompressed. bLen, err := z.readUint32() if err != nil { @@ -163,7 +173,9 @@ func (z *Reader) Read(buf []byte) (int, error) { if err != nil { return 0, err } - debug("frame checksum got=%x / want=%x", z.checksum.Sum32(), checksum) + if debugFlag { + debug("frame checksum got=%x / want=%x", z.checksum.Sum32(), checksum) + } z.pos += 4 if h := z.checksum.Sum32(); checksum != h { return 0, fmt.Errorf("lz4: invalid frame checksum: got %x; expected %x", h, checksum) @@ -179,11 +191,15 @@ func (z *Reader) Read(buf []byte) (int, error) { return 0, z.readHeader(false) } - debug("raw block size %d", bLen) + if debugFlag { + debug("raw block size %d", bLen) + } if bLen&compressedBlockFlag > 0 { // Uncompressed block. bLen &= compressedBlockMask - debug("uncompressed block size %d", bLen) + if debugFlag { + debug("uncompressed block size %d", bLen) + } if int(bLen) > cap(z.data) { return 0, fmt.Errorf("lz4: invalid block size: %d", bLen) } @@ -207,7 +223,9 @@ func (z *Reader) Read(buf []byte) (int, error) { } else { // Compressed block. - debug("compressed block size %d", bLen) + if debugFlag { + debug("compressed block size %d", bLen) + } if int(bLen) > cap(z.data) { return 0, fmt.Errorf("lz4: invalid block size: %d", bLen) } @@ -238,14 +256,18 @@ func (z *Reader) Read(buf []byte) (int, error) { if !z.NoChecksum { z.checksum.Write(z.data) - debug("current frame checksum %x", z.checksum.Sum32()) + if debugFlag { + debug("current frame checksum %x", z.checksum.Sum32()) + } } z.idx = 0 } n := copy(buf, z.data[z.idx:]) z.idx += n - debug("copied %d bytes to input", n) + if debugFlag { + debug("copied %d bytes to input", n) + } return n, nil } diff --git a/vendor/github.com/pierrec/lz4/writer.go b/vendor/github.com/pierrec/lz4/writer.go index 62a561703c5..0120438025d 100644 --- a/vendor/github.com/pierrec/lz4/writer.go +++ b/vendor/github.com/pierrec/lz4/writer.go @@ -86,7 +86,9 @@ func (z *Writer) writeHeader() error { return err } z.Header.done = true - debug("wrote header %v", z.Header) + if debugFlag { + debug("wrote header %v", z.Header) + } return nil } @@ -99,24 +101,36 @@ func (z *Writer) Write(buf []byte) (int, error) { return 0, err } } - - if !z.NoChecksum { - z.checksum.Write(buf) + if debugFlag { + debug("input buffer len=%d index=%d", len(buf), z.idx) } - debug("input buffer len=%d index=%d", len(buf), z.idx) + zn := len(z.data) var n int for len(buf) > 0 { + if z.idx == 0 && len(buf) >= zn { + // Avoid a copy as there is enough data for a block. + if err := z.compressBlock(buf[:zn]); err != nil { + return n, err + } + n += zn + buf = buf[zn:] + continue + } // Accumulate the data to be compressed. m := copy(z.data[z.idx:], buf) n += m z.idx += m buf = buf[m:] - debug("%d bytes copied to buf, current index %d", n, z.idx) + if debugFlag { + debug("%d bytes copied to buf, current index %d", n, z.idx) + } if z.idx < len(z.data) { // Buffer not filled. - debug("need more data for compression") + if debugFlag { + debug("need more data for compression") + } return n, nil } @@ -132,6 +146,10 @@ func (z *Writer) Write(buf []byte) (int, error) { // compressBlock compresses a block. func (z *Writer) compressBlock(data []byte) error { + if !z.NoChecksum { + z.checksum.Write(data) + } + // The compressed block size cannot exceed the input's. var zn int var err error @@ -144,7 +162,9 @@ func (z *Writer) compressBlock(data []byte) error { var zdata []byte var bLen uint32 - debug("block compression %d => %d", len(data), zn) + if debugFlag { + debug("block compression %d => %d", len(data), zn) + } if err == nil && zn > 0 && zn < len(data) { // Compressible and compressed size smaller than uncompressed: ok! bLen = uint32(zn) @@ -154,7 +174,9 @@ func (z *Writer) compressBlock(data []byte) error { bLen = uint32(len(data)) | compressedBlockFlag zdata = data } - debug("block compression to be written len=%d data len=%d", bLen, len(zdata)) + if debugFlag { + debug("block compression to be written len=%d data len=%d", bLen, len(zdata)) + } // Write the block. if err := z.writeUint32(bLen); err != nil { @@ -166,12 +188,16 @@ func (z *Writer) compressBlock(data []byte) error { if z.BlockChecksum { checksum := xxh32.ChecksumZero(zdata) - debug("block checksum %x", checksum) + if debugFlag { + debug("block checksum %x", checksum) + } if err := z.writeUint32(checksum); err != nil { return err } } - debug("current frame checksum %x", z.checksum.Sum32()) + if debugFlag { + debug("current frame checksum %x", z.checksum.Sum32()) + } return nil } @@ -180,7 +206,9 @@ func (z *Writer) compressBlock(data []byte) error { // Flush does not return until the data has been written. // If the underlying writer returns an error, Flush returns that error. func (z *Writer) Flush() error { - debug("flush with index %d", z.idx) + if debugFlag { + debug("flush with index %d", z.idx) + } if z.idx == 0 { return nil } @@ -200,13 +228,17 @@ func (z *Writer) Close() error { return err } - debug("writing last empty block") + if debugFlag { + debug("writing last empty block") + } if err := z.writeUint32(0); err != nil { return err } if !z.NoChecksum { checksum := z.checksum.Sum32() - debug("stream checksum %x", checksum) + if debugFlag { + debug("stream checksum %x", checksum) + } if err := z.writeUint32(checksum); err != nil { return err } diff --git a/vendor/github.com/rcrowley/go-metrics/meter.go b/vendor/github.com/rcrowley/go-metrics/meter.go index 7807406a3be..223669bcb29 100644 --- a/vendor/github.com/rcrowley/go-metrics/meter.go +++ b/vendor/github.com/rcrowley/go-metrics/meter.go @@ -126,8 +126,6 @@ func (NilMeter) Stop() {} // StandardMeter is the standard implementation of a Meter. type StandardMeter struct { - // Only used on stop. - lock sync.Mutex snapshot *MeterSnapshot a1, a5, a15 EWMA startTime time.Time @@ -146,11 +144,7 @@ func newStandardMeter() *StandardMeter { // Stop stops the meter, Mark() will be a no-op if you use it after being stopped. func (m *StandardMeter) Stop() { - m.lock.Lock() - stopped := m.stopped - m.stopped = 1 - m.lock.Unlock() - if stopped != 1 { + if atomic.CompareAndSwapUint32(&m.stopped, 0, 1) { arbiter.Lock() delete(arbiter.meters, m) arbiter.Unlock() diff --git a/vendor/github.com/sergi/go-diff/AUTHORS b/vendor/github.com/sergi/go-diff/AUTHORS new file mode 100644 index 00000000000..2d7bb2bf572 --- /dev/null +++ b/vendor/github.com/sergi/go-diff/AUTHORS @@ -0,0 +1,25 @@ +# This is the official list of go-diff authors for copyright purposes. +# This file is distinct from the CONTRIBUTORS files. +# See the latter for an explanation. + +# Names should be added to this file as +# Name or Organization +# The email address is not required for organizations. + +# Please keep the list sorted. + +Danny Yoo +James Kolb +Jonathan Amsterdam +Markus Zimmermann +Matt Kovars +Örjan Persson +Osman Masood +Robert Carlsen +Rory Flynn +Sergi Mansilla +Shatrugna Sadhu +Shawn Smith +Stas Maksimov +Tor Arvid Lund +Zac Bergquist diff --git a/vendor/github.com/sergi/go-diff/CONTRIBUTORS b/vendor/github.com/sergi/go-diff/CONTRIBUTORS new file mode 100644 index 00000000000..369e3d55190 --- /dev/null +++ b/vendor/github.com/sergi/go-diff/CONTRIBUTORS @@ -0,0 +1,32 @@ +# This is the official list of people who can contribute +# (and typically have contributed) code to the go-diff +# repository. +# +# The AUTHORS file lists the copyright holders; this file +# lists people. For example, ACME Inc. employees would be listed here +# but not in AUTHORS, because ACME Inc. would hold the copyright. +# +# When adding J Random Contributor's name to this file, +# either J's name or J's organization's name should be +# added to the AUTHORS file. +# +# Names should be added to this file like so: +# Name +# +# Please keep the list sorted. + +Danny Yoo +James Kolb +Jonathan Amsterdam +Markus Zimmermann +Matt Kovars +Örjan Persson +Osman Masood +Robert Carlsen +Rory Flynn +Sergi Mansilla +Shatrugna Sadhu +Shawn Smith +Stas Maksimov +Tor Arvid Lund +Zac Bergquist diff --git a/vendor/github.com/sergi/go-diff/LICENSE b/vendor/github.com/sergi/go-diff/LICENSE new file mode 100644 index 00000000000..937942c2b2c --- /dev/null +++ b/vendor/github.com/sergi/go-diff/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2012-2016 The go-diff Authors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + diff --git a/vendor/github.com/sergi/go-diff/diffmatchpatch/diff.go b/vendor/github.com/sergi/go-diff/diffmatchpatch/diff.go new file mode 100644 index 00000000000..82ad7bc8f1c --- /dev/null +++ b/vendor/github.com/sergi/go-diff/diffmatchpatch/diff.go @@ -0,0 +1,1344 @@ +// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. +// https://github.com/sergi/go-diff +// See the included LICENSE file for license details. +// +// go-diff is a Go implementation of Google's Diff, Match, and Patch library +// Original library is Copyright (c) 2006 Google Inc. +// http://code.google.com/p/google-diff-match-patch/ + +package diffmatchpatch + +import ( + "bytes" + "errors" + "fmt" + "html" + "math" + "net/url" + "regexp" + "strconv" + "strings" + "time" + "unicode/utf8" +) + +// Operation defines the operation of a diff item. +type Operation int8 + +const ( + // DiffDelete item represents a delete diff. + DiffDelete Operation = -1 + // DiffInsert item represents an insert diff. + DiffInsert Operation = 1 + // DiffEqual item represents an equal diff. + DiffEqual Operation = 0 +) + +// Diff represents one diff operation +type Diff struct { + Type Operation + Text string +} + +func splice(slice []Diff, index int, amount int, elements ...Diff) []Diff { + return append(slice[:index], append(elements, slice[index+amount:]...)...) +} + +// DiffMain finds the differences between two texts. +// If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character. +func (dmp *DiffMatchPatch) DiffMain(text1, text2 string, checklines bool) []Diff { + return dmp.DiffMainRunes([]rune(text1), []rune(text2), checklines) +} + +// DiffMainRunes finds the differences between two rune sequences. +// If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character. +func (dmp *DiffMatchPatch) DiffMainRunes(text1, text2 []rune, checklines bool) []Diff { + var deadline time.Time + if dmp.DiffTimeout > 0 { + deadline = time.Now().Add(dmp.DiffTimeout) + } + return dmp.diffMainRunes(text1, text2, checklines, deadline) +} + +func (dmp *DiffMatchPatch) diffMainRunes(text1, text2 []rune, checklines bool, deadline time.Time) []Diff { + if runesEqual(text1, text2) { + var diffs []Diff + if len(text1) > 0 { + diffs = append(diffs, Diff{DiffEqual, string(text1)}) + } + return diffs + } + // Trim off common prefix (speedup). + commonlength := commonPrefixLength(text1, text2) + commonprefix := text1[:commonlength] + text1 = text1[commonlength:] + text2 = text2[commonlength:] + + // Trim off common suffix (speedup). + commonlength = commonSuffixLength(text1, text2) + commonsuffix := text1[len(text1)-commonlength:] + text1 = text1[:len(text1)-commonlength] + text2 = text2[:len(text2)-commonlength] + + // Compute the diff on the middle block. + diffs := dmp.diffCompute(text1, text2, checklines, deadline) + + // Restore the prefix and suffix. + if len(commonprefix) != 0 { + diffs = append([]Diff{Diff{DiffEqual, string(commonprefix)}}, diffs...) + } + if len(commonsuffix) != 0 { + diffs = append(diffs, Diff{DiffEqual, string(commonsuffix)}) + } + + return dmp.DiffCleanupMerge(diffs) +} + +// diffCompute finds the differences between two rune slices. Assumes that the texts do not have any common prefix or suffix. +func (dmp *DiffMatchPatch) diffCompute(text1, text2 []rune, checklines bool, deadline time.Time) []Diff { + diffs := []Diff{} + if len(text1) == 0 { + // Just add some text (speedup). + return append(diffs, Diff{DiffInsert, string(text2)}) + } else if len(text2) == 0 { + // Just delete some text (speedup). + return append(diffs, Diff{DiffDelete, string(text1)}) + } + + var longtext, shorttext []rune + if len(text1) > len(text2) { + longtext = text1 + shorttext = text2 + } else { + longtext = text2 + shorttext = text1 + } + + if i := runesIndex(longtext, shorttext); i != -1 { + op := DiffInsert + // Swap insertions for deletions if diff is reversed. + if len(text1) > len(text2) { + op = DiffDelete + } + // Shorter text is inside the longer text (speedup). + return []Diff{ + Diff{op, string(longtext[:i])}, + Diff{DiffEqual, string(shorttext)}, + Diff{op, string(longtext[i+len(shorttext):])}, + } + } else if len(shorttext) == 1 { + // Single character string. + // After the previous speedup, the character can't be an equality. + return []Diff{ + Diff{DiffDelete, string(text1)}, + Diff{DiffInsert, string(text2)}, + } + // Check to see if the problem can be split in two. + } else if hm := dmp.diffHalfMatch(text1, text2); hm != nil { + // A half-match was found, sort out the return data. + text1A := hm[0] + text1B := hm[1] + text2A := hm[2] + text2B := hm[3] + midCommon := hm[4] + // Send both pairs off for separate processing. + diffsA := dmp.diffMainRunes(text1A, text2A, checklines, deadline) + diffsB := dmp.diffMainRunes(text1B, text2B, checklines, deadline) + // Merge the results. + return append(diffsA, append([]Diff{Diff{DiffEqual, string(midCommon)}}, diffsB...)...) + } else if checklines && len(text1) > 100 && len(text2) > 100 { + return dmp.diffLineMode(text1, text2, deadline) + } + return dmp.diffBisect(text1, text2, deadline) +} + +// diffLineMode does a quick line-level diff on both []runes, then rediff the parts for greater accuracy. This speedup can produce non-minimal diffs. +func (dmp *DiffMatchPatch) diffLineMode(text1, text2 []rune, deadline time.Time) []Diff { + // Scan the text on a line-by-line basis first. + text1, text2, linearray := dmp.diffLinesToRunes(text1, text2) + + diffs := dmp.diffMainRunes(text1, text2, false, deadline) + + // Convert the diff back to original text. + diffs = dmp.DiffCharsToLines(diffs, linearray) + // Eliminate freak matches (e.g. blank lines) + diffs = dmp.DiffCleanupSemantic(diffs) + + // Rediff any replacement blocks, this time character-by-character. + // Add a dummy entry at the end. + diffs = append(diffs, Diff{DiffEqual, ""}) + + pointer := 0 + countDelete := 0 + countInsert := 0 + + // NOTE: Rune slices are slower than using strings in this case. + textDelete := "" + textInsert := "" + + for pointer < len(diffs) { + switch diffs[pointer].Type { + case DiffInsert: + countInsert++ + textInsert += diffs[pointer].Text + case DiffDelete: + countDelete++ + textDelete += diffs[pointer].Text + case DiffEqual: + // Upon reaching an equality, check for prior redundancies. + if countDelete >= 1 && countInsert >= 1 { + // Delete the offending records and add the merged ones. + diffs = splice(diffs, pointer-countDelete-countInsert, + countDelete+countInsert) + + pointer = pointer - countDelete - countInsert + a := dmp.diffMainRunes([]rune(textDelete), []rune(textInsert), false, deadline) + for j := len(a) - 1; j >= 0; j-- { + diffs = splice(diffs, pointer, 0, a[j]) + } + pointer = pointer + len(a) + } + + countInsert = 0 + countDelete = 0 + textDelete = "" + textInsert = "" + } + pointer++ + } + + return diffs[:len(diffs)-1] // Remove the dummy entry at the end. +} + +// DiffBisect finds the 'middle snake' of a diff, split the problem in two and return the recursively constructed diff. +// If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character. +// See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. +func (dmp *DiffMatchPatch) DiffBisect(text1, text2 string, deadline time.Time) []Diff { + // Unused in this code, but retained for interface compatibility. + return dmp.diffBisect([]rune(text1), []rune(text2), deadline) +} + +// diffBisect finds the 'middle snake' of a diff, splits the problem in two and returns the recursively constructed diff. +// See Myers's 1986 paper: An O(ND) Difference Algorithm and Its Variations. +func (dmp *DiffMatchPatch) diffBisect(runes1, runes2 []rune, deadline time.Time) []Diff { + // Cache the text lengths to prevent multiple calls. + runes1Len, runes2Len := len(runes1), len(runes2) + + maxD := (runes1Len + runes2Len + 1) / 2 + vOffset := maxD + vLength := 2 * maxD + + v1 := make([]int, vLength) + v2 := make([]int, vLength) + for i := range v1 { + v1[i] = -1 + v2[i] = -1 + } + v1[vOffset+1] = 0 + v2[vOffset+1] = 0 + + delta := runes1Len - runes2Len + // If the total number of characters is odd, then the front path will collide with the reverse path. + front := (delta%2 != 0) + // Offsets for start and end of k loop. Prevents mapping of space beyond the grid. + k1start := 0 + k1end := 0 + k2start := 0 + k2end := 0 + for d := 0; d < maxD; d++ { + // Bail out if deadline is reached. + if !deadline.IsZero() && time.Now().After(deadline) { + break + } + + // Walk the front path one step. + for k1 := -d + k1start; k1 <= d-k1end; k1 += 2 { + k1Offset := vOffset + k1 + var x1 int + + if k1 == -d || (k1 != d && v1[k1Offset-1] < v1[k1Offset+1]) { + x1 = v1[k1Offset+1] + } else { + x1 = v1[k1Offset-1] + 1 + } + + y1 := x1 - k1 + for x1 < runes1Len && y1 < runes2Len { + if runes1[x1] != runes2[y1] { + break + } + x1++ + y1++ + } + v1[k1Offset] = x1 + if x1 > runes1Len { + // Ran off the right of the graph. + k1end += 2 + } else if y1 > runes2Len { + // Ran off the bottom of the graph. + k1start += 2 + } else if front { + k2Offset := vOffset + delta - k1 + if k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] != -1 { + // Mirror x2 onto top-left coordinate system. + x2 := runes1Len - v2[k2Offset] + if x1 >= x2 { + // Overlap detected. + return dmp.diffBisectSplit(runes1, runes2, x1, y1, deadline) + } + } + } + } + // Walk the reverse path one step. + for k2 := -d + k2start; k2 <= d-k2end; k2 += 2 { + k2Offset := vOffset + k2 + var x2 int + if k2 == -d || (k2 != d && v2[k2Offset-1] < v2[k2Offset+1]) { + x2 = v2[k2Offset+1] + } else { + x2 = v2[k2Offset-1] + 1 + } + var y2 = x2 - k2 + for x2 < runes1Len && y2 < runes2Len { + if runes1[runes1Len-x2-1] != runes2[runes2Len-y2-1] { + break + } + x2++ + y2++ + } + v2[k2Offset] = x2 + if x2 > runes1Len { + // Ran off the left of the graph. + k2end += 2 + } else if y2 > runes2Len { + // Ran off the top of the graph. + k2start += 2 + } else if !front { + k1Offset := vOffset + delta - k2 + if k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] != -1 { + x1 := v1[k1Offset] + y1 := vOffset + x1 - k1Offset + // Mirror x2 onto top-left coordinate system. + x2 = runes1Len - x2 + if x1 >= x2 { + // Overlap detected. + return dmp.diffBisectSplit(runes1, runes2, x1, y1, deadline) + } + } + } + } + } + // Diff took too long and hit the deadline or number of diffs equals number of characters, no commonality at all. + return []Diff{ + Diff{DiffDelete, string(runes1)}, + Diff{DiffInsert, string(runes2)}, + } +} + +func (dmp *DiffMatchPatch) diffBisectSplit(runes1, runes2 []rune, x, y int, + deadline time.Time) []Diff { + runes1a := runes1[:x] + runes2a := runes2[:y] + runes1b := runes1[x:] + runes2b := runes2[y:] + + // Compute both diffs serially. + diffs := dmp.diffMainRunes(runes1a, runes2a, false, deadline) + diffsb := dmp.diffMainRunes(runes1b, runes2b, false, deadline) + + return append(diffs, diffsb...) +} + +// DiffLinesToChars splits two texts into a list of strings, and educes the texts to a string of hashes where each Unicode character represents one line. +// It's slightly faster to call DiffLinesToRunes first, followed by DiffMainRunes. +func (dmp *DiffMatchPatch) DiffLinesToChars(text1, text2 string) (string, string, []string) { + chars1, chars2, lineArray := dmp.DiffLinesToRunes(text1, text2) + return string(chars1), string(chars2), lineArray +} + +// DiffLinesToRunes splits two texts into a list of runes. Each rune represents one line. +func (dmp *DiffMatchPatch) DiffLinesToRunes(text1, text2 string) ([]rune, []rune, []string) { + // '\x00' is a valid character, but various debuggers don't like it. So we'll insert a junk entry to avoid generating a null character. + lineArray := []string{""} // e.g. lineArray[4] == 'Hello\n' + lineHash := map[string]int{} // e.g. lineHash['Hello\n'] == 4 + + chars1 := dmp.diffLinesToRunesMunge(text1, &lineArray, lineHash) + chars2 := dmp.diffLinesToRunesMunge(text2, &lineArray, lineHash) + + return chars1, chars2, lineArray +} + +func (dmp *DiffMatchPatch) diffLinesToRunes(text1, text2 []rune) ([]rune, []rune, []string) { + return dmp.DiffLinesToRunes(string(text1), string(text2)) +} + +// diffLinesToRunesMunge splits a text into an array of strings, and reduces the texts to a []rune where each Unicode character represents one line. +// We use strings instead of []runes as input mainly because you can't use []rune as a map key. +func (dmp *DiffMatchPatch) diffLinesToRunesMunge(text string, lineArray *[]string, lineHash map[string]int) []rune { + // Walk the text, pulling out a substring for each line. text.split('\n') would would temporarily double our memory footprint. Modifying text would create many large strings to garbage collect. + lineStart := 0 + lineEnd := -1 + runes := []rune{} + + for lineEnd < len(text)-1 { + lineEnd = indexOf(text, "\n", lineStart) + + if lineEnd == -1 { + lineEnd = len(text) - 1 + } + + line := text[lineStart : lineEnd+1] + lineStart = lineEnd + 1 + lineValue, ok := lineHash[line] + + if ok { + runes = append(runes, rune(lineValue)) + } else { + *lineArray = append(*lineArray, line) + lineHash[line] = len(*lineArray) - 1 + runes = append(runes, rune(len(*lineArray)-1)) + } + } + + return runes +} + +// DiffCharsToLines rehydrates the text in a diff from a string of line hashes to real lines of text. +func (dmp *DiffMatchPatch) DiffCharsToLines(diffs []Diff, lineArray []string) []Diff { + hydrated := make([]Diff, 0, len(diffs)) + for _, aDiff := range diffs { + chars := aDiff.Text + text := make([]string, len(chars)) + + for i, r := range chars { + text[i] = lineArray[r] + } + + aDiff.Text = strings.Join(text, "") + hydrated = append(hydrated, aDiff) + } + return hydrated +} + +// DiffCommonPrefix determines the common prefix length of two strings. +func (dmp *DiffMatchPatch) DiffCommonPrefix(text1, text2 string) int { + // Unused in this code, but retained for interface compatibility. + return commonPrefixLength([]rune(text1), []rune(text2)) +} + +// DiffCommonSuffix determines the common suffix length of two strings. +func (dmp *DiffMatchPatch) DiffCommonSuffix(text1, text2 string) int { + // Unused in this code, but retained for interface compatibility. + return commonSuffixLength([]rune(text1), []rune(text2)) +} + +// commonPrefixLength returns the length of the common prefix of two rune slices. +func commonPrefixLength(text1, text2 []rune) int { + short, long := text1, text2 + if len(short) > len(long) { + short, long = long, short + } + for i, r := range short { + if r != long[i] { + return i + } + } + return len(short) +} + +// commonSuffixLength returns the length of the common suffix of two rune slices. +func commonSuffixLength(text1, text2 []rune) int { + n := min(len(text1), len(text2)) + for i := 0; i < n; i++ { + if text1[len(text1)-i-1] != text2[len(text2)-i-1] { + return i + } + } + return n + + // TODO research and benchmark this, why is it not activated? https://github.com/sergi/go-diff/issues/54 + // Binary search. + // Performance analysis: http://neil.fraser.name/news/2007/10/09/ + /* + pointermin := 0 + pointermax := math.Min(len(text1), len(text2)) + pointermid := pointermax + pointerend := 0 + for pointermin < pointermid { + if text1[len(text1)-pointermid:len(text1)-pointerend] == + text2[len(text2)-pointermid:len(text2)-pointerend] { + pointermin = pointermid + pointerend = pointermin + } else { + pointermax = pointermid + } + pointermid = math.Floor((pointermax-pointermin)/2 + pointermin) + } + return pointermid + */ +} + +// DiffCommonOverlap determines if the suffix of one string is the prefix of another. +func (dmp *DiffMatchPatch) DiffCommonOverlap(text1 string, text2 string) int { + // Cache the text lengths to prevent multiple calls. + text1Length := len(text1) + text2Length := len(text2) + // Eliminate the null case. + if text1Length == 0 || text2Length == 0 { + return 0 + } + // Truncate the longer string. + if text1Length > text2Length { + text1 = text1[text1Length-text2Length:] + } else if text1Length < text2Length { + text2 = text2[0:text1Length] + } + textLength := int(math.Min(float64(text1Length), float64(text2Length))) + // Quick check for the worst case. + if text1 == text2 { + return textLength + } + + // Start by looking for a single character match and increase length until no match is found. Performance analysis: http://neil.fraser.name/news/2010/11/04/ + best := 0 + length := 1 + for { + pattern := text1[textLength-length:] + found := strings.Index(text2, pattern) + if found == -1 { + break + } + length += found + if found == 0 || text1[textLength-length:] == text2[0:length] { + best = length + length++ + } + } + + return best +} + +// DiffHalfMatch checks whether the two texts share a substring which is at least half the length of the longer text. This speedup can produce non-minimal diffs. +func (dmp *DiffMatchPatch) DiffHalfMatch(text1, text2 string) []string { + // Unused in this code, but retained for interface compatibility. + runeSlices := dmp.diffHalfMatch([]rune(text1), []rune(text2)) + if runeSlices == nil { + return nil + } + + result := make([]string, len(runeSlices)) + for i, r := range runeSlices { + result[i] = string(r) + } + return result +} + +func (dmp *DiffMatchPatch) diffHalfMatch(text1, text2 []rune) [][]rune { + if dmp.DiffTimeout <= 0 { + // Don't risk returning a non-optimal diff if we have unlimited time. + return nil + } + + var longtext, shorttext []rune + if len(text1) > len(text2) { + longtext = text1 + shorttext = text2 + } else { + longtext = text2 + shorttext = text1 + } + + if len(longtext) < 4 || len(shorttext)*2 < len(longtext) { + return nil // Pointless. + } + + // First check if the second quarter is the seed for a half-match. + hm1 := dmp.diffHalfMatchI(longtext, shorttext, int(float64(len(longtext)+3)/4)) + + // Check again based on the third quarter. + hm2 := dmp.diffHalfMatchI(longtext, shorttext, int(float64(len(longtext)+1)/2)) + + hm := [][]rune{} + if hm1 == nil && hm2 == nil { + return nil + } else if hm2 == nil { + hm = hm1 + } else if hm1 == nil { + hm = hm2 + } else { + // Both matched. Select the longest. + if len(hm1[4]) > len(hm2[4]) { + hm = hm1 + } else { + hm = hm2 + } + } + + // A half-match was found, sort out the return data. + if len(text1) > len(text2) { + return hm + } + + return [][]rune{hm[2], hm[3], hm[0], hm[1], hm[4]} +} + +// diffHalfMatchI checks if a substring of shorttext exist within longtext such that the substring is at least half the length of longtext? +// Returns a slice containing the prefix of longtext, the suffix of longtext, the prefix of shorttext, the suffix of shorttext and the common middle, or null if there was no match. +func (dmp *DiffMatchPatch) diffHalfMatchI(l, s []rune, i int) [][]rune { + var bestCommonA []rune + var bestCommonB []rune + var bestCommonLen int + var bestLongtextA []rune + var bestLongtextB []rune + var bestShorttextA []rune + var bestShorttextB []rune + + // Start with a 1/4 length substring at position i as a seed. + seed := l[i : i+len(l)/4] + + for j := runesIndexOf(s, seed, 0); j != -1; j = runesIndexOf(s, seed, j+1) { + prefixLength := commonPrefixLength(l[i:], s[j:]) + suffixLength := commonSuffixLength(l[:i], s[:j]) + + if bestCommonLen < suffixLength+prefixLength { + bestCommonA = s[j-suffixLength : j] + bestCommonB = s[j : j+prefixLength] + bestCommonLen = len(bestCommonA) + len(bestCommonB) + bestLongtextA = l[:i-suffixLength] + bestLongtextB = l[i+prefixLength:] + bestShorttextA = s[:j-suffixLength] + bestShorttextB = s[j+prefixLength:] + } + } + + if bestCommonLen*2 < len(l) { + return nil + } + + return [][]rune{ + bestLongtextA, + bestLongtextB, + bestShorttextA, + bestShorttextB, + append(bestCommonA, bestCommonB...), + } +} + +// DiffCleanupSemantic reduces the number of edits by eliminating semantically trivial equalities. +func (dmp *DiffMatchPatch) DiffCleanupSemantic(diffs []Diff) []Diff { + changes := false + // Stack of indices where equalities are found. + type equality struct { + data int + next *equality + } + var equalities *equality + + var lastequality string + // Always equal to diffs[equalities[equalitiesLength - 1]][1] + var pointer int // Index of current position. + // Number of characters that changed prior to the equality. + var lengthInsertions1, lengthDeletions1 int + // Number of characters that changed after the equality. + var lengthInsertions2, lengthDeletions2 int + + for pointer < len(diffs) { + if diffs[pointer].Type == DiffEqual { + // Equality found. + + equalities = &equality{ + data: pointer, + next: equalities, + } + lengthInsertions1 = lengthInsertions2 + lengthDeletions1 = lengthDeletions2 + lengthInsertions2 = 0 + lengthDeletions2 = 0 + lastequality = diffs[pointer].Text + } else { + // An insertion or deletion. + + if diffs[pointer].Type == DiffInsert { + lengthInsertions2 += len(diffs[pointer].Text) + } else { + lengthDeletions2 += len(diffs[pointer].Text) + } + // Eliminate an equality that is smaller or equal to the edits on both sides of it. + difference1 := int(math.Max(float64(lengthInsertions1), float64(lengthDeletions1))) + difference2 := int(math.Max(float64(lengthInsertions2), float64(lengthDeletions2))) + if len(lastequality) > 0 && + (len(lastequality) <= difference1) && + (len(lastequality) <= difference2) { + // Duplicate record. + insPoint := equalities.data + diffs = append( + diffs[:insPoint], + append([]Diff{Diff{DiffDelete, lastequality}}, diffs[insPoint:]...)...) + + // Change second copy to insert. + diffs[insPoint+1].Type = DiffInsert + // Throw away the equality we just deleted. + equalities = equalities.next + + if equalities != nil { + equalities = equalities.next + } + if equalities != nil { + pointer = equalities.data + } else { + pointer = -1 + } + + lengthInsertions1 = 0 // Reset the counters. + lengthDeletions1 = 0 + lengthInsertions2 = 0 + lengthDeletions2 = 0 + lastequality = "" + changes = true + } + } + pointer++ + } + + // Normalize the diff. + if changes { + diffs = dmp.DiffCleanupMerge(diffs) + } + diffs = dmp.DiffCleanupSemanticLossless(diffs) + // Find any overlaps between deletions and insertions. + // e.g: abcxxxxxxdef + // -> abcxxxdef + // e.g: xxxabcdefxxx + // -> defxxxabc + // Only extract an overlap if it is as big as the edit ahead or behind it. + pointer = 1 + for pointer < len(diffs) { + if diffs[pointer-1].Type == DiffDelete && + diffs[pointer].Type == DiffInsert { + deletion := diffs[pointer-1].Text + insertion := diffs[pointer].Text + overlapLength1 := dmp.DiffCommonOverlap(deletion, insertion) + overlapLength2 := dmp.DiffCommonOverlap(insertion, deletion) + if overlapLength1 >= overlapLength2 { + if float64(overlapLength1) >= float64(len(deletion))/2 || + float64(overlapLength1) >= float64(len(insertion))/2 { + + // Overlap found. Insert an equality and trim the surrounding edits. + diffs = append( + diffs[:pointer], + append([]Diff{Diff{DiffEqual, insertion[:overlapLength1]}}, diffs[pointer:]...)...) + + diffs[pointer-1].Text = + deletion[0 : len(deletion)-overlapLength1] + diffs[pointer+1].Text = insertion[overlapLength1:] + pointer++ + } + } else { + if float64(overlapLength2) >= float64(len(deletion))/2 || + float64(overlapLength2) >= float64(len(insertion))/2 { + // Reverse overlap found. Insert an equality and swap and trim the surrounding edits. + overlap := Diff{DiffEqual, deletion[:overlapLength2]} + diffs = append( + diffs[:pointer], + append([]Diff{overlap}, diffs[pointer:]...)...) + + diffs[pointer-1].Type = DiffInsert + diffs[pointer-1].Text = insertion[0 : len(insertion)-overlapLength2] + diffs[pointer+1].Type = DiffDelete + diffs[pointer+1].Text = deletion[overlapLength2:] + pointer++ + } + } + pointer++ + } + pointer++ + } + + return diffs +} + +// Define some regex patterns for matching boundaries. +var ( + nonAlphaNumericRegex = regexp.MustCompile(`[^a-zA-Z0-9]`) + whitespaceRegex = regexp.MustCompile(`\s`) + linebreakRegex = regexp.MustCompile(`[\r\n]`) + blanklineEndRegex = regexp.MustCompile(`\n\r?\n$`) + blanklineStartRegex = regexp.MustCompile(`^\r?\n\r?\n`) +) + +// diffCleanupSemanticScore computes a score representing whether the internal boundary falls on logical boundaries. +// Scores range from 6 (best) to 0 (worst). Closure, but does not reference any external variables. +func diffCleanupSemanticScore(one, two string) int { + if len(one) == 0 || len(two) == 0 { + // Edges are the best. + return 6 + } + + // Each port of this function behaves slightly differently due to subtle differences in each language's definition of things like 'whitespace'. Since this function's purpose is largely cosmetic, the choice has been made to use each language's native features rather than force total conformity. + rune1, _ := utf8.DecodeLastRuneInString(one) + rune2, _ := utf8.DecodeRuneInString(two) + char1 := string(rune1) + char2 := string(rune2) + + nonAlphaNumeric1 := nonAlphaNumericRegex.MatchString(char1) + nonAlphaNumeric2 := nonAlphaNumericRegex.MatchString(char2) + whitespace1 := nonAlphaNumeric1 && whitespaceRegex.MatchString(char1) + whitespace2 := nonAlphaNumeric2 && whitespaceRegex.MatchString(char2) + lineBreak1 := whitespace1 && linebreakRegex.MatchString(char1) + lineBreak2 := whitespace2 && linebreakRegex.MatchString(char2) + blankLine1 := lineBreak1 && blanklineEndRegex.MatchString(one) + blankLine2 := lineBreak2 && blanklineEndRegex.MatchString(two) + + if blankLine1 || blankLine2 { + // Five points for blank lines. + return 5 + } else if lineBreak1 || lineBreak2 { + // Four points for line breaks. + return 4 + } else if nonAlphaNumeric1 && !whitespace1 && whitespace2 { + // Three points for end of sentences. + return 3 + } else if whitespace1 || whitespace2 { + // Two points for whitespace. + return 2 + } else if nonAlphaNumeric1 || nonAlphaNumeric2 { + // One point for non-alphanumeric. + return 1 + } + return 0 +} + +// DiffCleanupSemanticLossless looks for single edits surrounded on both sides by equalities which can be shifted sideways to align the edit to a word boundary. +// E.g: The cat came. -> The cat came. +func (dmp *DiffMatchPatch) DiffCleanupSemanticLossless(diffs []Diff) []Diff { + pointer := 1 + + // Intentionally ignore the first and last element (don't need checking). + for pointer < len(diffs)-1 { + if diffs[pointer-1].Type == DiffEqual && + diffs[pointer+1].Type == DiffEqual { + + // This is a single edit surrounded by equalities. + equality1 := diffs[pointer-1].Text + edit := diffs[pointer].Text + equality2 := diffs[pointer+1].Text + + // First, shift the edit as far left as possible. + commonOffset := dmp.DiffCommonSuffix(equality1, edit) + if commonOffset > 0 { + commonString := edit[len(edit)-commonOffset:] + equality1 = equality1[0 : len(equality1)-commonOffset] + edit = commonString + edit[:len(edit)-commonOffset] + equality2 = commonString + equality2 + } + + // Second, step character by character right, looking for the best fit. + bestEquality1 := equality1 + bestEdit := edit + bestEquality2 := equality2 + bestScore := diffCleanupSemanticScore(equality1, edit) + + diffCleanupSemanticScore(edit, equality2) + + for len(edit) != 0 && len(equality2) != 0 { + _, sz := utf8.DecodeRuneInString(edit) + if len(equality2) < sz || edit[:sz] != equality2[:sz] { + break + } + equality1 += edit[:sz] + edit = edit[sz:] + equality2[:sz] + equality2 = equality2[sz:] + score := diffCleanupSemanticScore(equality1, edit) + + diffCleanupSemanticScore(edit, equality2) + // The >= encourages trailing rather than leading whitespace on edits. + if score >= bestScore { + bestScore = score + bestEquality1 = equality1 + bestEdit = edit + bestEquality2 = equality2 + } + } + + if diffs[pointer-1].Text != bestEquality1 { + // We have an improvement, save it back to the diff. + if len(bestEquality1) != 0 { + diffs[pointer-1].Text = bestEquality1 + } else { + diffs = splice(diffs, pointer-1, 1) + pointer-- + } + + diffs[pointer].Text = bestEdit + if len(bestEquality2) != 0 { + diffs[pointer+1].Text = bestEquality2 + } else { + diffs = append(diffs[:pointer+1], diffs[pointer+2:]...) + pointer-- + } + } + } + pointer++ + } + + return diffs +} + +// DiffCleanupEfficiency reduces the number of edits by eliminating operationally trivial equalities. +func (dmp *DiffMatchPatch) DiffCleanupEfficiency(diffs []Diff) []Diff { + changes := false + // Stack of indices where equalities are found. + type equality struct { + data int + next *equality + } + var equalities *equality + // Always equal to equalities[equalitiesLength-1][1] + lastequality := "" + pointer := 0 // Index of current position. + // Is there an insertion operation before the last equality. + preIns := false + // Is there a deletion operation before the last equality. + preDel := false + // Is there an insertion operation after the last equality. + postIns := false + // Is there a deletion operation after the last equality. + postDel := false + for pointer < len(diffs) { + if diffs[pointer].Type == DiffEqual { // Equality found. + if len(diffs[pointer].Text) < dmp.DiffEditCost && + (postIns || postDel) { + // Candidate found. + equalities = &equality{ + data: pointer, + next: equalities, + } + preIns = postIns + preDel = postDel + lastequality = diffs[pointer].Text + } else { + // Not a candidate, and can never become one. + equalities = nil + lastequality = "" + } + postIns = false + postDel = false + } else { // An insertion or deletion. + if diffs[pointer].Type == DiffDelete { + postDel = true + } else { + postIns = true + } + + // Five types to be split: + // ABXYCD + // AXCD + // ABXC + // AXCD + // ABXC + var sumPres int + if preIns { + sumPres++ + } + if preDel { + sumPres++ + } + if postIns { + sumPres++ + } + if postDel { + sumPres++ + } + if len(lastequality) > 0 && + ((preIns && preDel && postIns && postDel) || + ((len(lastequality) < dmp.DiffEditCost/2) && sumPres == 3)) { + + insPoint := equalities.data + + // Duplicate record. + diffs = append(diffs[:insPoint], + append([]Diff{Diff{DiffDelete, lastequality}}, diffs[insPoint:]...)...) + + // Change second copy to insert. + diffs[insPoint+1].Type = DiffInsert + // Throw away the equality we just deleted. + equalities = equalities.next + lastequality = "" + + if preIns && preDel { + // No changes made which could affect previous entry, keep going. + postIns = true + postDel = true + equalities = nil + } else { + if equalities != nil { + equalities = equalities.next + } + if equalities != nil { + pointer = equalities.data + } else { + pointer = -1 + } + postIns = false + postDel = false + } + changes = true + } + } + pointer++ + } + + if changes { + diffs = dmp.DiffCleanupMerge(diffs) + } + + return diffs +} + +// DiffCleanupMerge reorders and merges like edit sections. Merge equalities. +// Any edit section can move as long as it doesn't cross an equality. +func (dmp *DiffMatchPatch) DiffCleanupMerge(diffs []Diff) []Diff { + // Add a dummy entry at the end. + diffs = append(diffs, Diff{DiffEqual, ""}) + pointer := 0 + countDelete := 0 + countInsert := 0 + commonlength := 0 + textDelete := []rune(nil) + textInsert := []rune(nil) + + for pointer < len(diffs) { + switch diffs[pointer].Type { + case DiffInsert: + countInsert++ + textInsert = append(textInsert, []rune(diffs[pointer].Text)...) + pointer++ + break + case DiffDelete: + countDelete++ + textDelete = append(textDelete, []rune(diffs[pointer].Text)...) + pointer++ + break + case DiffEqual: + // Upon reaching an equality, check for prior redundancies. + if countDelete+countInsert > 1 { + if countDelete != 0 && countInsert != 0 { + // Factor out any common prefixies. + commonlength = commonPrefixLength(textInsert, textDelete) + if commonlength != 0 { + x := pointer - countDelete - countInsert + if x > 0 && diffs[x-1].Type == DiffEqual { + diffs[x-1].Text += string(textInsert[:commonlength]) + } else { + diffs = append([]Diff{Diff{DiffEqual, string(textInsert[:commonlength])}}, diffs...) + pointer++ + } + textInsert = textInsert[commonlength:] + textDelete = textDelete[commonlength:] + } + // Factor out any common suffixies. + commonlength = commonSuffixLength(textInsert, textDelete) + if commonlength != 0 { + insertIndex := len(textInsert) - commonlength + deleteIndex := len(textDelete) - commonlength + diffs[pointer].Text = string(textInsert[insertIndex:]) + diffs[pointer].Text + textInsert = textInsert[:insertIndex] + textDelete = textDelete[:deleteIndex] + } + } + // Delete the offending records and add the merged ones. + if countDelete == 0 { + diffs = splice(diffs, pointer-countInsert, + countDelete+countInsert, + Diff{DiffInsert, string(textInsert)}) + } else if countInsert == 0 { + diffs = splice(diffs, pointer-countDelete, + countDelete+countInsert, + Diff{DiffDelete, string(textDelete)}) + } else { + diffs = splice(diffs, pointer-countDelete-countInsert, + countDelete+countInsert, + Diff{DiffDelete, string(textDelete)}, + Diff{DiffInsert, string(textInsert)}) + } + + pointer = pointer - countDelete - countInsert + 1 + if countDelete != 0 { + pointer++ + } + if countInsert != 0 { + pointer++ + } + } else if pointer != 0 && diffs[pointer-1].Type == DiffEqual { + // Merge this equality with the previous one. + diffs[pointer-1].Text += diffs[pointer].Text + diffs = append(diffs[:pointer], diffs[pointer+1:]...) + } else { + pointer++ + } + countInsert = 0 + countDelete = 0 + textDelete = nil + textInsert = nil + break + } + } + + if len(diffs[len(diffs)-1].Text) == 0 { + diffs = diffs[0 : len(diffs)-1] // Remove the dummy entry at the end. + } + + // Second pass: look for single edits surrounded on both sides by equalities which can be shifted sideways to eliminate an equality. E.g: ABAC -> ABAC + changes := false + pointer = 1 + // Intentionally ignore the first and last element (don't need checking). + for pointer < (len(diffs) - 1) { + if diffs[pointer-1].Type == DiffEqual && + diffs[pointer+1].Type == DiffEqual { + // This is a single edit surrounded by equalities. + if strings.HasSuffix(diffs[pointer].Text, diffs[pointer-1].Text) { + // Shift the edit over the previous equality. + diffs[pointer].Text = diffs[pointer-1].Text + + diffs[pointer].Text[:len(diffs[pointer].Text)-len(diffs[pointer-1].Text)] + diffs[pointer+1].Text = diffs[pointer-1].Text + diffs[pointer+1].Text + diffs = splice(diffs, pointer-1, 1) + changes = true + } else if strings.HasPrefix(diffs[pointer].Text, diffs[pointer+1].Text) { + // Shift the edit over the next equality. + diffs[pointer-1].Text += diffs[pointer+1].Text + diffs[pointer].Text = + diffs[pointer].Text[len(diffs[pointer+1].Text):] + diffs[pointer+1].Text + diffs = splice(diffs, pointer+1, 1) + changes = true + } + } + pointer++ + } + + // If shifts were made, the diff needs reordering and another shift sweep. + if changes { + diffs = dmp.DiffCleanupMerge(diffs) + } + + return diffs +} + +// DiffXIndex returns the equivalent location in s2. +func (dmp *DiffMatchPatch) DiffXIndex(diffs []Diff, loc int) int { + chars1 := 0 + chars2 := 0 + lastChars1 := 0 + lastChars2 := 0 + lastDiff := Diff{} + for i := 0; i < len(diffs); i++ { + aDiff := diffs[i] + if aDiff.Type != DiffInsert { + // Equality or deletion. + chars1 += len(aDiff.Text) + } + if aDiff.Type != DiffDelete { + // Equality or insertion. + chars2 += len(aDiff.Text) + } + if chars1 > loc { + // Overshot the location. + lastDiff = aDiff + break + } + lastChars1 = chars1 + lastChars2 = chars2 + } + if lastDiff.Type == DiffDelete { + // The location was deleted. + return lastChars2 + } + // Add the remaining character length. + return lastChars2 + (loc - lastChars1) +} + +// DiffPrettyHtml converts a []Diff into a pretty HTML report. +// It is intended as an example from which to write one's own display functions. +func (dmp *DiffMatchPatch) DiffPrettyHtml(diffs []Diff) string { + var buff bytes.Buffer + for _, diff := range diffs { + text := strings.Replace(html.EscapeString(diff.Text), "\n", "¶
", -1) + switch diff.Type { + case DiffInsert: + _, _ = buff.WriteString("") + _, _ = buff.WriteString(text) + _, _ = buff.WriteString("") + case DiffDelete: + _, _ = buff.WriteString("") + _, _ = buff.WriteString(text) + _, _ = buff.WriteString("") + case DiffEqual: + _, _ = buff.WriteString("") + _, _ = buff.WriteString(text) + _, _ = buff.WriteString("") + } + } + return buff.String() +} + +// DiffPrettyText converts a []Diff into a colored text report. +func (dmp *DiffMatchPatch) DiffPrettyText(diffs []Diff) string { + var buff bytes.Buffer + for _, diff := range diffs { + text := diff.Text + + switch diff.Type { + case DiffInsert: + _, _ = buff.WriteString("\x1b[32m") + _, _ = buff.WriteString(text) + _, _ = buff.WriteString("\x1b[0m") + case DiffDelete: + _, _ = buff.WriteString("\x1b[31m") + _, _ = buff.WriteString(text) + _, _ = buff.WriteString("\x1b[0m") + case DiffEqual: + _, _ = buff.WriteString(text) + } + } + + return buff.String() +} + +// DiffText1 computes and returns the source text (all equalities and deletions). +func (dmp *DiffMatchPatch) DiffText1(diffs []Diff) string { + //StringBuilder text = new StringBuilder() + var text bytes.Buffer + + for _, aDiff := range diffs { + if aDiff.Type != DiffInsert { + _, _ = text.WriteString(aDiff.Text) + } + } + return text.String() +} + +// DiffText2 computes and returns the destination text (all equalities and insertions). +func (dmp *DiffMatchPatch) DiffText2(diffs []Diff) string { + var text bytes.Buffer + + for _, aDiff := range diffs { + if aDiff.Type != DiffDelete { + _, _ = text.WriteString(aDiff.Text) + } + } + return text.String() +} + +// DiffLevenshtein computes the Levenshtein distance that is the number of inserted, deleted or substituted characters. +func (dmp *DiffMatchPatch) DiffLevenshtein(diffs []Diff) int { + levenshtein := 0 + insertions := 0 + deletions := 0 + + for _, aDiff := range diffs { + switch aDiff.Type { + case DiffInsert: + insertions += len(aDiff.Text) + case DiffDelete: + deletions += len(aDiff.Text) + case DiffEqual: + // A deletion and an insertion is one substitution. + levenshtein += max(insertions, deletions) + insertions = 0 + deletions = 0 + } + } + + levenshtein += max(insertions, deletions) + return levenshtein +} + +// DiffToDelta crushes the diff into an encoded string which describes the operations required to transform text1 into text2. +// E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. Operations are tab-separated. Inserted text is escaped using %xx notation. +func (dmp *DiffMatchPatch) DiffToDelta(diffs []Diff) string { + var text bytes.Buffer + for _, aDiff := range diffs { + switch aDiff.Type { + case DiffInsert: + _, _ = text.WriteString("+") + _, _ = text.WriteString(strings.Replace(url.QueryEscape(aDiff.Text), "+", " ", -1)) + _, _ = text.WriteString("\t") + break + case DiffDelete: + _, _ = text.WriteString("-") + _, _ = text.WriteString(strconv.Itoa(utf8.RuneCountInString(aDiff.Text))) + _, _ = text.WriteString("\t") + break + case DiffEqual: + _, _ = text.WriteString("=") + _, _ = text.WriteString(strconv.Itoa(utf8.RuneCountInString(aDiff.Text))) + _, _ = text.WriteString("\t") + break + } + } + delta := text.String() + if len(delta) != 0 { + // Strip off trailing tab character. + delta = delta[0 : utf8.RuneCountInString(delta)-1] + delta = unescaper.Replace(delta) + } + return delta +} + +// DiffFromDelta given the original text1, and an encoded string which describes the operations required to transform text1 into text2, comAdde the full diff. +func (dmp *DiffMatchPatch) DiffFromDelta(text1 string, delta string) (diffs []Diff, err error) { + i := 0 + runes := []rune(text1) + + for _, token := range strings.Split(delta, "\t") { + if len(token) == 0 { + // Blank tokens are ok (from a trailing \t). + continue + } + + // Each token begins with a one character parameter which specifies the operation of this token (delete, insert, equality). + param := token[1:] + + switch op := token[0]; op { + case '+': + // Decode would Diff all "+" to " " + param = strings.Replace(param, "+", "%2b", -1) + param, err = url.QueryUnescape(param) + if err != nil { + return nil, err + } + if !utf8.ValidString(param) { + return nil, fmt.Errorf("invalid UTF-8 token: %q", param) + } + + diffs = append(diffs, Diff{DiffInsert, param}) + case '=', '-': + n, err := strconv.ParseInt(param, 10, 0) + if err != nil { + return nil, err + } else if n < 0 { + return nil, errors.New("Negative number in DiffFromDelta: " + param) + } + + i += int(n) + // Break out if we are out of bounds, go1.6 can't handle this very well + if i > len(runes) { + break + } + // Remember that string slicing is by byte - we want by rune here. + text := string(runes[i-int(n) : i]) + + if op == '=' { + diffs = append(diffs, Diff{DiffEqual, text}) + } else { + diffs = append(diffs, Diff{DiffDelete, text}) + } + default: + // Anything else is an error. + return nil, errors.New("Invalid diff operation in DiffFromDelta: " + string(token[0])) + } + } + + if i != len(runes) { + return nil, fmt.Errorf("Delta length (%v) is different from source text length (%v)", i, len(text1)) + } + + return diffs, nil +} diff --git a/vendor/github.com/sergi/go-diff/diffmatchpatch/diffmatchpatch.go b/vendor/github.com/sergi/go-diff/diffmatchpatch/diffmatchpatch.go new file mode 100644 index 00000000000..d3acc32ce13 --- /dev/null +++ b/vendor/github.com/sergi/go-diff/diffmatchpatch/diffmatchpatch.go @@ -0,0 +1,46 @@ +// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. +// https://github.com/sergi/go-diff +// See the included LICENSE file for license details. +// +// go-diff is a Go implementation of Google's Diff, Match, and Patch library +// Original library is Copyright (c) 2006 Google Inc. +// http://code.google.com/p/google-diff-match-patch/ + +// Package diffmatchpatch offers robust algorithms to perform the operations required for synchronizing plain text. +package diffmatchpatch + +import ( + "time" +) + +// DiffMatchPatch holds the configuration for diff-match-patch operations. +type DiffMatchPatch struct { + // Number of seconds to map a diff before giving up (0 for infinity). + DiffTimeout time.Duration + // Cost of an empty edit operation in terms of edit characters. + DiffEditCost int + // How far to search for a match (0 = exact location, 1000+ = broad match). A match this many characters away from the expected location will add 1.0 to the score (0.0 is a perfect match). + MatchDistance int + // When deleting a large block of text (over ~64 characters), how close do the contents have to be to match the expected contents. (0.0 = perfection, 1.0 = very loose). Note that MatchThreshold controls how closely the end points of a delete need to match. + PatchDeleteThreshold float64 + // Chunk size for context length. + PatchMargin int + // The number of bits in an int. + MatchMaxBits int + // At what point is no match declared (0.0 = perfection, 1.0 = very loose). + MatchThreshold float64 +} + +// New creates a new DiffMatchPatch object with default parameters. +func New() *DiffMatchPatch { + // Defaults. + return &DiffMatchPatch{ + DiffTimeout: time.Second, + DiffEditCost: 4, + MatchThreshold: 0.5, + MatchDistance: 1000, + PatchDeleteThreshold: 0.5, + PatchMargin: 4, + MatchMaxBits: 32, + } +} diff --git a/vendor/github.com/sergi/go-diff/diffmatchpatch/match.go b/vendor/github.com/sergi/go-diff/diffmatchpatch/match.go new file mode 100644 index 00000000000..17374e109fe --- /dev/null +++ b/vendor/github.com/sergi/go-diff/diffmatchpatch/match.go @@ -0,0 +1,160 @@ +// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. +// https://github.com/sergi/go-diff +// See the included LICENSE file for license details. +// +// go-diff is a Go implementation of Google's Diff, Match, and Patch library +// Original library is Copyright (c) 2006 Google Inc. +// http://code.google.com/p/google-diff-match-patch/ + +package diffmatchpatch + +import ( + "math" +) + +// MatchMain locates the best instance of 'pattern' in 'text' near 'loc'. +// Returns -1 if no match found. +func (dmp *DiffMatchPatch) MatchMain(text, pattern string, loc int) int { + // Check for null inputs not needed since null can't be passed in C#. + + loc = int(math.Max(0, math.Min(float64(loc), float64(len(text))))) + if text == pattern { + // Shortcut (potentially not guaranteed by the algorithm) + return 0 + } else if len(text) == 0 { + // Nothing to match. + return -1 + } else if loc+len(pattern) <= len(text) && text[loc:loc+len(pattern)] == pattern { + // Perfect match at the perfect spot! (Includes case of null pattern) + return loc + } + // Do a fuzzy compare. + return dmp.MatchBitap(text, pattern, loc) +} + +// MatchBitap locates the best instance of 'pattern' in 'text' near 'loc' using the Bitap algorithm. +// Returns -1 if no match was found. +func (dmp *DiffMatchPatch) MatchBitap(text, pattern string, loc int) int { + // Initialise the alphabet. + s := dmp.MatchAlphabet(pattern) + + // Highest score beyond which we give up. + scoreThreshold := dmp.MatchThreshold + // Is there a nearby exact match? (speedup) + bestLoc := indexOf(text, pattern, loc) + if bestLoc != -1 { + scoreThreshold = math.Min(dmp.matchBitapScore(0, bestLoc, loc, + pattern), scoreThreshold) + // What about in the other direction? (speedup) + bestLoc = lastIndexOf(text, pattern, loc+len(pattern)) + if bestLoc != -1 { + scoreThreshold = math.Min(dmp.matchBitapScore(0, bestLoc, loc, + pattern), scoreThreshold) + } + } + + // Initialise the bit arrays. + matchmask := 1 << uint((len(pattern) - 1)) + bestLoc = -1 + + var binMin, binMid int + binMax := len(pattern) + len(text) + lastRd := []int{} + for d := 0; d < len(pattern); d++ { + // Scan for the best match; each iteration allows for one more error. Run a binary search to determine how far from 'loc' we can stray at this error level. + binMin = 0 + binMid = binMax + for binMin < binMid { + if dmp.matchBitapScore(d, loc+binMid, loc, pattern) <= scoreThreshold { + binMin = binMid + } else { + binMax = binMid + } + binMid = (binMax-binMin)/2 + binMin + } + // Use the result from this iteration as the maximum for the next. + binMax = binMid + start := int(math.Max(1, float64(loc-binMid+1))) + finish := int(math.Min(float64(loc+binMid), float64(len(text))) + float64(len(pattern))) + + rd := make([]int, finish+2) + rd[finish+1] = (1 << uint(d)) - 1 + + for j := finish; j >= start; j-- { + var charMatch int + if len(text) <= j-1 { + // Out of range. + charMatch = 0 + } else if _, ok := s[text[j-1]]; !ok { + charMatch = 0 + } else { + charMatch = s[text[j-1]] + } + + if d == 0 { + // First pass: exact match. + rd[j] = ((rd[j+1] << 1) | 1) & charMatch + } else { + // Subsequent passes: fuzzy match. + rd[j] = ((rd[j+1]<<1)|1)&charMatch | (((lastRd[j+1] | lastRd[j]) << 1) | 1) | lastRd[j+1] + } + if (rd[j] & matchmask) != 0 { + score := dmp.matchBitapScore(d, j-1, loc, pattern) + // This match will almost certainly be better than any existing match. But check anyway. + if score <= scoreThreshold { + // Told you so. + scoreThreshold = score + bestLoc = j - 1 + if bestLoc > loc { + // When passing loc, don't exceed our current distance from loc. + start = int(math.Max(1, float64(2*loc-bestLoc))) + } else { + // Already passed loc, downhill from here on in. + break + } + } + } + } + if dmp.matchBitapScore(d+1, loc, loc, pattern) > scoreThreshold { + // No hope for a (better) match at greater error levels. + break + } + lastRd = rd + } + return bestLoc +} + +// matchBitapScore computes and returns the score for a match with e errors and x location. +func (dmp *DiffMatchPatch) matchBitapScore(e, x, loc int, pattern string) float64 { + accuracy := float64(e) / float64(len(pattern)) + proximity := math.Abs(float64(loc - x)) + if dmp.MatchDistance == 0 { + // Dodge divide by zero error. + if proximity == 0 { + return accuracy + } + + return 1.0 + } + return accuracy + (proximity / float64(dmp.MatchDistance)) +} + +// MatchAlphabet initialises the alphabet for the Bitap algorithm. +func (dmp *DiffMatchPatch) MatchAlphabet(pattern string) map[byte]int { + s := map[byte]int{} + charPattern := []byte(pattern) + for _, c := range charPattern { + _, ok := s[c] + if !ok { + s[c] = 0 + } + } + i := 0 + + for _, c := range charPattern { + value := s[c] | int(uint(1)< y { + return x + } + return y +} diff --git a/vendor/github.com/sergi/go-diff/diffmatchpatch/patch.go b/vendor/github.com/sergi/go-diff/diffmatchpatch/patch.go new file mode 100644 index 00000000000..223c43c4268 --- /dev/null +++ b/vendor/github.com/sergi/go-diff/diffmatchpatch/patch.go @@ -0,0 +1,556 @@ +// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. +// https://github.com/sergi/go-diff +// See the included LICENSE file for license details. +// +// go-diff is a Go implementation of Google's Diff, Match, and Patch library +// Original library is Copyright (c) 2006 Google Inc. +// http://code.google.com/p/google-diff-match-patch/ + +package diffmatchpatch + +import ( + "bytes" + "errors" + "math" + "net/url" + "regexp" + "strconv" + "strings" +) + +// Patch represents one patch operation. +type Patch struct { + diffs []Diff + Start1 int + Start2 int + Length1 int + Length2 int +} + +// String emulates GNU diff's format. +// Header: @@ -382,8 +481,9 @@ +// Indices are printed as 1-based, not 0-based. +func (p *Patch) String() string { + var coords1, coords2 string + + if p.Length1 == 0 { + coords1 = strconv.Itoa(p.Start1) + ",0" + } else if p.Length1 == 1 { + coords1 = strconv.Itoa(p.Start1 + 1) + } else { + coords1 = strconv.Itoa(p.Start1+1) + "," + strconv.Itoa(p.Length1) + } + + if p.Length2 == 0 { + coords2 = strconv.Itoa(p.Start2) + ",0" + } else if p.Length2 == 1 { + coords2 = strconv.Itoa(p.Start2 + 1) + } else { + coords2 = strconv.Itoa(p.Start2+1) + "," + strconv.Itoa(p.Length2) + } + + var text bytes.Buffer + _, _ = text.WriteString("@@ -" + coords1 + " +" + coords2 + " @@\n") + + // Escape the body of the patch with %xx notation. + for _, aDiff := range p.diffs { + switch aDiff.Type { + case DiffInsert: + _, _ = text.WriteString("+") + case DiffDelete: + _, _ = text.WriteString("-") + case DiffEqual: + _, _ = text.WriteString(" ") + } + + _, _ = text.WriteString(strings.Replace(url.QueryEscape(aDiff.Text), "+", " ", -1)) + _, _ = text.WriteString("\n") + } + + return unescaper.Replace(text.String()) +} + +// PatchAddContext increases the context until it is unique, but doesn't let the pattern expand beyond MatchMaxBits. +func (dmp *DiffMatchPatch) PatchAddContext(patch Patch, text string) Patch { + if len(text) == 0 { + return patch + } + + pattern := text[patch.Start2 : patch.Start2+patch.Length1] + padding := 0 + + // Look for the first and last matches of pattern in text. If two different matches are found, increase the pattern length. + for strings.Index(text, pattern) != strings.LastIndex(text, pattern) && + len(pattern) < dmp.MatchMaxBits-2*dmp.PatchMargin { + padding += dmp.PatchMargin + maxStart := max(0, patch.Start2-padding) + minEnd := min(len(text), patch.Start2+patch.Length1+padding) + pattern = text[maxStart:minEnd] + } + // Add one chunk for good luck. + padding += dmp.PatchMargin + + // Add the prefix. + prefix := text[max(0, patch.Start2-padding):patch.Start2] + if len(prefix) != 0 { + patch.diffs = append([]Diff{Diff{DiffEqual, prefix}}, patch.diffs...) + } + // Add the suffix. + suffix := text[patch.Start2+patch.Length1 : min(len(text), patch.Start2+patch.Length1+padding)] + if len(suffix) != 0 { + patch.diffs = append(patch.diffs, Diff{DiffEqual, suffix}) + } + + // Roll back the start points. + patch.Start1 -= len(prefix) + patch.Start2 -= len(prefix) + // Extend the lengths. + patch.Length1 += len(prefix) + len(suffix) + patch.Length2 += len(prefix) + len(suffix) + + return patch +} + +// PatchMake computes a list of patches. +func (dmp *DiffMatchPatch) PatchMake(opt ...interface{}) []Patch { + if len(opt) == 1 { + diffs, _ := opt[0].([]Diff) + text1 := dmp.DiffText1(diffs) + return dmp.PatchMake(text1, diffs) + } else if len(opt) == 2 { + text1 := opt[0].(string) + switch t := opt[1].(type) { + case string: + diffs := dmp.DiffMain(text1, t, true) + if len(diffs) > 2 { + diffs = dmp.DiffCleanupSemantic(diffs) + diffs = dmp.DiffCleanupEfficiency(diffs) + } + return dmp.PatchMake(text1, diffs) + case []Diff: + return dmp.patchMake2(text1, t) + } + } else if len(opt) == 3 { + return dmp.PatchMake(opt[0], opt[2]) + } + return []Patch{} +} + +// patchMake2 computes a list of patches to turn text1 into text2. +// text2 is not provided, diffs are the delta between text1 and text2. +func (dmp *DiffMatchPatch) patchMake2(text1 string, diffs []Diff) []Patch { + // Check for null inputs not needed since null can't be passed in C#. + patches := []Patch{} + if len(diffs) == 0 { + return patches // Get rid of the null case. + } + + patch := Patch{} + charCount1 := 0 // Number of characters into the text1 string. + charCount2 := 0 // Number of characters into the text2 string. + // Start with text1 (prepatchText) and apply the diffs until we arrive at text2 (postpatchText). We recreate the patches one by one to determine context info. + prepatchText := text1 + postpatchText := text1 + + for i, aDiff := range diffs { + if len(patch.diffs) == 0 && aDiff.Type != DiffEqual { + // A new patch starts here. + patch.Start1 = charCount1 + patch.Start2 = charCount2 + } + + switch aDiff.Type { + case DiffInsert: + patch.diffs = append(patch.diffs, aDiff) + patch.Length2 += len(aDiff.Text) + postpatchText = postpatchText[:charCount2] + + aDiff.Text + postpatchText[charCount2:] + case DiffDelete: + patch.Length1 += len(aDiff.Text) + patch.diffs = append(patch.diffs, aDiff) + postpatchText = postpatchText[:charCount2] + postpatchText[charCount2+len(aDiff.Text):] + case DiffEqual: + if len(aDiff.Text) <= 2*dmp.PatchMargin && + len(patch.diffs) != 0 && i != len(diffs)-1 { + // Small equality inside a patch. + patch.diffs = append(patch.diffs, aDiff) + patch.Length1 += len(aDiff.Text) + patch.Length2 += len(aDiff.Text) + } + if len(aDiff.Text) >= 2*dmp.PatchMargin { + // Time for a new patch. + if len(patch.diffs) != 0 { + patch = dmp.PatchAddContext(patch, prepatchText) + patches = append(patches, patch) + patch = Patch{} + // Unlike Unidiff, our patch lists have a rolling context. http://code.google.com/p/google-diff-match-patch/wiki/Unidiff Update prepatch text & pos to reflect the application of the just completed patch. + prepatchText = postpatchText + charCount1 = charCount2 + } + } + } + + // Update the current character count. + if aDiff.Type != DiffInsert { + charCount1 += len(aDiff.Text) + } + if aDiff.Type != DiffDelete { + charCount2 += len(aDiff.Text) + } + } + + // Pick up the leftover patch if not empty. + if len(patch.diffs) != 0 { + patch = dmp.PatchAddContext(patch, prepatchText) + patches = append(patches, patch) + } + + return patches +} + +// PatchDeepCopy returns an array that is identical to a given an array of patches. +func (dmp *DiffMatchPatch) PatchDeepCopy(patches []Patch) []Patch { + patchesCopy := []Patch{} + for _, aPatch := range patches { + patchCopy := Patch{} + for _, aDiff := range aPatch.diffs { + patchCopy.diffs = append(patchCopy.diffs, Diff{ + aDiff.Type, + aDiff.Text, + }) + } + patchCopy.Start1 = aPatch.Start1 + patchCopy.Start2 = aPatch.Start2 + patchCopy.Length1 = aPatch.Length1 + patchCopy.Length2 = aPatch.Length2 + patchesCopy = append(patchesCopy, patchCopy) + } + return patchesCopy +} + +// PatchApply merges a set of patches onto the text. Returns a patched text, as well as an array of true/false values indicating which patches were applied. +func (dmp *DiffMatchPatch) PatchApply(patches []Patch, text string) (string, []bool) { + if len(patches) == 0 { + return text, []bool{} + } + + // Deep copy the patches so that no changes are made to originals. + patches = dmp.PatchDeepCopy(patches) + + nullPadding := dmp.PatchAddPadding(patches) + text = nullPadding + text + nullPadding + patches = dmp.PatchSplitMax(patches) + + x := 0 + // delta keeps track of the offset between the expected and actual location of the previous patch. If there are patches expected at positions 10 and 20, but the first patch was found at 12, delta is 2 and the second patch has an effective expected position of 22. + delta := 0 + results := make([]bool, len(patches)) + for _, aPatch := range patches { + expectedLoc := aPatch.Start2 + delta + text1 := dmp.DiffText1(aPatch.diffs) + var startLoc int + endLoc := -1 + if len(text1) > dmp.MatchMaxBits { + // PatchSplitMax will only provide an oversized pattern in the case of a monster delete. + startLoc = dmp.MatchMain(text, text1[:dmp.MatchMaxBits], expectedLoc) + if startLoc != -1 { + endLoc = dmp.MatchMain(text, + text1[len(text1)-dmp.MatchMaxBits:], expectedLoc+len(text1)-dmp.MatchMaxBits) + if endLoc == -1 || startLoc >= endLoc { + // Can't find valid trailing context. Drop this patch. + startLoc = -1 + } + } + } else { + startLoc = dmp.MatchMain(text, text1, expectedLoc) + } + if startLoc == -1 { + // No match found. :( + results[x] = false + // Subtract the delta for this failed patch from subsequent patches. + delta -= aPatch.Length2 - aPatch.Length1 + } else { + // Found a match. :) + results[x] = true + delta = startLoc - expectedLoc + var text2 string + if endLoc == -1 { + text2 = text[startLoc:int(math.Min(float64(startLoc+len(text1)), float64(len(text))))] + } else { + text2 = text[startLoc:int(math.Min(float64(endLoc+dmp.MatchMaxBits), float64(len(text))))] + } + if text1 == text2 { + // Perfect match, just shove the Replacement text in. + text = text[:startLoc] + dmp.DiffText2(aPatch.diffs) + text[startLoc+len(text1):] + } else { + // Imperfect match. Run a diff to get a framework of equivalent indices. + diffs := dmp.DiffMain(text1, text2, false) + if len(text1) > dmp.MatchMaxBits && float64(dmp.DiffLevenshtein(diffs))/float64(len(text1)) > dmp.PatchDeleteThreshold { + // The end points match, but the content is unacceptably bad. + results[x] = false + } else { + diffs = dmp.DiffCleanupSemanticLossless(diffs) + index1 := 0 + for _, aDiff := range aPatch.diffs { + if aDiff.Type != DiffEqual { + index2 := dmp.DiffXIndex(diffs, index1) + if aDiff.Type == DiffInsert { + // Insertion + text = text[:startLoc+index2] + aDiff.Text + text[startLoc+index2:] + } else if aDiff.Type == DiffDelete { + // Deletion + startIndex := startLoc + index2 + text = text[:startIndex] + + text[startIndex+dmp.DiffXIndex(diffs, index1+len(aDiff.Text))-index2:] + } + } + if aDiff.Type != DiffDelete { + index1 += len(aDiff.Text) + } + } + } + } + } + x++ + } + // Strip the padding off. + text = text[len(nullPadding) : len(nullPadding)+(len(text)-2*len(nullPadding))] + return text, results +} + +// PatchAddPadding adds some padding on text start and end so that edges can match something. +// Intended to be called only from within patchApply. +func (dmp *DiffMatchPatch) PatchAddPadding(patches []Patch) string { + paddingLength := dmp.PatchMargin + nullPadding := "" + for x := 1; x <= paddingLength; x++ { + nullPadding += string(x) + } + + // Bump all the patches forward. + for i := range patches { + patches[i].Start1 += paddingLength + patches[i].Start2 += paddingLength + } + + // Add some padding on start of first diff. + if len(patches[0].diffs) == 0 || patches[0].diffs[0].Type != DiffEqual { + // Add nullPadding equality. + patches[0].diffs = append([]Diff{Diff{DiffEqual, nullPadding}}, patches[0].diffs...) + patches[0].Start1 -= paddingLength // Should be 0. + patches[0].Start2 -= paddingLength // Should be 0. + patches[0].Length1 += paddingLength + patches[0].Length2 += paddingLength + } else if paddingLength > len(patches[0].diffs[0].Text) { + // Grow first equality. + extraLength := paddingLength - len(patches[0].diffs[0].Text) + patches[0].diffs[0].Text = nullPadding[len(patches[0].diffs[0].Text):] + patches[0].diffs[0].Text + patches[0].Start1 -= extraLength + patches[0].Start2 -= extraLength + patches[0].Length1 += extraLength + patches[0].Length2 += extraLength + } + + // Add some padding on end of last diff. + last := len(patches) - 1 + if len(patches[last].diffs) == 0 || patches[last].diffs[len(patches[last].diffs)-1].Type != DiffEqual { + // Add nullPadding equality. + patches[last].diffs = append(patches[last].diffs, Diff{DiffEqual, nullPadding}) + patches[last].Length1 += paddingLength + patches[last].Length2 += paddingLength + } else if paddingLength > len(patches[last].diffs[len(patches[last].diffs)-1].Text) { + // Grow last equality. + lastDiff := patches[last].diffs[len(patches[last].diffs)-1] + extraLength := paddingLength - len(lastDiff.Text) + patches[last].diffs[len(patches[last].diffs)-1].Text += nullPadding[:extraLength] + patches[last].Length1 += extraLength + patches[last].Length2 += extraLength + } + + return nullPadding +} + +// PatchSplitMax looks through the patches and breaks up any which are longer than the maximum limit of the match algorithm. +// Intended to be called only from within patchApply. +func (dmp *DiffMatchPatch) PatchSplitMax(patches []Patch) []Patch { + patchSize := dmp.MatchMaxBits + for x := 0; x < len(patches); x++ { + if patches[x].Length1 <= patchSize { + continue + } + bigpatch := patches[x] + // Remove the big old patch. + patches = append(patches[:x], patches[x+1:]...) + x-- + + Start1 := bigpatch.Start1 + Start2 := bigpatch.Start2 + precontext := "" + for len(bigpatch.diffs) != 0 { + // Create one of several smaller patches. + patch := Patch{} + empty := true + patch.Start1 = Start1 - len(precontext) + patch.Start2 = Start2 - len(precontext) + if len(precontext) != 0 { + patch.Length1 = len(precontext) + patch.Length2 = len(precontext) + patch.diffs = append(patch.diffs, Diff{DiffEqual, precontext}) + } + for len(bigpatch.diffs) != 0 && patch.Length1 < patchSize-dmp.PatchMargin { + diffType := bigpatch.diffs[0].Type + diffText := bigpatch.diffs[0].Text + if diffType == DiffInsert { + // Insertions are harmless. + patch.Length2 += len(diffText) + Start2 += len(diffText) + patch.diffs = append(patch.diffs, bigpatch.diffs[0]) + bigpatch.diffs = bigpatch.diffs[1:] + empty = false + } else if diffType == DiffDelete && len(patch.diffs) == 1 && patch.diffs[0].Type == DiffEqual && len(diffText) > 2*patchSize { + // This is a large deletion. Let it pass in one chunk. + patch.Length1 += len(diffText) + Start1 += len(diffText) + empty = false + patch.diffs = append(patch.diffs, Diff{diffType, diffText}) + bigpatch.diffs = bigpatch.diffs[1:] + } else { + // Deletion or equality. Only take as much as we can stomach. + diffText = diffText[:min(len(diffText), patchSize-patch.Length1-dmp.PatchMargin)] + + patch.Length1 += len(diffText) + Start1 += len(diffText) + if diffType == DiffEqual { + patch.Length2 += len(diffText) + Start2 += len(diffText) + } else { + empty = false + } + patch.diffs = append(patch.diffs, Diff{diffType, diffText}) + if diffText == bigpatch.diffs[0].Text { + bigpatch.diffs = bigpatch.diffs[1:] + } else { + bigpatch.diffs[0].Text = + bigpatch.diffs[0].Text[len(diffText):] + } + } + } + // Compute the head context for the next patch. + precontext = dmp.DiffText2(patch.diffs) + precontext = precontext[max(0, len(precontext)-dmp.PatchMargin):] + + postcontext := "" + // Append the end context for this patch. + if len(dmp.DiffText1(bigpatch.diffs)) > dmp.PatchMargin { + postcontext = dmp.DiffText1(bigpatch.diffs)[:dmp.PatchMargin] + } else { + postcontext = dmp.DiffText1(bigpatch.diffs) + } + + if len(postcontext) != 0 { + patch.Length1 += len(postcontext) + patch.Length2 += len(postcontext) + if len(patch.diffs) != 0 && patch.diffs[len(patch.diffs)-1].Type == DiffEqual { + patch.diffs[len(patch.diffs)-1].Text += postcontext + } else { + patch.diffs = append(patch.diffs, Diff{DiffEqual, postcontext}) + } + } + if !empty { + x++ + patches = append(patches[:x], append([]Patch{patch}, patches[x:]...)...) + } + } + } + return patches +} + +// PatchToText takes a list of patches and returns a textual representation. +func (dmp *DiffMatchPatch) PatchToText(patches []Patch) string { + var text bytes.Buffer + for _, aPatch := range patches { + _, _ = text.WriteString(aPatch.String()) + } + return text.String() +} + +// PatchFromText parses a textual representation of patches and returns a List of Patch objects. +func (dmp *DiffMatchPatch) PatchFromText(textline string) ([]Patch, error) { + patches := []Patch{} + if len(textline) == 0 { + return patches, nil + } + text := strings.Split(textline, "\n") + textPointer := 0 + patchHeader := regexp.MustCompile("^@@ -(\\d+),?(\\d*) \\+(\\d+),?(\\d*) @@$") + + var patch Patch + var sign uint8 + var line string + for textPointer < len(text) { + + if !patchHeader.MatchString(text[textPointer]) { + return patches, errors.New("Invalid patch string: " + text[textPointer]) + } + + patch = Patch{} + m := patchHeader.FindStringSubmatch(text[textPointer]) + + patch.Start1, _ = strconv.Atoi(m[1]) + if len(m[2]) == 0 { + patch.Start1-- + patch.Length1 = 1 + } else if m[2] == "0" { + patch.Length1 = 0 + } else { + patch.Start1-- + patch.Length1, _ = strconv.Atoi(m[2]) + } + + patch.Start2, _ = strconv.Atoi(m[3]) + + if len(m[4]) == 0 { + patch.Start2-- + patch.Length2 = 1 + } else if m[4] == "0" { + patch.Length2 = 0 + } else { + patch.Start2-- + patch.Length2, _ = strconv.Atoi(m[4]) + } + textPointer++ + + for textPointer < len(text) { + if len(text[textPointer]) > 0 { + sign = text[textPointer][0] + } else { + textPointer++ + continue + } + + line = text[textPointer][1:] + line = strings.Replace(line, "+", "%2b", -1) + line, _ = url.QueryUnescape(line) + if sign == '-' { + // Deletion. + patch.diffs = append(patch.diffs, Diff{DiffDelete, line}) + } else if sign == '+' { + // Insertion. + patch.diffs = append(patch.diffs, Diff{DiffInsert, line}) + } else if sign == ' ' { + // Minor equality. + patch.diffs = append(patch.diffs, Diff{DiffEqual, line}) + } else if sign == '@' { + // Start of next patch. + break + } else { + // WTF? + return patches, errors.New("Invalid patch mode '" + string(sign) + "' in: " + string(line)) + } + textPointer++ + } + + patches = append(patches, patch) + } + return patches, nil +} diff --git a/vendor/github.com/sergi/go-diff/diffmatchpatch/stringutil.go b/vendor/github.com/sergi/go-diff/diffmatchpatch/stringutil.go new file mode 100644 index 00000000000..265f29cc7e5 --- /dev/null +++ b/vendor/github.com/sergi/go-diff/diffmatchpatch/stringutil.go @@ -0,0 +1,88 @@ +// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. +// https://github.com/sergi/go-diff +// See the included LICENSE file for license details. +// +// go-diff is a Go implementation of Google's Diff, Match, and Patch library +// Original library is Copyright (c) 2006 Google Inc. +// http://code.google.com/p/google-diff-match-patch/ + +package diffmatchpatch + +import ( + "strings" + "unicode/utf8" +) + +// unescaper unescapes selected chars for compatibility with JavaScript's encodeURI. +// In speed critical applications this could be dropped since the receiving application will certainly decode these fine. Note that this function is case-sensitive. Thus "%3F" would not be unescaped. But this is ok because it is only called with the output of HttpUtility.UrlEncode which returns lowercase hex. Example: "%3f" -> "?", "%24" -> "$", etc. +var unescaper = strings.NewReplacer( + "%21", "!", "%7E", "~", "%27", "'", + "%28", "(", "%29", ")", "%3B", ";", + "%2F", "/", "%3F", "?", "%3A", ":", + "%40", "@", "%26", "&", "%3D", "=", + "%2B", "+", "%24", "$", "%2C", ",", "%23", "#", "%2A", "*") + +// indexOf returns the first index of pattern in str, starting at str[i]. +func indexOf(str string, pattern string, i int) int { + if i > len(str)-1 { + return -1 + } + if i <= 0 { + return strings.Index(str, pattern) + } + ind := strings.Index(str[i:], pattern) + if ind == -1 { + return -1 + } + return ind + i +} + +// lastIndexOf returns the last index of pattern in str, starting at str[i]. +func lastIndexOf(str string, pattern string, i int) int { + if i < 0 { + return -1 + } + if i >= len(str) { + return strings.LastIndex(str, pattern) + } + _, size := utf8.DecodeRuneInString(str[i:]) + return strings.LastIndex(str[:i+size], pattern) +} + +// runesIndexOf returns the index of pattern in target, starting at target[i]. +func runesIndexOf(target, pattern []rune, i int) int { + if i > len(target)-1 { + return -1 + } + if i <= 0 { + return runesIndex(target, pattern) + } + ind := runesIndex(target[i:], pattern) + if ind == -1 { + return -1 + } + return ind + i +} + +func runesEqual(r1, r2 []rune) bool { + if len(r1) != len(r2) { + return false + } + for i, c := range r1 { + if c != r2[i] { + return false + } + } + return true +} + +// runesIndex is the equivalent of strings.Index for rune slices. +func runesIndex(r1, r2 []rune) int { + last := len(r1) - len(r2) + for i := 0; i <= last; i++ { + if runesEqual(r1[i:i+len(r2)], r2) { + return i + } + } + return -1 +} diff --git a/vendor/go.opencensus.io/exporter/stackdriver/propagation/http.go b/vendor/go.opencensus.io/exporter/stackdriver/propagation/http.go deleted file mode 100644 index 7cc02a1104b..00000000000 --- a/vendor/go.opencensus.io/exporter/stackdriver/propagation/http.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2018, OpenCensus 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 propagation implement X-Cloud-Trace-Context header propagation used -// by Google Cloud products. -package propagation // import "go.opencensus.io/exporter/stackdriver/propagation" - -import ( - "encoding/binary" - "encoding/hex" - "fmt" - "net/http" - "strconv" - "strings" - - "go.opencensus.io/trace" - "go.opencensus.io/trace/propagation" -) - -const ( - httpHeaderMaxSize = 200 - httpHeader = `X-Cloud-Trace-Context` -) - -var _ propagation.HTTPFormat = (*HTTPFormat)(nil) - -// HTTPFormat implements propagation.HTTPFormat to propagate -// traces in HTTP headers for Google Cloud Platform and Stackdriver Trace. -type HTTPFormat struct{} - -// SpanContextFromRequest extracts a Stackdriver Trace span context from incoming requests. -func (f *HTTPFormat) SpanContextFromRequest(req *http.Request) (sc trace.SpanContext, ok bool) { - h := req.Header.Get(httpHeader) - // See https://cloud.google.com/trace/docs/faq for the header HTTPFormat. - // Return if the header is empty or missing, or if the header is unreasonably - // large, to avoid making unnecessary copies of a large string. - if h == "" || len(h) > httpHeaderMaxSize { - return trace.SpanContext{}, false - } - - // Parse the trace id field. - slash := strings.Index(h, `/`) - if slash == -1 { - return trace.SpanContext{}, false - } - tid, h := h[:slash], h[slash+1:] - - buf, err := hex.DecodeString(tid) - if err != nil { - return trace.SpanContext{}, false - } - copy(sc.TraceID[:], buf) - - // Parse the span id field. - spanstr := h - semicolon := strings.Index(h, `;`) - if semicolon != -1 { - spanstr, h = h[:semicolon], h[semicolon+1:] - } - sid, err := strconv.ParseUint(spanstr, 10, 64) - if err != nil { - return trace.SpanContext{}, false - } - binary.BigEndian.PutUint64(sc.SpanID[:], sid) - - // Parse the options field, options field is optional. - if !strings.HasPrefix(h, "o=") { - return sc, true - } - o, err := strconv.ParseUint(h[2:], 10, 64) - if err != nil { - return trace.SpanContext{}, false - } - sc.TraceOptions = trace.TraceOptions(o) - return sc, true -} - -// SpanContextToRequest modifies the given request to include a Stackdriver Trace header. -func (f *HTTPFormat) SpanContextToRequest(sc trace.SpanContext, req *http.Request) { - sid := binary.BigEndian.Uint64(sc.SpanID[:]) - header := fmt.Sprintf("%s/%d;o=%d", hex.EncodeToString(sc.TraceID[:]), sid, int64(sc.TraceOptions)) - req.Header.Set(httpHeader, header) -} diff --git a/vendor/go.opencensus.io/plugin/ocgrpc/client.go b/vendor/go.opencensus.io/plugin/ocgrpc/client.go deleted file mode 100644 index 37d238f1499..00000000000 --- a/vendor/go.opencensus.io/plugin/ocgrpc/client.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2018, OpenCensus 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 ocgrpc - -import ( - "go.opencensus.io/trace" - "golang.org/x/net/context" - - "google.golang.org/grpc/stats" -) - -// ClientHandler implements a gRPC stats.Handler for recording OpenCensus stats and -// traces. Use with gRPC clients only. -type ClientHandler struct { - // StartOptions allows configuring the StartOptions used to create new spans. - // - // StartOptions.SpanKind will always be set to trace.SpanKindClient - // for spans started by this handler. - StartOptions trace.StartOptions -} - -func (c *ClientHandler) HandleConn(ctx context.Context, cs stats.ConnStats) { - // no-op -} - -// TagConn exists to satisfy gRPC stats.Handler. -func (c *ClientHandler) TagConn(ctx context.Context, cti *stats.ConnTagInfo) context.Context { - // no-op - return ctx -} - -// HandleRPC implements per-RPC tracing and stats instrumentation. -func (c *ClientHandler) HandleRPC(ctx context.Context, rs stats.RPCStats) { - traceHandleRPC(ctx, rs) - statsHandleRPC(ctx, rs) -} - -// TagRPC implements per-RPC context management. -func (c *ClientHandler) TagRPC(ctx context.Context, rti *stats.RPCTagInfo) context.Context { - ctx = c.traceTagRPC(ctx, rti) - ctx = c.statsTagRPC(ctx, rti) - return ctx -} diff --git a/vendor/go.opencensus.io/plugin/ocgrpc/client_metrics.go b/vendor/go.opencensus.io/plugin/ocgrpc/client_metrics.go deleted file mode 100644 index b8efacfb3fd..00000000000 --- a/vendor/go.opencensus.io/plugin/ocgrpc/client_metrics.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2017, OpenCensus 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 ocgrpc - -import ( - "go.opencensus.io/stats" - "go.opencensus.io/stats/view" - "go.opencensus.io/tag" -) - -// The following variables are measures are recorded by ClientHandler: -var ( - ClientSentMessagesPerRPC = stats.Int64("grpc.io/client/sent_messages_per_rpc", "Number of messages sent in the RPC (always 1 for non-streaming RPCs).", stats.UnitDimensionless) - ClientSentBytesPerRPC = stats.Int64("grpc.io/client/sent_bytes_per_rpc", "Total bytes sent across all request messages per RPC.", stats.UnitBytes) - ClientReceivedMessagesPerRPC = stats.Int64("grpc.io/client/received_messages_per_rpc", "Number of response messages received per RPC (always 1 for non-streaming RPCs).", stats.UnitDimensionless) - ClientReceivedBytesPerRPC = stats.Int64("grpc.io/client/received_bytes_per_rpc", "Total bytes received across all response messages per RPC.", stats.UnitBytes) - ClientRoundtripLatency = stats.Float64("grpc.io/client/roundtrip_latency", "Time between first byte of request sent to last byte of response received, or terminal error.", stats.UnitMilliseconds) - ClientServerLatency = stats.Float64("grpc.io/client/server_latency", `Propagated from the server and should have the same value as "grpc.io/server/latency".`, stats.UnitMilliseconds) -) - -// Predefined views may be subscribed to collect data for the above measures. -// As always, you may also define your own custom views over measures collected by this -// package. These are declared as a convenience only; none are subscribed by -// default. -var ( - ClientSentBytesPerRPCView = &view.View{ - Measure: ClientSentBytesPerRPC, - Name: "grpc.io/client/sent_bytes_per_rpc", - Description: "Distribution of bytes sent per RPC, by method.", - TagKeys: []tag.Key{KeyClientMethod}, - Aggregation: DefaultBytesDistribution, - } - - ClientReceivedBytesPerRPCView = &view.View{ - Measure: ClientReceivedBytesPerRPC, - Name: "grpc.io/client/received_bytes_per_rpc", - Description: "Distribution of bytes received per RPC, by method.", - TagKeys: []tag.Key{KeyClientMethod}, - Aggregation: DefaultBytesDistribution, - } - - ClientRoundtripLatencyView = &view.View{ - Measure: ClientRoundtripLatency, - Name: "grpc.io/client/roundtrip_latency", - Description: "Distribution of round-trip latency, by method.", - TagKeys: []tag.Key{KeyClientMethod}, - Aggregation: DefaultMillisecondsDistribution, - } - - ClientCompletedRPCsView = &view.View{ - Measure: ClientRoundtripLatency, - Name: "grpc.io/client/completed_rpcs", - Description: "Count of RPCs by method and status.", - TagKeys: []tag.Key{KeyClientMethod, KeyClientStatus}, - Aggregation: view.Count(), - } - - ClientSentMessagesPerRPCView = &view.View{ - Measure: ClientSentMessagesPerRPC, - Name: "grpc.io/client/sent_messages_per_rpc", - Description: "Distribution of sent messages count per RPC, by method.", - TagKeys: []tag.Key{KeyClientMethod}, - Aggregation: DefaultMessageCountDistribution, - } - - ClientReceivedMessagesPerRPCView = &view.View{ - Measure: ClientReceivedMessagesPerRPC, - Name: "grpc.io/client/received_messages_per_rpc", - Description: "Distribution of received messages count per RPC, by method.", - TagKeys: []tag.Key{KeyClientMethod}, - Aggregation: DefaultMessageCountDistribution, - } - - ClientServerLatencyView = &view.View{ - Measure: ClientServerLatency, - Name: "grpc.io/client/server_latency", - Description: "Distribution of server latency as viewed by client, by method.", - TagKeys: []tag.Key{KeyClientMethod}, - Aggregation: DefaultMillisecondsDistribution, - } - - // Deprecated: This view is going to be removed, if you need it please define it - // yourself. - ClientRequestCountView = &view.View{ - Name: "Count of request messages per client RPC", - TagKeys: []tag.Key{KeyClientMethod}, - Measure: ClientRoundtripLatency, - Aggregation: view.Count(), - } -) - -// DefaultClientViews are the default client views provided by this package. -var DefaultClientViews = []*view.View{ - ClientSentBytesPerRPCView, - ClientReceivedBytesPerRPCView, - ClientRoundtripLatencyView, - ClientCompletedRPCsView, -} - -// TODO(jbd): Add roundtrip_latency, uncompressed_request_bytes, uncompressed_response_bytes, request_count, response_count. -// TODO(acetechnologist): This is temporary and will need to be replaced by a -// mechanism to load these defaults from a common repository/config shared by -// all supported languages. Likely a serialized protobuf of these defaults. diff --git a/vendor/go.opencensus.io/plugin/ocgrpc/client_stats_handler.go b/vendor/go.opencensus.io/plugin/ocgrpc/client_stats_handler.go deleted file mode 100644 index 303c607f632..00000000000 --- a/vendor/go.opencensus.io/plugin/ocgrpc/client_stats_handler.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2017, OpenCensus 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 ocgrpc - -import ( - "time" - - "go.opencensus.io/tag" - "golang.org/x/net/context" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/stats" -) - -// statsTagRPC gets the tag.Map populated by the application code, serializes -// its tags into the GRPC metadata in order to be sent to the server. -func (h *ClientHandler) statsTagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context { - startTime := time.Now() - if info == nil { - if grpclog.V(2) { - grpclog.Infof("clientHandler.TagRPC called with nil info.", info.FullMethodName) - } - return ctx - } - - d := &rpcData{ - startTime: startTime, - method: info.FullMethodName, - } - ts := tag.FromContext(ctx) - if ts != nil { - encoded := tag.Encode(ts) - ctx = stats.SetTags(ctx, encoded) - } - - return context.WithValue(ctx, rpcDataKey, d) -} diff --git a/vendor/go.opencensus.io/plugin/ocgrpc/server.go b/vendor/go.opencensus.io/plugin/ocgrpc/server.go deleted file mode 100644 index b67b3e2be2a..00000000000 --- a/vendor/go.opencensus.io/plugin/ocgrpc/server.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2018, OpenCensus 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 ocgrpc - -import ( - "go.opencensus.io/trace" - "golang.org/x/net/context" - - "google.golang.org/grpc/stats" -) - -// ServerHandler implements gRPC stats.Handler recording OpenCensus stats and -// traces. Use with gRPC servers. -// -// When installed (see Example), tracing metadata is read from inbound RPCs -// by default. If no tracing metadata is present, or if the tracing metadata is -// present but the SpanContext isn't sampled, then a new trace may be started -// (as determined by Sampler). -type ServerHandler struct { - // IsPublicEndpoint may be set to true to always start a new trace around - // each RPC. Any SpanContext in the RPC metadata will be added as a linked - // span instead of making it the parent of the span created around the - // server RPC. - // - // Be aware that if you leave this false (the default) on a public-facing - // server, callers will be able to send tracing metadata in gRPC headers - // and trigger traces in your backend. - IsPublicEndpoint bool - - // StartOptions to use for to spans started around RPCs handled by this server. - // - // These will apply even if there is tracing metadata already - // present on the inbound RPC but the SpanContext is not sampled. This - // ensures that each service has some opportunity to be traced. If you would - // like to not add any additional traces for this gRPC service, set: - // - // StartOptions.Sampler = trace.ProbabilitySampler(0.0) - // - // StartOptions.SpanKind will always be set to trace.SpanKindServer - // for spans started by this handler. - StartOptions trace.StartOptions -} - -var _ stats.Handler = (*ServerHandler)(nil) - -// HandleConn exists to satisfy gRPC stats.Handler. -func (s *ServerHandler) HandleConn(ctx context.Context, cs stats.ConnStats) { - // no-op -} - -// TagConn exists to satisfy gRPC stats.Handler. -func (s *ServerHandler) TagConn(ctx context.Context, cti *stats.ConnTagInfo) context.Context { - // no-op - return ctx -} - -// HandleRPC implements per-RPC tracing and stats instrumentation. -func (s *ServerHandler) HandleRPC(ctx context.Context, rs stats.RPCStats) { - traceHandleRPC(ctx, rs) - statsHandleRPC(ctx, rs) -} - -// TagRPC implements per-RPC context management. -func (s *ServerHandler) TagRPC(ctx context.Context, rti *stats.RPCTagInfo) context.Context { - ctx = s.traceTagRPC(ctx, rti) - ctx = s.statsTagRPC(ctx, rti) - return ctx -} diff --git a/vendor/go.opencensus.io/plugin/ocgrpc/server_metrics.go b/vendor/go.opencensus.io/plugin/ocgrpc/server_metrics.go deleted file mode 100644 index 02323f8712e..00000000000 --- a/vendor/go.opencensus.io/plugin/ocgrpc/server_metrics.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2017, OpenCensus 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 ocgrpc - -import ( - "go.opencensus.io/stats" - "go.opencensus.io/stats/view" - "go.opencensus.io/tag" -) - -// The following variables are measures are recorded by ServerHandler: -var ( - ServerReceivedMessagesPerRPC = stats.Int64("grpc.io/server/received_messages_per_rpc", "Number of messages received in each RPC. Has value 1 for non-streaming RPCs.", stats.UnitDimensionless) - ServerReceivedBytesPerRPC = stats.Int64("grpc.io/server/received_bytes_per_rpc", "Total bytes received across all messages per RPC.", stats.UnitBytes) - ServerSentMessagesPerRPC = stats.Int64("grpc.io/server/sent_messages_per_rpc", "Number of messages sent in each RPC. Has value 1 for non-streaming RPCs.", stats.UnitDimensionless) - ServerSentBytesPerRPC = stats.Int64("grpc.io/server/sent_bytes_per_rpc", "Total bytes sent in across all response messages per RPC.", stats.UnitBytes) - ServerLatency = stats.Float64("grpc.io/server/server_latency", "Time between first byte of request received to last byte of response sent, or terminal error.", stats.UnitMilliseconds) -) - -// TODO(acetechnologist): This is temporary and will need to be replaced by a -// mechanism to load these defaults from a common repository/config shared by -// all supported languages. Likely a serialized protobuf of these defaults. - -// Predefined views may be subscribed to collect data for the above measures. -// As always, you may also define your own custom views over measures collected by this -// package. These are declared as a convenience only; none are subscribed by -// default. -var ( - ServerReceivedBytesPerRPCView = &view.View{ - Name: "grpc.io/server/received_bytes_per_rpc", - Description: "Distribution of received bytes per RPC, by method.", - Measure: ServerReceivedBytesPerRPC, - TagKeys: []tag.Key{KeyServerMethod}, - Aggregation: DefaultBytesDistribution, - } - - ServerSentBytesPerRPCView = &view.View{ - Name: "grpc.io/server/sent_bytes_per_rpc", - Description: "Distribution of total sent bytes per RPC, by method.", - Measure: ServerSentBytesPerRPC, - TagKeys: []tag.Key{KeyServerMethod}, - Aggregation: DefaultBytesDistribution, - } - - ServerLatencyView = &view.View{ - Name: "grpc.io/server/server_latency", - Description: "Distribution of server latency in milliseconds, by method.", - TagKeys: []tag.Key{KeyServerMethod}, - Measure: ServerLatency, - Aggregation: DefaultMillisecondsDistribution, - } - - ServerCompletedRPCsView = &view.View{ - Name: "grpc.io/server/completed_rpcs", - Description: "Count of RPCs by method and status.", - TagKeys: []tag.Key{KeyServerMethod, KeyServerStatus}, - Measure: ServerLatency, - Aggregation: view.Count(), - } - - ServerReceivedMessagesPerRPCView = &view.View{ - Name: "grpc.io/server/received_messages_per_rpc", - Description: "Distribution of messages received count per RPC, by method.", - TagKeys: []tag.Key{KeyServerMethod}, - Measure: ServerReceivedMessagesPerRPC, - Aggregation: DefaultMessageCountDistribution, - } - - ServerSentMessagesPerRPCView = &view.View{ - Name: "grpc.io/server/sent_messages_per_rpc", - Description: "Distribution of messages sent count per RPC, by method.", - TagKeys: []tag.Key{KeyServerMethod}, - Measure: ServerSentMessagesPerRPC, - Aggregation: DefaultMessageCountDistribution, - } -) - -// DefaultServerViews are the default server views provided by this package. -var DefaultServerViews = []*view.View{ - ServerReceivedBytesPerRPCView, - ServerSentBytesPerRPCView, - ServerLatencyView, - ServerCompletedRPCsView, -} diff --git a/vendor/go.opencensus.io/plugin/ocgrpc/server_stats_handler.go b/vendor/go.opencensus.io/plugin/ocgrpc/server_stats_handler.go deleted file mode 100644 index 7847c1a912e..00000000000 --- a/vendor/go.opencensus.io/plugin/ocgrpc/server_stats_handler.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2017, OpenCensus 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 ocgrpc - -import ( - "time" - - "golang.org/x/net/context" - - "go.opencensus.io/tag" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/stats" -) - -// statsTagRPC gets the metadata from gRPC context, extracts the encoded tags from -// it and creates a new tag.Map and puts them into the returned context. -func (h *ServerHandler) statsTagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context { - startTime := time.Now() - if info == nil { - if grpclog.V(2) { - grpclog.Infof("opencensus: TagRPC called with nil info.") - } - return ctx - } - d := &rpcData{ - startTime: startTime, - method: info.FullMethodName, - } - propagated := h.extractPropagatedTags(ctx) - ctx = tag.NewContext(ctx, propagated) - ctx, _ = tag.New(ctx, tag.Upsert(KeyServerMethod, methodName(info.FullMethodName))) - return context.WithValue(ctx, rpcDataKey, d) -} - -// extractPropagatedTags creates a new tag map containing the tags extracted from the -// gRPC metadata. -func (h *ServerHandler) extractPropagatedTags(ctx context.Context) *tag.Map { - buf := stats.Tags(ctx) - if buf == nil { - return nil - } - propagated, err := tag.Decode(buf) - if err != nil { - if grpclog.V(2) { - grpclog.Warningf("opencensus: Failed to decode tags from gRPC metadata failed to decode: %v", err) - } - return nil - } - return propagated -} diff --git a/vendor/go.opencensus.io/plugin/ocgrpc/stats_common.go b/vendor/go.opencensus.io/plugin/ocgrpc/stats_common.go deleted file mode 100644 index acb626e126c..00000000000 --- a/vendor/go.opencensus.io/plugin/ocgrpc/stats_common.go +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright 2017, OpenCensus 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 ocgrpc - -import ( - "context" - "strconv" - "strings" - "sync/atomic" - "time" - - ocstats "go.opencensus.io/stats" - "go.opencensus.io/stats/view" - "go.opencensus.io/tag" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" -) - -type grpcInstrumentationKey string - -// rpcData holds the instrumentation RPC data that is needed between the start -// and end of an call. It holds the info that this package needs to keep track -// of between the various GRPC events. -type rpcData struct { - // reqCount and respCount has to be the first words - // in order to be 64-aligned on 32-bit architectures. - sentCount, sentBytes, recvCount, recvBytes int64 // access atomically - - // startTime represents the time at which TagRPC was invoked at the - // beginning of an RPC. It is an appoximation of the time when the - // application code invoked GRPC code. - startTime time.Time - method string -} - -// The following variables define the default hard-coded auxiliary data used by -// both the default GRPC client and GRPC server metrics. -var ( - DefaultBytesDistribution = view.Distribution(0, 1024, 2048, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216, 67108864, 268435456, 1073741824, 4294967296) - DefaultMillisecondsDistribution = view.Distribution(0, 0.01, 0.05, 0.1, 0.3, 0.6, 0.8, 1, 2, 3, 4, 5, 6, 8, 10, 13, 16, 20, 25, 30, 40, 50, 65, 80, 100, 130, 160, 200, 250, 300, 400, 500, 650, 800, 1000, 2000, 5000, 10000, 20000, 50000, 100000) - DefaultMessageCountDistribution = view.Distribution(0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536) -) - -var ( - KeyServerMethod, _ = tag.NewKey("grpc_server_method") - KeyClientMethod, _ = tag.NewKey("grpc_client_method") - KeyServerStatus, _ = tag.NewKey("grpc_server_status") - KeyClientStatus, _ = tag.NewKey("grpc_client_status") -) - -var ( - rpcDataKey = grpcInstrumentationKey("opencensus-rpcData") -) - -func methodName(fullname string) string { - return strings.TrimLeft(fullname, "/") -} - -// statsHandleRPC processes the RPC events. -func statsHandleRPC(ctx context.Context, s stats.RPCStats) { - switch st := s.(type) { - case *stats.Begin, *stats.OutHeader, *stats.InHeader, *stats.InTrailer, *stats.OutTrailer: - // do nothing for client - case *stats.OutPayload: - handleRPCOutPayload(ctx, st) - case *stats.InPayload: - handleRPCInPayload(ctx, st) - case *stats.End: - handleRPCEnd(ctx, st) - default: - grpclog.Infof("unexpected stats: %T", st) - } -} - -func handleRPCOutPayload(ctx context.Context, s *stats.OutPayload) { - d, ok := ctx.Value(rpcDataKey).(*rpcData) - if !ok { - if grpclog.V(2) { - grpclog.Infoln("Failed to retrieve *rpcData from context.") - } - return - } - - atomic.AddInt64(&d.sentBytes, int64(s.Length)) - atomic.AddInt64(&d.sentCount, 1) -} - -func handleRPCInPayload(ctx context.Context, s *stats.InPayload) { - d, ok := ctx.Value(rpcDataKey).(*rpcData) - if !ok { - if grpclog.V(2) { - grpclog.Infoln("Failed to retrieve *rpcData from context.") - } - return - } - - atomic.AddInt64(&d.recvBytes, int64(s.Length)) - atomic.AddInt64(&d.recvCount, 1) -} - -func handleRPCEnd(ctx context.Context, s *stats.End) { - d, ok := ctx.Value(rpcDataKey).(*rpcData) - if !ok { - if grpclog.V(2) { - grpclog.Infoln("Failed to retrieve *rpcData from context.") - } - return - } - - elapsedTime := time.Since(d.startTime) - - var st string - if s.Error != nil { - s, ok := status.FromError(s.Error) - if ok { - st = statusCodeToString(s) - } - } else { - st = "OK" - } - - latencyMillis := float64(elapsedTime) / float64(time.Millisecond) - if s.Client { - ctx, _ = tag.New(ctx, - tag.Upsert(KeyClientMethod, methodName(d.method)), - tag.Upsert(KeyClientStatus, st)) - ocstats.Record(ctx, - ClientSentBytesPerRPC.M(atomic.LoadInt64(&d.sentBytes)), - ClientSentMessagesPerRPC.M(atomic.LoadInt64(&d.sentCount)), - ClientReceivedMessagesPerRPC.M(atomic.LoadInt64(&d.recvCount)), - ClientReceivedBytesPerRPC.M(atomic.LoadInt64(&d.recvBytes)), - ClientRoundtripLatency.M(latencyMillis)) - } else { - ctx, _ = tag.New(ctx, tag.Upsert(KeyServerStatus, st)) - ocstats.Record(ctx, - ServerSentBytesPerRPC.M(atomic.LoadInt64(&d.sentBytes)), - ServerSentMessagesPerRPC.M(atomic.LoadInt64(&d.sentCount)), - ServerReceivedMessagesPerRPC.M(atomic.LoadInt64(&d.recvCount)), - ServerReceivedBytesPerRPC.M(atomic.LoadInt64(&d.recvBytes)), - ServerLatency.M(latencyMillis)) - } -} - -func statusCodeToString(s *status.Status) string { - // see https://github.com/grpc/grpc/blob/master/doc/statuscodes.md - switch c := s.Code(); c { - case codes.OK: - return "OK" - case codes.Canceled: - return "CANCELLED" - case codes.Unknown: - return "UNKNOWN" - case codes.InvalidArgument: - return "INVALID_ARGUMENT" - case codes.DeadlineExceeded: - return "DEADLINE_EXCEEDED" - case codes.NotFound: - return "NOT_FOUND" - case codes.AlreadyExists: - return "ALREADY_EXISTS" - case codes.PermissionDenied: - return "PERMISSION_DENIED" - case codes.ResourceExhausted: - return "RESOURCE_EXHAUSTED" - case codes.FailedPrecondition: - return "FAILED_PRECONDITION" - case codes.Aborted: - return "ABORTED" - case codes.OutOfRange: - return "OUT_OF_RANGE" - case codes.Unimplemented: - return "UNIMPLEMENTED" - case codes.Internal: - return "INTERNAL" - case codes.Unavailable: - return "UNAVAILABLE" - case codes.DataLoss: - return "DATA_LOSS" - case codes.Unauthenticated: - return "UNAUTHENTICATED" - default: - return "CODE_" + strconv.FormatInt(int64(c), 10) - } -} diff --git a/vendor/go.opencensus.io/plugin/ocgrpc/trace_common.go b/vendor/go.opencensus.io/plugin/ocgrpc/trace_common.go deleted file mode 100644 index 720f381c275..00000000000 --- a/vendor/go.opencensus.io/plugin/ocgrpc/trace_common.go +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2017, OpenCensus 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 ocgrpc - -import ( - "strings" - - "google.golang.org/grpc/codes" - - "go.opencensus.io/trace" - "go.opencensus.io/trace/propagation" - "golang.org/x/net/context" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" -) - -const traceContextKey = "grpc-trace-bin" - -// TagRPC creates a new trace span for the client side of the RPC. -// -// It returns ctx with the new trace span added and a serialization of the -// SpanContext added to the outgoing gRPC metadata. -func (c *ClientHandler) traceTagRPC(ctx context.Context, rti *stats.RPCTagInfo) context.Context { - name := strings.TrimPrefix(rti.FullMethodName, "/") - name = strings.Replace(name, "/", ".", -1) - ctx, span := trace.StartSpan(ctx, name, - trace.WithSampler(c.StartOptions.Sampler), - trace.WithSpanKind(trace.SpanKindClient)) // span is ended by traceHandleRPC - traceContextBinary := propagation.Binary(span.SpanContext()) - return metadata.AppendToOutgoingContext(ctx, traceContextKey, string(traceContextBinary)) -} - -// TagRPC creates a new trace span for the server side of the RPC. -// -// It checks the incoming gRPC metadata in ctx for a SpanContext, and if -// it finds one, uses that SpanContext as the parent context of the new span. -// -// It returns ctx, with the new trace span added. -func (s *ServerHandler) traceTagRPC(ctx context.Context, rti *stats.RPCTagInfo) context.Context { - md, _ := metadata.FromIncomingContext(ctx) - name := strings.TrimPrefix(rti.FullMethodName, "/") - name = strings.Replace(name, "/", ".", -1) - traceContext := md[traceContextKey] - var ( - parent trace.SpanContext - haveParent bool - ) - if len(traceContext) > 0 { - // Metadata with keys ending in -bin are actually binary. They are base64 - // encoded before being put on the wire, see: - // https://github.com/grpc/grpc-go/blob/08d6261/Documentation/grpc-metadata.md#storing-binary-data-in-metadata - traceContextBinary := []byte(traceContext[0]) - parent, haveParent = propagation.FromBinary(traceContextBinary) - if haveParent && !s.IsPublicEndpoint { - ctx, _ := trace.StartSpanWithRemoteParent(ctx, name, parent, - trace.WithSpanKind(trace.SpanKindServer), - trace.WithSampler(s.StartOptions.Sampler), - ) - return ctx - } - } - ctx, span := trace.StartSpan(ctx, name, - trace.WithSpanKind(trace.SpanKindServer), - trace.WithSampler(s.StartOptions.Sampler)) - if haveParent { - span.AddLink(trace.Link{TraceID: parent.TraceID, SpanID: parent.SpanID, Type: trace.LinkTypeChild}) - } - return ctx -} - -func traceHandleRPC(ctx context.Context, rs stats.RPCStats) { - span := trace.FromContext(ctx) - // TODO: compressed and uncompressed sizes are not populated in every message. - switch rs := rs.(type) { - case *stats.Begin: - span.AddAttributes( - trace.BoolAttribute("Client", rs.Client), - trace.BoolAttribute("FailFast", rs.FailFast)) - case *stats.InPayload: - span.AddMessageReceiveEvent(0 /* TODO: messageID */, int64(rs.Length), int64(rs.WireLength)) - case *stats.OutPayload: - span.AddMessageSendEvent(0, int64(rs.Length), int64(rs.WireLength)) - case *stats.End: - if rs.Error != nil { - s, ok := status.FromError(rs.Error) - if ok { - span.SetStatus(trace.Status{Code: int32(s.Code()), Message: s.Message()}) - } else { - span.SetStatus(trace.Status{Code: int32(codes.Internal), Message: rs.Error.Error()}) - } - } - span.End() - } -} diff --git a/vendor/golang.org/x/net/internal/timeseries/timeseries.go b/vendor/golang.org/x/net/internal/timeseries/timeseries.go deleted file mode 100644 index 685f0e7ea23..00000000000 --- a/vendor/golang.org/x/net/internal/timeseries/timeseries.go +++ /dev/null @@ -1,525 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package timeseries implements a time series structure for stats collection. -package timeseries // import "golang.org/x/net/internal/timeseries" - -import ( - "fmt" - "log" - "time" -) - -const ( - timeSeriesNumBuckets = 64 - minuteHourSeriesNumBuckets = 60 -) - -var timeSeriesResolutions = []time.Duration{ - 1 * time.Second, - 10 * time.Second, - 1 * time.Minute, - 10 * time.Minute, - 1 * time.Hour, - 6 * time.Hour, - 24 * time.Hour, // 1 day - 7 * 24 * time.Hour, // 1 week - 4 * 7 * 24 * time.Hour, // 4 weeks - 16 * 7 * 24 * time.Hour, // 16 weeks -} - -var minuteHourSeriesResolutions = []time.Duration{ - 1 * time.Second, - 1 * time.Minute, -} - -// An Observable is a kind of data that can be aggregated in a time series. -type Observable interface { - Multiply(ratio float64) // Multiplies the data in self by a given ratio - Add(other Observable) // Adds the data from a different observation to self - Clear() // Clears the observation so it can be reused. - CopyFrom(other Observable) // Copies the contents of a given observation to self -} - -// Float attaches the methods of Observable to a float64. -type Float float64 - -// NewFloat returns a Float. -func NewFloat() Observable { - f := Float(0) - return &f -} - -// String returns the float as a string. -func (f *Float) String() string { return fmt.Sprintf("%g", f.Value()) } - -// Value returns the float's value. -func (f *Float) Value() float64 { return float64(*f) } - -func (f *Float) Multiply(ratio float64) { *f *= Float(ratio) } - -func (f *Float) Add(other Observable) { - o := other.(*Float) - *f += *o -} - -func (f *Float) Clear() { *f = 0 } - -func (f *Float) CopyFrom(other Observable) { - o := other.(*Float) - *f = *o -} - -// A Clock tells the current time. -type Clock interface { - Time() time.Time -} - -type defaultClock int - -var defaultClockInstance defaultClock - -func (defaultClock) Time() time.Time { return time.Now() } - -// Information kept per level. Each level consists of a circular list of -// observations. The start of the level may be derived from end and the -// len(buckets) * sizeInMillis. -type tsLevel struct { - oldest int // index to oldest bucketed Observable - newest int // index to newest bucketed Observable - end time.Time // end timestamp for this level - size time.Duration // duration of the bucketed Observable - buckets []Observable // collections of observations - provider func() Observable // used for creating new Observable -} - -func (l *tsLevel) Clear() { - l.oldest = 0 - l.newest = len(l.buckets) - 1 - l.end = time.Time{} - for i := range l.buckets { - if l.buckets[i] != nil { - l.buckets[i].Clear() - l.buckets[i] = nil - } - } -} - -func (l *tsLevel) InitLevel(size time.Duration, numBuckets int, f func() Observable) { - l.size = size - l.provider = f - l.buckets = make([]Observable, numBuckets) -} - -// Keeps a sequence of levels. Each level is responsible for storing data at -// a given resolution. For example, the first level stores data at a one -// minute resolution while the second level stores data at a one hour -// resolution. - -// Each level is represented by a sequence of buckets. Each bucket spans an -// interval equal to the resolution of the level. New observations are added -// to the last bucket. -type timeSeries struct { - provider func() Observable // make more Observable - numBuckets int // number of buckets in each level - levels []*tsLevel // levels of bucketed Observable - lastAdd time.Time // time of last Observable tracked - total Observable // convenient aggregation of all Observable - clock Clock // Clock for getting current time - pending Observable // observations not yet bucketed - pendingTime time.Time // what time are we keeping in pending - dirty bool // if there are pending observations -} - -// init initializes a level according to the supplied criteria. -func (ts *timeSeries) init(resolutions []time.Duration, f func() Observable, numBuckets int, clock Clock) { - ts.provider = f - ts.numBuckets = numBuckets - ts.clock = clock - ts.levels = make([]*tsLevel, len(resolutions)) - - for i := range resolutions { - if i > 0 && resolutions[i-1] >= resolutions[i] { - log.Print("timeseries: resolutions must be monotonically increasing") - break - } - newLevel := new(tsLevel) - newLevel.InitLevel(resolutions[i], ts.numBuckets, ts.provider) - ts.levels[i] = newLevel - } - - ts.Clear() -} - -// Clear removes all observations from the time series. -func (ts *timeSeries) Clear() { - ts.lastAdd = time.Time{} - ts.total = ts.resetObservation(ts.total) - ts.pending = ts.resetObservation(ts.pending) - ts.pendingTime = time.Time{} - ts.dirty = false - - for i := range ts.levels { - ts.levels[i].Clear() - } -} - -// Add records an observation at the current time. -func (ts *timeSeries) Add(observation Observable) { - ts.AddWithTime(observation, ts.clock.Time()) -} - -// AddWithTime records an observation at the specified time. -func (ts *timeSeries) AddWithTime(observation Observable, t time.Time) { - - smallBucketDuration := ts.levels[0].size - - if t.After(ts.lastAdd) { - ts.lastAdd = t - } - - if t.After(ts.pendingTime) { - ts.advance(t) - ts.mergePendingUpdates() - ts.pendingTime = ts.levels[0].end - ts.pending.CopyFrom(observation) - ts.dirty = true - } else if t.After(ts.pendingTime.Add(-1 * smallBucketDuration)) { - // The observation is close enough to go into the pending bucket. - // This compensates for clock skewing and small scheduling delays - // by letting the update stay in the fast path. - ts.pending.Add(observation) - ts.dirty = true - } else { - ts.mergeValue(observation, t) - } -} - -// mergeValue inserts the observation at the specified time in the past into all levels. -func (ts *timeSeries) mergeValue(observation Observable, t time.Time) { - for _, level := range ts.levels { - index := (ts.numBuckets - 1) - int(level.end.Sub(t)/level.size) - if 0 <= index && index < ts.numBuckets { - bucketNumber := (level.oldest + index) % ts.numBuckets - if level.buckets[bucketNumber] == nil { - level.buckets[bucketNumber] = level.provider() - } - level.buckets[bucketNumber].Add(observation) - } - } - ts.total.Add(observation) -} - -// mergePendingUpdates applies the pending updates into all levels. -func (ts *timeSeries) mergePendingUpdates() { - if ts.dirty { - ts.mergeValue(ts.pending, ts.pendingTime) - ts.pending = ts.resetObservation(ts.pending) - ts.dirty = false - } -} - -// advance cycles the buckets at each level until the latest bucket in -// each level can hold the time specified. -func (ts *timeSeries) advance(t time.Time) { - if !t.After(ts.levels[0].end) { - return - } - for i := 0; i < len(ts.levels); i++ { - level := ts.levels[i] - if !level.end.Before(t) { - break - } - - // If the time is sufficiently far, just clear the level and advance - // directly. - if !t.Before(level.end.Add(level.size * time.Duration(ts.numBuckets))) { - for _, b := range level.buckets { - ts.resetObservation(b) - } - level.end = time.Unix(0, (t.UnixNano()/level.size.Nanoseconds())*level.size.Nanoseconds()) - } - - for t.After(level.end) { - level.end = level.end.Add(level.size) - level.newest = level.oldest - level.oldest = (level.oldest + 1) % ts.numBuckets - ts.resetObservation(level.buckets[level.newest]) - } - - t = level.end - } -} - -// Latest returns the sum of the num latest buckets from the level. -func (ts *timeSeries) Latest(level, num int) Observable { - now := ts.clock.Time() - if ts.levels[0].end.Before(now) { - ts.advance(now) - } - - ts.mergePendingUpdates() - - result := ts.provider() - l := ts.levels[level] - index := l.newest - - for i := 0; i < num; i++ { - if l.buckets[index] != nil { - result.Add(l.buckets[index]) - } - if index == 0 { - index = ts.numBuckets - } - index-- - } - - return result -} - -// LatestBuckets returns a copy of the num latest buckets from level. -func (ts *timeSeries) LatestBuckets(level, num int) []Observable { - if level < 0 || level > len(ts.levels) { - log.Print("timeseries: bad level argument: ", level) - return nil - } - if num < 0 || num >= ts.numBuckets { - log.Print("timeseries: bad num argument: ", num) - return nil - } - - results := make([]Observable, num) - now := ts.clock.Time() - if ts.levels[0].end.Before(now) { - ts.advance(now) - } - - ts.mergePendingUpdates() - - l := ts.levels[level] - index := l.newest - - for i := 0; i < num; i++ { - result := ts.provider() - results[i] = result - if l.buckets[index] != nil { - result.CopyFrom(l.buckets[index]) - } - - if index == 0 { - index = ts.numBuckets - } - index -= 1 - } - return results -} - -// ScaleBy updates observations by scaling by factor. -func (ts *timeSeries) ScaleBy(factor float64) { - for _, l := range ts.levels { - for i := 0; i < ts.numBuckets; i++ { - l.buckets[i].Multiply(factor) - } - } - - ts.total.Multiply(factor) - ts.pending.Multiply(factor) -} - -// Range returns the sum of observations added over the specified time range. -// If start or finish times don't fall on bucket boundaries of the same -// level, then return values are approximate answers. -func (ts *timeSeries) Range(start, finish time.Time) Observable { - return ts.ComputeRange(start, finish, 1)[0] -} - -// Recent returns the sum of observations from the last delta. -func (ts *timeSeries) Recent(delta time.Duration) Observable { - now := ts.clock.Time() - return ts.Range(now.Add(-delta), now) -} - -// Total returns the total of all observations. -func (ts *timeSeries) Total() Observable { - ts.mergePendingUpdates() - return ts.total -} - -// ComputeRange computes a specified number of values into a slice using -// the observations recorded over the specified time period. The return -// values are approximate if the start or finish times don't fall on the -// bucket boundaries at the same level or if the number of buckets spanning -// the range is not an integral multiple of num. -func (ts *timeSeries) ComputeRange(start, finish time.Time, num int) []Observable { - if start.After(finish) { - log.Printf("timeseries: start > finish, %v>%v", start, finish) - return nil - } - - if num < 0 { - log.Printf("timeseries: num < 0, %v", num) - return nil - } - - results := make([]Observable, num) - - for _, l := range ts.levels { - if !start.Before(l.end.Add(-l.size * time.Duration(ts.numBuckets))) { - ts.extract(l, start, finish, num, results) - return results - } - } - - // Failed to find a level that covers the desired range. So just - // extract from the last level, even if it doesn't cover the entire - // desired range. - ts.extract(ts.levels[len(ts.levels)-1], start, finish, num, results) - - return results -} - -// RecentList returns the specified number of values in slice over the most -// recent time period of the specified range. -func (ts *timeSeries) RecentList(delta time.Duration, num int) []Observable { - if delta < 0 { - return nil - } - now := ts.clock.Time() - return ts.ComputeRange(now.Add(-delta), now, num) -} - -// extract returns a slice of specified number of observations from a given -// level over a given range. -func (ts *timeSeries) extract(l *tsLevel, start, finish time.Time, num int, results []Observable) { - ts.mergePendingUpdates() - - srcInterval := l.size - dstInterval := finish.Sub(start) / time.Duration(num) - dstStart := start - srcStart := l.end.Add(-srcInterval * time.Duration(ts.numBuckets)) - - srcIndex := 0 - - // Where should scanning start? - if dstStart.After(srcStart) { - advance := dstStart.Sub(srcStart) / srcInterval - srcIndex += int(advance) - srcStart = srcStart.Add(advance * srcInterval) - } - - // The i'th value is computed as show below. - // interval = (finish/start)/num - // i'th value = sum of observation in range - // [ start + i * interval, - // start + (i + 1) * interval ) - for i := 0; i < num; i++ { - results[i] = ts.resetObservation(results[i]) - dstEnd := dstStart.Add(dstInterval) - for srcIndex < ts.numBuckets && srcStart.Before(dstEnd) { - srcEnd := srcStart.Add(srcInterval) - if srcEnd.After(ts.lastAdd) { - srcEnd = ts.lastAdd - } - - if !srcEnd.Before(dstStart) { - srcValue := l.buckets[(srcIndex+l.oldest)%ts.numBuckets] - if !srcStart.Before(dstStart) && !srcEnd.After(dstEnd) { - // dst completely contains src. - if srcValue != nil { - results[i].Add(srcValue) - } - } else { - // dst partially overlaps src. - overlapStart := maxTime(srcStart, dstStart) - overlapEnd := minTime(srcEnd, dstEnd) - base := srcEnd.Sub(srcStart) - fraction := overlapEnd.Sub(overlapStart).Seconds() / base.Seconds() - - used := ts.provider() - if srcValue != nil { - used.CopyFrom(srcValue) - } - used.Multiply(fraction) - results[i].Add(used) - } - - if srcEnd.After(dstEnd) { - break - } - } - srcIndex++ - srcStart = srcStart.Add(srcInterval) - } - dstStart = dstStart.Add(dstInterval) - } -} - -// resetObservation clears the content so the struct may be reused. -func (ts *timeSeries) resetObservation(observation Observable) Observable { - if observation == nil { - observation = ts.provider() - } else { - observation.Clear() - } - return observation -} - -// TimeSeries tracks data at granularities from 1 second to 16 weeks. -type TimeSeries struct { - timeSeries -} - -// NewTimeSeries creates a new TimeSeries using the function provided for creating new Observable. -func NewTimeSeries(f func() Observable) *TimeSeries { - return NewTimeSeriesWithClock(f, defaultClockInstance) -} - -// NewTimeSeriesWithClock creates a new TimeSeries using the function provided for creating new Observable and the clock for -// assigning timestamps. -func NewTimeSeriesWithClock(f func() Observable, clock Clock) *TimeSeries { - ts := new(TimeSeries) - ts.timeSeries.init(timeSeriesResolutions, f, timeSeriesNumBuckets, clock) - return ts -} - -// MinuteHourSeries tracks data at granularities of 1 minute and 1 hour. -type MinuteHourSeries struct { - timeSeries -} - -// NewMinuteHourSeries creates a new MinuteHourSeries using the function provided for creating new Observable. -func NewMinuteHourSeries(f func() Observable) *MinuteHourSeries { - return NewMinuteHourSeriesWithClock(f, defaultClockInstance) -} - -// NewMinuteHourSeriesWithClock creates a new MinuteHourSeries using the function provided for creating new Observable and the clock for -// assigning timestamps. -func NewMinuteHourSeriesWithClock(f func() Observable, clock Clock) *MinuteHourSeries { - ts := new(MinuteHourSeries) - ts.timeSeries.init(minuteHourSeriesResolutions, f, - minuteHourSeriesNumBuckets, clock) - return ts -} - -func (ts *MinuteHourSeries) Minute() Observable { - return ts.timeSeries.Latest(0, 60) -} - -func (ts *MinuteHourSeries) Hour() Observable { - return ts.timeSeries.Latest(1, 60) -} - -func minTime(a, b time.Time) time.Time { - if a.Before(b) { - return a - } - return b -} - -func maxTime(a, b time.Time) time.Time { - if a.After(b) { - return a - } - return b -} diff --git a/vendor/golang.org/x/net/trace/events.go b/vendor/golang.org/x/net/trace/events.go deleted file mode 100644 index c646a6952e5..00000000000 --- a/vendor/golang.org/x/net/trace/events.go +++ /dev/null @@ -1,532 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package trace - -import ( - "bytes" - "fmt" - "html/template" - "io" - "log" - "net/http" - "runtime" - "sort" - "strconv" - "strings" - "sync" - "sync/atomic" - "text/tabwriter" - "time" -) - -const maxEventsPerLog = 100 - -type bucket struct { - MaxErrAge time.Duration - String string -} - -var buckets = []bucket{ - {0, "total"}, - {10 * time.Second, "errs<10s"}, - {1 * time.Minute, "errs<1m"}, - {10 * time.Minute, "errs<10m"}, - {1 * time.Hour, "errs<1h"}, - {10 * time.Hour, "errs<10h"}, - {24000 * time.Hour, "errors"}, -} - -// RenderEvents renders the HTML page typically served at /debug/events. -// It does not do any auth checking. The request may be nil. -// -// Most users will use the Events handler. -func RenderEvents(w http.ResponseWriter, req *http.Request, sensitive bool) { - now := time.Now() - data := &struct { - Families []string // family names - Buckets []bucket - Counts [][]int // eventLog count per family/bucket - - // Set when a bucket has been selected. - Family string - Bucket int - EventLogs eventLogs - Expanded bool - }{ - Buckets: buckets, - } - - data.Families = make([]string, 0, len(families)) - famMu.RLock() - for name := range families { - data.Families = append(data.Families, name) - } - famMu.RUnlock() - sort.Strings(data.Families) - - // Count the number of eventLogs in each family for each error age. - data.Counts = make([][]int, len(data.Families)) - for i, name := range data.Families { - // TODO(sameer): move this loop under the family lock. - f := getEventFamily(name) - data.Counts[i] = make([]int, len(data.Buckets)) - for j, b := range data.Buckets { - data.Counts[i][j] = f.Count(now, b.MaxErrAge) - } - } - - if req != nil { - var ok bool - data.Family, data.Bucket, ok = parseEventsArgs(req) - if !ok { - // No-op - } else { - data.EventLogs = getEventFamily(data.Family).Copy(now, buckets[data.Bucket].MaxErrAge) - } - if data.EventLogs != nil { - defer data.EventLogs.Free() - sort.Sort(data.EventLogs) - } - if exp, err := strconv.ParseBool(req.FormValue("exp")); err == nil { - data.Expanded = exp - } - } - - famMu.RLock() - defer famMu.RUnlock() - if err := eventsTmpl().Execute(w, data); err != nil { - log.Printf("net/trace: Failed executing template: %v", err) - } -} - -func parseEventsArgs(req *http.Request) (fam string, b int, ok bool) { - fam, bStr := req.FormValue("fam"), req.FormValue("b") - if fam == "" || bStr == "" { - return "", 0, false - } - b, err := strconv.Atoi(bStr) - if err != nil || b < 0 || b >= len(buckets) { - return "", 0, false - } - return fam, b, true -} - -// An EventLog provides a log of events associated with a specific object. -type EventLog interface { - // Printf formats its arguments with fmt.Sprintf and adds the - // result to the event log. - Printf(format string, a ...interface{}) - - // Errorf is like Printf, but it marks this event as an error. - Errorf(format string, a ...interface{}) - - // Finish declares that this event log is complete. - // The event log should not be used after calling this method. - Finish() -} - -// NewEventLog returns a new EventLog with the specified family name -// and title. -func NewEventLog(family, title string) EventLog { - el := newEventLog() - el.ref() - el.Family, el.Title = family, title - el.Start = time.Now() - el.events = make([]logEntry, 0, maxEventsPerLog) - el.stack = make([]uintptr, 32) - n := runtime.Callers(2, el.stack) - el.stack = el.stack[:n] - - getEventFamily(family).add(el) - return el -} - -func (el *eventLog) Finish() { - getEventFamily(el.Family).remove(el) - el.unref() // matches ref in New -} - -var ( - famMu sync.RWMutex - families = make(map[string]*eventFamily) // family name => family -) - -func getEventFamily(fam string) *eventFamily { - famMu.Lock() - defer famMu.Unlock() - f := families[fam] - if f == nil { - f = &eventFamily{} - families[fam] = f - } - return f -} - -type eventFamily struct { - mu sync.RWMutex - eventLogs eventLogs -} - -func (f *eventFamily) add(el *eventLog) { - f.mu.Lock() - f.eventLogs = append(f.eventLogs, el) - f.mu.Unlock() -} - -func (f *eventFamily) remove(el *eventLog) { - f.mu.Lock() - defer f.mu.Unlock() - for i, el0 := range f.eventLogs { - if el == el0 { - copy(f.eventLogs[i:], f.eventLogs[i+1:]) - f.eventLogs = f.eventLogs[:len(f.eventLogs)-1] - return - } - } -} - -func (f *eventFamily) Count(now time.Time, maxErrAge time.Duration) (n int) { - f.mu.RLock() - defer f.mu.RUnlock() - for _, el := range f.eventLogs { - if el.hasRecentError(now, maxErrAge) { - n++ - } - } - return -} - -func (f *eventFamily) Copy(now time.Time, maxErrAge time.Duration) (els eventLogs) { - f.mu.RLock() - defer f.mu.RUnlock() - els = make(eventLogs, 0, len(f.eventLogs)) - for _, el := range f.eventLogs { - if el.hasRecentError(now, maxErrAge) { - el.ref() - els = append(els, el) - } - } - return -} - -type eventLogs []*eventLog - -// Free calls unref on each element of the list. -func (els eventLogs) Free() { - for _, el := range els { - el.unref() - } -} - -// eventLogs may be sorted in reverse chronological order. -func (els eventLogs) Len() int { return len(els) } -func (els eventLogs) Less(i, j int) bool { return els[i].Start.After(els[j].Start) } -func (els eventLogs) Swap(i, j int) { els[i], els[j] = els[j], els[i] } - -// A logEntry is a timestamped log entry in an event log. -type logEntry struct { - When time.Time - Elapsed time.Duration // since previous event in log - NewDay bool // whether this event is on a different day to the previous event - What string - IsErr bool -} - -// WhenString returns a string representation of the elapsed time of the event. -// It will include the date if midnight was crossed. -func (e logEntry) WhenString() string { - if e.NewDay { - return e.When.Format("2006/01/02 15:04:05.000000") - } - return e.When.Format("15:04:05.000000") -} - -// An eventLog represents an active event log. -type eventLog struct { - // Family is the top-level grouping of event logs to which this belongs. - Family string - - // Title is the title of this event log. - Title string - - // Timing information. - Start time.Time - - // Call stack where this event log was created. - stack []uintptr - - // Append-only sequence of events. - // - // TODO(sameer): change this to a ring buffer to avoid the array copy - // when we hit maxEventsPerLog. - mu sync.RWMutex - events []logEntry - LastErrorTime time.Time - discarded int - - refs int32 // how many buckets this is in -} - -func (el *eventLog) reset() { - // Clear all but the mutex. Mutexes may not be copied, even when unlocked. - el.Family = "" - el.Title = "" - el.Start = time.Time{} - el.stack = nil - el.events = nil - el.LastErrorTime = time.Time{} - el.discarded = 0 - el.refs = 0 -} - -func (el *eventLog) hasRecentError(now time.Time, maxErrAge time.Duration) bool { - if maxErrAge == 0 { - return true - } - el.mu.RLock() - defer el.mu.RUnlock() - return now.Sub(el.LastErrorTime) < maxErrAge -} - -// delta returns the elapsed time since the last event or the log start, -// and whether it spans midnight. -// L >= el.mu -func (el *eventLog) delta(t time.Time) (time.Duration, bool) { - if len(el.events) == 0 { - return t.Sub(el.Start), false - } - prev := el.events[len(el.events)-1].When - return t.Sub(prev), prev.Day() != t.Day() - -} - -func (el *eventLog) Printf(format string, a ...interface{}) { - el.printf(false, format, a...) -} - -func (el *eventLog) Errorf(format string, a ...interface{}) { - el.printf(true, format, a...) -} - -func (el *eventLog) printf(isErr bool, format string, a ...interface{}) { - e := logEntry{When: time.Now(), IsErr: isErr, What: fmt.Sprintf(format, a...)} - el.mu.Lock() - e.Elapsed, e.NewDay = el.delta(e.When) - if len(el.events) < maxEventsPerLog { - el.events = append(el.events, e) - } else { - // Discard the oldest event. - if el.discarded == 0 { - // el.discarded starts at two to count for the event it - // is replacing, plus the next one that we are about to - // drop. - el.discarded = 2 - } else { - el.discarded++ - } - // TODO(sameer): if this causes allocations on a critical path, - // change eventLog.What to be a fmt.Stringer, as in trace.go. - el.events[0].What = fmt.Sprintf("(%d events discarded)", el.discarded) - // The timestamp of the discarded meta-event should be - // the time of the last event it is representing. - el.events[0].When = el.events[1].When - copy(el.events[1:], el.events[2:]) - el.events[maxEventsPerLog-1] = e - } - if e.IsErr { - el.LastErrorTime = e.When - } - el.mu.Unlock() -} - -func (el *eventLog) ref() { - atomic.AddInt32(&el.refs, 1) -} - -func (el *eventLog) unref() { - if atomic.AddInt32(&el.refs, -1) == 0 { - freeEventLog(el) - } -} - -func (el *eventLog) When() string { - return el.Start.Format("2006/01/02 15:04:05.000000") -} - -func (el *eventLog) ElapsedTime() string { - elapsed := time.Since(el.Start) - return fmt.Sprintf("%.6f", elapsed.Seconds()) -} - -func (el *eventLog) Stack() string { - buf := new(bytes.Buffer) - tw := tabwriter.NewWriter(buf, 1, 8, 1, '\t', 0) - printStackRecord(tw, el.stack) - tw.Flush() - return buf.String() -} - -// printStackRecord prints the function + source line information -// for a single stack trace. -// Adapted from runtime/pprof/pprof.go. -func printStackRecord(w io.Writer, stk []uintptr) { - for _, pc := range stk { - f := runtime.FuncForPC(pc) - if f == nil { - continue - } - file, line := f.FileLine(pc) - name := f.Name() - // Hide runtime.goexit and any runtime functions at the beginning. - if strings.HasPrefix(name, "runtime.") { - continue - } - fmt.Fprintf(w, "# %s\t%s:%d\n", name, file, line) - } -} - -func (el *eventLog) Events() []logEntry { - el.mu.RLock() - defer el.mu.RUnlock() - return el.events -} - -// freeEventLogs is a freelist of *eventLog -var freeEventLogs = make(chan *eventLog, 1000) - -// newEventLog returns a event log ready to use. -func newEventLog() *eventLog { - select { - case el := <-freeEventLogs: - return el - default: - return new(eventLog) - } -} - -// freeEventLog adds el to freeEventLogs if there's room. -// This is non-blocking. -func freeEventLog(el *eventLog) { - el.reset() - select { - case freeEventLogs <- el: - default: - } -} - -var eventsTmplCache *template.Template -var eventsTmplOnce sync.Once - -func eventsTmpl() *template.Template { - eventsTmplOnce.Do(func() { - eventsTmplCache = template.Must(template.New("events").Funcs(template.FuncMap{ - "elapsed": elapsed, - "trimSpace": strings.TrimSpace, - }).Parse(eventsHTML)) - }) - return eventsTmplCache -} - -const eventsHTML = ` - - - events - - - - -

/debug/events

- - - {{range $i, $fam := .Families}} - - - - {{range $j, $bucket := $.Buckets}} - {{$n := index $.Counts $i $j}} - - {{end}} - - {{end}} -
{{$fam}} - {{if $n}}{{end}} - [{{$n}} {{$bucket.String}}] - {{if $n}}{{end}} -
- -{{if $.EventLogs}} -
-

Family: {{$.Family}}

- -{{if $.Expanded}}{{end}} -[Summary]{{if $.Expanded}}{{end}} - -{{if not $.Expanded}}{{end}} -[Expanded]{{if not $.Expanded}}{{end}} - - - - {{range $el := $.EventLogs}} - - - - - {{if $.Expanded}} - - - - - - {{range $el.Events}} - - - - - - {{end}} - {{end}} - {{end}} -
WhenElapsed
{{$el.When}}{{$el.ElapsedTime}}{{$el.Title}} -
{{$el.Stack|trimSpace}}
{{.WhenString}}{{elapsed .Elapsed}}.{{if .IsErr}}E{{else}}.{{end}}. {{.What}}
-{{end}} - - -` diff --git a/vendor/golang.org/x/net/trace/histogram.go b/vendor/golang.org/x/net/trace/histogram.go deleted file mode 100644 index 9bf4286c794..00000000000 --- a/vendor/golang.org/x/net/trace/histogram.go +++ /dev/null @@ -1,365 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package trace - -// This file implements histogramming for RPC statistics collection. - -import ( - "bytes" - "fmt" - "html/template" - "log" - "math" - "sync" - - "golang.org/x/net/internal/timeseries" -) - -const ( - bucketCount = 38 -) - -// histogram keeps counts of values in buckets that are spaced -// out in powers of 2: 0-1, 2-3, 4-7... -// histogram implements timeseries.Observable -type histogram struct { - sum int64 // running total of measurements - sumOfSquares float64 // square of running total - buckets []int64 // bucketed values for histogram - value int // holds a single value as an optimization - valueCount int64 // number of values recorded for single value -} - -// AddMeasurement records a value measurement observation to the histogram. -func (h *histogram) addMeasurement(value int64) { - // TODO: assert invariant - h.sum += value - h.sumOfSquares += float64(value) * float64(value) - - bucketIndex := getBucket(value) - - if h.valueCount == 0 || (h.valueCount > 0 && h.value == bucketIndex) { - h.value = bucketIndex - h.valueCount++ - } else { - h.allocateBuckets() - h.buckets[bucketIndex]++ - } -} - -func (h *histogram) allocateBuckets() { - if h.buckets == nil { - h.buckets = make([]int64, bucketCount) - h.buckets[h.value] = h.valueCount - h.value = 0 - h.valueCount = -1 - } -} - -func log2(i int64) int { - n := 0 - for ; i >= 0x100; i >>= 8 { - n += 8 - } - for ; i > 0; i >>= 1 { - n += 1 - } - return n -} - -func getBucket(i int64) (index int) { - index = log2(i) - 1 - if index < 0 { - index = 0 - } - if index >= bucketCount { - index = bucketCount - 1 - } - return -} - -// Total returns the number of recorded observations. -func (h *histogram) total() (total int64) { - if h.valueCount >= 0 { - total = h.valueCount - } - for _, val := range h.buckets { - total += int64(val) - } - return -} - -// Average returns the average value of recorded observations. -func (h *histogram) average() float64 { - t := h.total() - if t == 0 { - return 0 - } - return float64(h.sum) / float64(t) -} - -// Variance returns the variance of recorded observations. -func (h *histogram) variance() float64 { - t := float64(h.total()) - if t == 0 { - return 0 - } - s := float64(h.sum) / t - return h.sumOfSquares/t - s*s -} - -// StandardDeviation returns the standard deviation of recorded observations. -func (h *histogram) standardDeviation() float64 { - return math.Sqrt(h.variance()) -} - -// PercentileBoundary estimates the value that the given fraction of recorded -// observations are less than. -func (h *histogram) percentileBoundary(percentile float64) int64 { - total := h.total() - - // Corner cases (make sure result is strictly less than Total()) - if total == 0 { - return 0 - } else if total == 1 { - return int64(h.average()) - } - - percentOfTotal := round(float64(total) * percentile) - var runningTotal int64 - - for i := range h.buckets { - value := h.buckets[i] - runningTotal += value - if runningTotal == percentOfTotal { - // We hit an exact bucket boundary. If the next bucket has data, it is a - // good estimate of the value. If the bucket is empty, we interpolate the - // midpoint between the next bucket's boundary and the next non-zero - // bucket. If the remaining buckets are all empty, then we use the - // boundary for the next bucket as the estimate. - j := uint8(i + 1) - min := bucketBoundary(j) - if runningTotal < total { - for h.buckets[j] == 0 { - j++ - } - } - max := bucketBoundary(j) - return min + round(float64(max-min)/2) - } else if runningTotal > percentOfTotal { - // The value is in this bucket. Interpolate the value. - delta := runningTotal - percentOfTotal - percentBucket := float64(value-delta) / float64(value) - bucketMin := bucketBoundary(uint8(i)) - nextBucketMin := bucketBoundary(uint8(i + 1)) - bucketSize := nextBucketMin - bucketMin - return bucketMin + round(percentBucket*float64(bucketSize)) - } - } - return bucketBoundary(bucketCount - 1) -} - -// Median returns the estimated median of the observed values. -func (h *histogram) median() int64 { - return h.percentileBoundary(0.5) -} - -// Add adds other to h. -func (h *histogram) Add(other timeseries.Observable) { - o := other.(*histogram) - if o.valueCount == 0 { - // Other histogram is empty - } else if h.valueCount >= 0 && o.valueCount > 0 && h.value == o.value { - // Both have a single bucketed value, aggregate them - h.valueCount += o.valueCount - } else { - // Two different values necessitate buckets in this histogram - h.allocateBuckets() - if o.valueCount >= 0 { - h.buckets[o.value] += o.valueCount - } else { - for i := range h.buckets { - h.buckets[i] += o.buckets[i] - } - } - } - h.sumOfSquares += o.sumOfSquares - h.sum += o.sum -} - -// Clear resets the histogram to an empty state, removing all observed values. -func (h *histogram) Clear() { - h.buckets = nil - h.value = 0 - h.valueCount = 0 - h.sum = 0 - h.sumOfSquares = 0 -} - -// CopyFrom copies from other, which must be a *histogram, into h. -func (h *histogram) CopyFrom(other timeseries.Observable) { - o := other.(*histogram) - if o.valueCount == -1 { - h.allocateBuckets() - copy(h.buckets, o.buckets) - } - h.sum = o.sum - h.sumOfSquares = o.sumOfSquares - h.value = o.value - h.valueCount = o.valueCount -} - -// Multiply scales the histogram by the specified ratio. -func (h *histogram) Multiply(ratio float64) { - if h.valueCount == -1 { - for i := range h.buckets { - h.buckets[i] = int64(float64(h.buckets[i]) * ratio) - } - } else { - h.valueCount = int64(float64(h.valueCount) * ratio) - } - h.sum = int64(float64(h.sum) * ratio) - h.sumOfSquares = h.sumOfSquares * ratio -} - -// New creates a new histogram. -func (h *histogram) New() timeseries.Observable { - r := new(histogram) - r.Clear() - return r -} - -func (h *histogram) String() string { - return fmt.Sprintf("%d, %f, %d, %d, %v", - h.sum, h.sumOfSquares, h.value, h.valueCount, h.buckets) -} - -// round returns the closest int64 to the argument -func round(in float64) int64 { - return int64(math.Floor(in + 0.5)) -} - -// bucketBoundary returns the first value in the bucket. -func bucketBoundary(bucket uint8) int64 { - if bucket == 0 { - return 0 - } - return 1 << bucket -} - -// bucketData holds data about a specific bucket for use in distTmpl. -type bucketData struct { - Lower, Upper int64 - N int64 - Pct, CumulativePct float64 - GraphWidth int -} - -// data holds data about a Distribution for use in distTmpl. -type data struct { - Buckets []*bucketData - Count, Median int64 - Mean, StandardDeviation float64 -} - -// maxHTMLBarWidth is the maximum width of the HTML bar for visualizing buckets. -const maxHTMLBarWidth = 350.0 - -// newData returns data representing h for use in distTmpl. -func (h *histogram) newData() *data { - // Force the allocation of buckets to simplify the rendering implementation - h.allocateBuckets() - // We scale the bars on the right so that the largest bar is - // maxHTMLBarWidth pixels in width. - maxBucket := int64(0) - for _, n := range h.buckets { - if n > maxBucket { - maxBucket = n - } - } - total := h.total() - barsizeMult := maxHTMLBarWidth / float64(maxBucket) - var pctMult float64 - if total == 0 { - pctMult = 1.0 - } else { - pctMult = 100.0 / float64(total) - } - - buckets := make([]*bucketData, len(h.buckets)) - runningTotal := int64(0) - for i, n := range h.buckets { - if n == 0 { - continue - } - runningTotal += n - var upperBound int64 - if i < bucketCount-1 { - upperBound = bucketBoundary(uint8(i + 1)) - } else { - upperBound = math.MaxInt64 - } - buckets[i] = &bucketData{ - Lower: bucketBoundary(uint8(i)), - Upper: upperBound, - N: n, - Pct: float64(n) * pctMult, - CumulativePct: float64(runningTotal) * pctMult, - GraphWidth: int(float64(n) * barsizeMult), - } - } - return &data{ - Buckets: buckets, - Count: total, - Median: h.median(), - Mean: h.average(), - StandardDeviation: h.standardDeviation(), - } -} - -func (h *histogram) html() template.HTML { - buf := new(bytes.Buffer) - if err := distTmpl().Execute(buf, h.newData()); err != nil { - buf.Reset() - log.Printf("net/trace: couldn't execute template: %v", err) - } - return template.HTML(buf.String()) -} - -var distTmplCache *template.Template -var distTmplOnce sync.Once - -func distTmpl() *template.Template { - distTmplOnce.Do(func() { - // Input: data - distTmplCache = template.Must(template.New("distTmpl").Parse(` - - - - - - - -
Count: {{.Count}}Mean: {{printf "%.0f" .Mean}}StdDev: {{printf "%.0f" .StandardDeviation}}Median: {{.Median}}
-
- -{{range $b := .Buckets}} -{{if $b}} - - - - - - - - - -{{end}} -{{end}} -
[{{.Lower}},{{.Upper}}){{.N}}{{printf "%#.3f" .Pct}}%{{printf "%#.3f" .CumulativePct}}%
-`)) - }) - return distTmplCache -} diff --git a/vendor/golang.org/x/net/trace/trace.go b/vendor/golang.org/x/net/trace/trace.go deleted file mode 100644 index a46ee0eaa31..00000000000 --- a/vendor/golang.org/x/net/trace/trace.go +++ /dev/null @@ -1,1103 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -Package trace implements tracing of requests and long-lived objects. -It exports HTTP interfaces on /debug/requests and /debug/events. - -A trace.Trace provides tracing for short-lived objects, usually requests. -A request handler might be implemented like this: - - func fooHandler(w http.ResponseWriter, req *http.Request) { - tr := trace.New("mypkg.Foo", req.URL.Path) - defer tr.Finish() - ... - tr.LazyPrintf("some event %q happened", str) - ... - if err := somethingImportant(); err != nil { - tr.LazyPrintf("somethingImportant failed: %v", err) - tr.SetError() - } - } - -The /debug/requests HTTP endpoint organizes the traces by family, -errors, and duration. It also provides histogram of request duration -for each family. - -A trace.EventLog provides tracing for long-lived objects, such as RPC -connections. - - // A Fetcher fetches URL paths for a single domain. - type Fetcher struct { - domain string - events trace.EventLog - } - - func NewFetcher(domain string) *Fetcher { - return &Fetcher{ - domain, - trace.NewEventLog("mypkg.Fetcher", domain), - } - } - - func (f *Fetcher) Fetch(path string) (string, error) { - resp, err := http.Get("http://" + f.domain + "/" + path) - if err != nil { - f.events.Errorf("Get(%q) = %v", path, err) - return "", err - } - f.events.Printf("Get(%q) = %s", path, resp.Status) - ... - } - - func (f *Fetcher) Close() error { - f.events.Finish() - return nil - } - -The /debug/events HTTP endpoint organizes the event logs by family and -by time since the last error. The expanded view displays recent log -entries and the log's call stack. -*/ -package trace // import "golang.org/x/net/trace" - -import ( - "bytes" - "fmt" - "html/template" - "io" - "log" - "net" - "net/http" - "runtime" - "sort" - "strconv" - "sync" - "sync/atomic" - "time" - - "golang.org/x/net/internal/timeseries" -) - -// DebugUseAfterFinish controls whether to debug uses of Trace values after finishing. -// FOR DEBUGGING ONLY. This will slow down the program. -var DebugUseAfterFinish = false - -// AuthRequest determines whether a specific request is permitted to load the -// /debug/requests or /debug/events pages. -// -// It returns two bools; the first indicates whether the page may be viewed at all, -// and the second indicates whether sensitive events will be shown. -// -// AuthRequest may be replaced by a program to customize its authorization requirements. -// -// The default AuthRequest function returns (true, true) if and only if the request -// comes from localhost/127.0.0.1/[::1]. -var AuthRequest = func(req *http.Request) (any, sensitive bool) { - // RemoteAddr is commonly in the form "IP" or "IP:port". - // If it is in the form "IP:port", split off the port. - host, _, err := net.SplitHostPort(req.RemoteAddr) - if err != nil { - host = req.RemoteAddr - } - switch host { - case "localhost", "127.0.0.1", "::1": - return true, true - default: - return false, false - } -} - -func init() { - // TODO(jbd): Serve Traces from /debug/traces in the future? - // There is no requirement for a request to be present to have traces. - http.HandleFunc("/debug/requests", Traces) - http.HandleFunc("/debug/events", Events) -} - -// Traces responds with traces from the program. -// The package initialization registers it in http.DefaultServeMux -// at /debug/requests. -// -// It performs authorization by running AuthRequest. -func Traces(w http.ResponseWriter, req *http.Request) { - any, sensitive := AuthRequest(req) - if !any { - http.Error(w, "not allowed", http.StatusUnauthorized) - return - } - w.Header().Set("Content-Type", "text/html; charset=utf-8") - Render(w, req, sensitive) -} - -// Events responds with a page of events collected by EventLogs. -// The package initialization registers it in http.DefaultServeMux -// at /debug/events. -// -// It performs authorization by running AuthRequest. -func Events(w http.ResponseWriter, req *http.Request) { - any, sensitive := AuthRequest(req) - if !any { - http.Error(w, "not allowed", http.StatusUnauthorized) - return - } - w.Header().Set("Content-Type", "text/html; charset=utf-8") - RenderEvents(w, req, sensitive) -} - -// Render renders the HTML page typically served at /debug/requests. -// It does not do any auth checking. The request may be nil. -// -// Most users will use the Traces handler. -func Render(w io.Writer, req *http.Request, sensitive bool) { - data := &struct { - Families []string - ActiveTraceCount map[string]int - CompletedTraces map[string]*family - - // Set when a bucket has been selected. - Traces traceList - Family string - Bucket int - Expanded bool - Traced bool - Active bool - ShowSensitive bool // whether to show sensitive events - - Histogram template.HTML - HistogramWindow string // e.g. "last minute", "last hour", "all time" - - // If non-zero, the set of traces is a partial set, - // and this is the total number. - Total int - }{ - CompletedTraces: completedTraces, - } - - data.ShowSensitive = sensitive - if req != nil { - // Allow show_sensitive=0 to force hiding of sensitive data for testing. - // This only goes one way; you can't use show_sensitive=1 to see things. - if req.FormValue("show_sensitive") == "0" { - data.ShowSensitive = false - } - - if exp, err := strconv.ParseBool(req.FormValue("exp")); err == nil { - data.Expanded = exp - } - if exp, err := strconv.ParseBool(req.FormValue("rtraced")); err == nil { - data.Traced = exp - } - } - - completedMu.RLock() - data.Families = make([]string, 0, len(completedTraces)) - for fam := range completedTraces { - data.Families = append(data.Families, fam) - } - completedMu.RUnlock() - sort.Strings(data.Families) - - // We are careful here to minimize the time spent locking activeMu, - // since that lock is required every time an RPC starts and finishes. - data.ActiveTraceCount = make(map[string]int, len(data.Families)) - activeMu.RLock() - for fam, s := range activeTraces { - data.ActiveTraceCount[fam] = s.Len() - } - activeMu.RUnlock() - - var ok bool - data.Family, data.Bucket, ok = parseArgs(req) - switch { - case !ok: - // No-op - case data.Bucket == -1: - data.Active = true - n := data.ActiveTraceCount[data.Family] - data.Traces = getActiveTraces(data.Family) - if len(data.Traces) < n { - data.Total = n - } - case data.Bucket < bucketsPerFamily: - if b := lookupBucket(data.Family, data.Bucket); b != nil { - data.Traces = b.Copy(data.Traced) - } - default: - if f := getFamily(data.Family, false); f != nil { - var obs timeseries.Observable - f.LatencyMu.RLock() - switch o := data.Bucket - bucketsPerFamily; o { - case 0: - obs = f.Latency.Minute() - data.HistogramWindow = "last minute" - case 1: - obs = f.Latency.Hour() - data.HistogramWindow = "last hour" - case 2: - obs = f.Latency.Total() - data.HistogramWindow = "all time" - } - f.LatencyMu.RUnlock() - if obs != nil { - data.Histogram = obs.(*histogram).html() - } - } - } - - if data.Traces != nil { - defer data.Traces.Free() - sort.Sort(data.Traces) - } - - completedMu.RLock() - defer completedMu.RUnlock() - if err := pageTmpl().ExecuteTemplate(w, "Page", data); err != nil { - log.Printf("net/trace: Failed executing template: %v", err) - } -} - -func parseArgs(req *http.Request) (fam string, b int, ok bool) { - if req == nil { - return "", 0, false - } - fam, bStr := req.FormValue("fam"), req.FormValue("b") - if fam == "" || bStr == "" { - return "", 0, false - } - b, err := strconv.Atoi(bStr) - if err != nil || b < -1 { - return "", 0, false - } - - return fam, b, true -} - -func lookupBucket(fam string, b int) *traceBucket { - f := getFamily(fam, false) - if f == nil || b < 0 || b >= len(f.Buckets) { - return nil - } - return f.Buckets[b] -} - -type contextKeyT string - -var contextKey = contextKeyT("golang.org/x/net/trace.Trace") - -// Trace represents an active request. -type Trace interface { - // LazyLog adds x to the event log. It will be evaluated each time the - // /debug/requests page is rendered. Any memory referenced by x will be - // pinned until the trace is finished and later discarded. - LazyLog(x fmt.Stringer, sensitive bool) - - // LazyPrintf evaluates its arguments with fmt.Sprintf each time the - // /debug/requests page is rendered. Any memory referenced by a will be - // pinned until the trace is finished and later discarded. - LazyPrintf(format string, a ...interface{}) - - // SetError declares that this trace resulted in an error. - SetError() - - // SetRecycler sets a recycler for the trace. - // f will be called for each event passed to LazyLog at a time when - // it is no longer required, whether while the trace is still active - // and the event is discarded, or when a completed trace is discarded. - SetRecycler(f func(interface{})) - - // SetTraceInfo sets the trace info for the trace. - // This is currently unused. - SetTraceInfo(traceID, spanID uint64) - - // SetMaxEvents sets the maximum number of events that will be stored - // in the trace. This has no effect if any events have already been - // added to the trace. - SetMaxEvents(m int) - - // Finish declares that this trace is complete. - // The trace should not be used after calling this method. - Finish() -} - -type lazySprintf struct { - format string - a []interface{} -} - -func (l *lazySprintf) String() string { - return fmt.Sprintf(l.format, l.a...) -} - -// New returns a new Trace with the specified family and title. -func New(family, title string) Trace { - tr := newTrace() - tr.ref() - tr.Family, tr.Title = family, title - tr.Start = time.Now() - tr.maxEvents = maxEventsPerTrace - tr.events = tr.eventsBuf[:0] - - activeMu.RLock() - s := activeTraces[tr.Family] - activeMu.RUnlock() - if s == nil { - activeMu.Lock() - s = activeTraces[tr.Family] // check again - if s == nil { - s = new(traceSet) - activeTraces[tr.Family] = s - } - activeMu.Unlock() - } - s.Add(tr) - - // Trigger allocation of the completed trace structure for this family. - // This will cause the family to be present in the request page during - // the first trace of this family. We don't care about the return value, - // nor is there any need for this to run inline, so we execute it in its - // own goroutine, but only if the family isn't allocated yet. - completedMu.RLock() - if _, ok := completedTraces[tr.Family]; !ok { - go allocFamily(tr.Family) - } - completedMu.RUnlock() - - return tr -} - -func (tr *trace) Finish() { - elapsed := time.Now().Sub(tr.Start) - tr.mu.Lock() - tr.Elapsed = elapsed - tr.mu.Unlock() - - if DebugUseAfterFinish { - buf := make([]byte, 4<<10) // 4 KB should be enough - n := runtime.Stack(buf, false) - tr.finishStack = buf[:n] - } - - activeMu.RLock() - m := activeTraces[tr.Family] - activeMu.RUnlock() - m.Remove(tr) - - f := getFamily(tr.Family, true) - tr.mu.RLock() // protects tr fields in Cond.match calls - for _, b := range f.Buckets { - if b.Cond.match(tr) { - b.Add(tr) - } - } - tr.mu.RUnlock() - - // Add a sample of elapsed time as microseconds to the family's timeseries - h := new(histogram) - h.addMeasurement(elapsed.Nanoseconds() / 1e3) - f.LatencyMu.Lock() - f.Latency.Add(h) - f.LatencyMu.Unlock() - - tr.unref() // matches ref in New -} - -const ( - bucketsPerFamily = 9 - tracesPerBucket = 10 - maxActiveTraces = 20 // Maximum number of active traces to show. - maxEventsPerTrace = 10 - numHistogramBuckets = 38 -) - -var ( - // The active traces. - activeMu sync.RWMutex - activeTraces = make(map[string]*traceSet) // family -> traces - - // Families of completed traces. - completedMu sync.RWMutex - completedTraces = make(map[string]*family) // family -> traces -) - -type traceSet struct { - mu sync.RWMutex - m map[*trace]bool - - // We could avoid the entire map scan in FirstN by having a slice of all the traces - // ordered by start time, and an index into that from the trace struct, with a periodic - // repack of the slice after enough traces finish; we could also use a skip list or similar. - // However, that would shift some of the expense from /debug/requests time to RPC time, - // which is probably the wrong trade-off. -} - -func (ts *traceSet) Len() int { - ts.mu.RLock() - defer ts.mu.RUnlock() - return len(ts.m) -} - -func (ts *traceSet) Add(tr *trace) { - ts.mu.Lock() - if ts.m == nil { - ts.m = make(map[*trace]bool) - } - ts.m[tr] = true - ts.mu.Unlock() -} - -func (ts *traceSet) Remove(tr *trace) { - ts.mu.Lock() - delete(ts.m, tr) - ts.mu.Unlock() -} - -// FirstN returns the first n traces ordered by time. -func (ts *traceSet) FirstN(n int) traceList { - ts.mu.RLock() - defer ts.mu.RUnlock() - - if n > len(ts.m) { - n = len(ts.m) - } - trl := make(traceList, 0, n) - - // Fast path for when no selectivity is needed. - if n == len(ts.m) { - for tr := range ts.m { - tr.ref() - trl = append(trl, tr) - } - sort.Sort(trl) - return trl - } - - // Pick the oldest n traces. - // This is inefficient. See the comment in the traceSet struct. - for tr := range ts.m { - // Put the first n traces into trl in the order they occur. - // When we have n, sort trl, and thereafter maintain its order. - if len(trl) < n { - tr.ref() - trl = append(trl, tr) - if len(trl) == n { - // This is guaranteed to happen exactly once during this loop. - sort.Sort(trl) - } - continue - } - if tr.Start.After(trl[n-1].Start) { - continue - } - - // Find where to insert this one. - tr.ref() - i := sort.Search(n, func(i int) bool { return trl[i].Start.After(tr.Start) }) - trl[n-1].unref() - copy(trl[i+1:], trl[i:]) - trl[i] = tr - } - - return trl -} - -func getActiveTraces(fam string) traceList { - activeMu.RLock() - s := activeTraces[fam] - activeMu.RUnlock() - if s == nil { - return nil - } - return s.FirstN(maxActiveTraces) -} - -func getFamily(fam string, allocNew bool) *family { - completedMu.RLock() - f := completedTraces[fam] - completedMu.RUnlock() - if f == nil && allocNew { - f = allocFamily(fam) - } - return f -} - -func allocFamily(fam string) *family { - completedMu.Lock() - defer completedMu.Unlock() - f := completedTraces[fam] - if f == nil { - f = newFamily() - completedTraces[fam] = f - } - return f -} - -// family represents a set of trace buckets and associated latency information. -type family struct { - // traces may occur in multiple buckets. - Buckets [bucketsPerFamily]*traceBucket - - // latency time series - LatencyMu sync.RWMutex - Latency *timeseries.MinuteHourSeries -} - -func newFamily() *family { - return &family{ - Buckets: [bucketsPerFamily]*traceBucket{ - {Cond: minCond(0)}, - {Cond: minCond(50 * time.Millisecond)}, - {Cond: minCond(100 * time.Millisecond)}, - {Cond: minCond(200 * time.Millisecond)}, - {Cond: minCond(500 * time.Millisecond)}, - {Cond: minCond(1 * time.Second)}, - {Cond: minCond(10 * time.Second)}, - {Cond: minCond(100 * time.Second)}, - {Cond: errorCond{}}, - }, - Latency: timeseries.NewMinuteHourSeries(func() timeseries.Observable { return new(histogram) }), - } -} - -// traceBucket represents a size-capped bucket of historic traces, -// along with a condition for a trace to belong to the bucket. -type traceBucket struct { - Cond cond - - // Ring buffer implementation of a fixed-size FIFO queue. - mu sync.RWMutex - buf [tracesPerBucket]*trace - start int // < tracesPerBucket - length int // <= tracesPerBucket -} - -func (b *traceBucket) Add(tr *trace) { - b.mu.Lock() - defer b.mu.Unlock() - - i := b.start + b.length - if i >= tracesPerBucket { - i -= tracesPerBucket - } - if b.length == tracesPerBucket { - // "Remove" an element from the bucket. - b.buf[i].unref() - b.start++ - if b.start == tracesPerBucket { - b.start = 0 - } - } - b.buf[i] = tr - if b.length < tracesPerBucket { - b.length++ - } - tr.ref() -} - -// Copy returns a copy of the traces in the bucket. -// If tracedOnly is true, only the traces with trace information will be returned. -// The logs will be ref'd before returning; the caller should call -// the Free method when it is done with them. -// TODO(dsymonds): keep track of traced requests in separate buckets. -func (b *traceBucket) Copy(tracedOnly bool) traceList { - b.mu.RLock() - defer b.mu.RUnlock() - - trl := make(traceList, 0, b.length) - for i, x := 0, b.start; i < b.length; i++ { - tr := b.buf[x] - if !tracedOnly || tr.spanID != 0 { - tr.ref() - trl = append(trl, tr) - } - x++ - if x == b.length { - x = 0 - } - } - return trl -} - -func (b *traceBucket) Empty() bool { - b.mu.RLock() - defer b.mu.RUnlock() - return b.length == 0 -} - -// cond represents a condition on a trace. -type cond interface { - match(t *trace) bool - String() string -} - -type minCond time.Duration - -func (m minCond) match(t *trace) bool { return t.Elapsed >= time.Duration(m) } -func (m minCond) String() string { return fmt.Sprintf("≥%gs", time.Duration(m).Seconds()) } - -type errorCond struct{} - -func (e errorCond) match(t *trace) bool { return t.IsError } -func (e errorCond) String() string { return "errors" } - -type traceList []*trace - -// Free calls unref on each element of the list. -func (trl traceList) Free() { - for _, t := range trl { - t.unref() - } -} - -// traceList may be sorted in reverse chronological order. -func (trl traceList) Len() int { return len(trl) } -func (trl traceList) Less(i, j int) bool { return trl[i].Start.After(trl[j].Start) } -func (trl traceList) Swap(i, j int) { trl[i], trl[j] = trl[j], trl[i] } - -// An event is a timestamped log entry in a trace. -type event struct { - When time.Time - Elapsed time.Duration // since previous event in trace - NewDay bool // whether this event is on a different day to the previous event - Recyclable bool // whether this event was passed via LazyLog - Sensitive bool // whether this event contains sensitive information - What interface{} // string or fmt.Stringer -} - -// WhenString returns a string representation of the elapsed time of the event. -// It will include the date if midnight was crossed. -func (e event) WhenString() string { - if e.NewDay { - return e.When.Format("2006/01/02 15:04:05.000000") - } - return e.When.Format("15:04:05.000000") -} - -// discarded represents a number of discarded events. -// It is stored as *discarded to make it easier to update in-place. -type discarded int - -func (d *discarded) String() string { - return fmt.Sprintf("(%d events discarded)", int(*d)) -} - -// trace represents an active or complete request, -// either sent or received by this program. -type trace struct { - // Family is the top-level grouping of traces to which this belongs. - Family string - - // Title is the title of this trace. - Title string - - // Start time of the this trace. - Start time.Time - - mu sync.RWMutex - events []event // Append-only sequence of events (modulo discards). - maxEvents int - recycler func(interface{}) - IsError bool // Whether this trace resulted in an error. - Elapsed time.Duration // Elapsed time for this trace, zero while active. - traceID uint64 // Trace information if non-zero. - spanID uint64 - - refs int32 // how many buckets this is in - disc discarded // scratch space to avoid allocation - - finishStack []byte // where finish was called, if DebugUseAfterFinish is set - - eventsBuf [4]event // preallocated buffer in case we only log a few events -} - -func (tr *trace) reset() { - // Clear all but the mutex. Mutexes may not be copied, even when unlocked. - tr.Family = "" - tr.Title = "" - tr.Start = time.Time{} - - tr.mu.Lock() - tr.Elapsed = 0 - tr.traceID = 0 - tr.spanID = 0 - tr.IsError = false - tr.maxEvents = 0 - tr.events = nil - tr.recycler = nil - tr.mu.Unlock() - - tr.refs = 0 - tr.disc = 0 - tr.finishStack = nil - for i := range tr.eventsBuf { - tr.eventsBuf[i] = event{} - } -} - -// delta returns the elapsed time since the last event or the trace start, -// and whether it spans midnight. -// L >= tr.mu -func (tr *trace) delta(t time.Time) (time.Duration, bool) { - if len(tr.events) == 0 { - return t.Sub(tr.Start), false - } - prev := tr.events[len(tr.events)-1].When - return t.Sub(prev), prev.Day() != t.Day() -} - -func (tr *trace) addEvent(x interface{}, recyclable, sensitive bool) { - if DebugUseAfterFinish && tr.finishStack != nil { - buf := make([]byte, 4<<10) // 4 KB should be enough - n := runtime.Stack(buf, false) - log.Printf("net/trace: trace used after finish:\nFinished at:\n%s\nUsed at:\n%s", tr.finishStack, buf[:n]) - } - - /* - NOTE TO DEBUGGERS - - If you are here because your program panicked in this code, - it is almost definitely the fault of code using this package, - and very unlikely to be the fault of this code. - - The most likely scenario is that some code elsewhere is using - a trace.Trace after its Finish method is called. - You can temporarily set the DebugUseAfterFinish var - to help discover where that is; do not leave that var set, - since it makes this package much less efficient. - */ - - e := event{When: time.Now(), What: x, Recyclable: recyclable, Sensitive: sensitive} - tr.mu.Lock() - e.Elapsed, e.NewDay = tr.delta(e.When) - if len(tr.events) < tr.maxEvents { - tr.events = append(tr.events, e) - } else { - // Discard the middle events. - di := int((tr.maxEvents - 1) / 2) - if d, ok := tr.events[di].What.(*discarded); ok { - (*d)++ - } else { - // disc starts at two to count for the event it is replacing, - // plus the next one that we are about to drop. - tr.disc = 2 - if tr.recycler != nil && tr.events[di].Recyclable { - go tr.recycler(tr.events[di].What) - } - tr.events[di].What = &tr.disc - } - // The timestamp of the discarded meta-event should be - // the time of the last event it is representing. - tr.events[di].When = tr.events[di+1].When - - if tr.recycler != nil && tr.events[di+1].Recyclable { - go tr.recycler(tr.events[di+1].What) - } - copy(tr.events[di+1:], tr.events[di+2:]) - tr.events[tr.maxEvents-1] = e - } - tr.mu.Unlock() -} - -func (tr *trace) LazyLog(x fmt.Stringer, sensitive bool) { - tr.addEvent(x, true, sensitive) -} - -func (tr *trace) LazyPrintf(format string, a ...interface{}) { - tr.addEvent(&lazySprintf{format, a}, false, false) -} - -func (tr *trace) SetError() { - tr.mu.Lock() - tr.IsError = true - tr.mu.Unlock() -} - -func (tr *trace) SetRecycler(f func(interface{})) { - tr.mu.Lock() - tr.recycler = f - tr.mu.Unlock() -} - -func (tr *trace) SetTraceInfo(traceID, spanID uint64) { - tr.mu.Lock() - tr.traceID, tr.spanID = traceID, spanID - tr.mu.Unlock() -} - -func (tr *trace) SetMaxEvents(m int) { - tr.mu.Lock() - // Always keep at least three events: first, discarded count, last. - if len(tr.events) == 0 && m > 3 { - tr.maxEvents = m - } - tr.mu.Unlock() -} - -func (tr *trace) ref() { - atomic.AddInt32(&tr.refs, 1) -} - -func (tr *trace) unref() { - if atomic.AddInt32(&tr.refs, -1) == 0 { - tr.mu.RLock() - if tr.recycler != nil { - // freeTrace clears tr, so we hold tr.recycler and tr.events here. - go func(f func(interface{}), es []event) { - for _, e := range es { - if e.Recyclable { - f(e.What) - } - } - }(tr.recycler, tr.events) - } - tr.mu.RUnlock() - - freeTrace(tr) - } -} - -func (tr *trace) When() string { - return tr.Start.Format("2006/01/02 15:04:05.000000") -} - -func (tr *trace) ElapsedTime() string { - tr.mu.RLock() - t := tr.Elapsed - tr.mu.RUnlock() - - if t == 0 { - // Active trace. - t = time.Since(tr.Start) - } - return fmt.Sprintf("%.6f", t.Seconds()) -} - -func (tr *trace) Events() []event { - tr.mu.RLock() - defer tr.mu.RUnlock() - return tr.events -} - -var traceFreeList = make(chan *trace, 1000) // TODO(dsymonds): Use sync.Pool? - -// newTrace returns a trace ready to use. -func newTrace() *trace { - select { - case tr := <-traceFreeList: - return tr - default: - return new(trace) - } -} - -// freeTrace adds tr to traceFreeList if there's room. -// This is non-blocking. -func freeTrace(tr *trace) { - if DebugUseAfterFinish { - return // never reuse - } - tr.reset() - select { - case traceFreeList <- tr: - default: - } -} - -func elapsed(d time.Duration) string { - b := []byte(fmt.Sprintf("%.6f", d.Seconds())) - - // For subsecond durations, blank all zeros before decimal point, - // and all zeros between the decimal point and the first non-zero digit. - if d < time.Second { - dot := bytes.IndexByte(b, '.') - for i := 0; i < dot; i++ { - b[i] = ' ' - } - for i := dot + 1; i < len(b); i++ { - if b[i] == '0' { - b[i] = ' ' - } else { - break - } - } - } - - return string(b) -} - -var pageTmplCache *template.Template -var pageTmplOnce sync.Once - -func pageTmpl() *template.Template { - pageTmplOnce.Do(func() { - pageTmplCache = template.Must(template.New("Page").Funcs(template.FuncMap{ - "elapsed": elapsed, - "add": func(a, b int) int { return a + b }, - }).Parse(pageHTML)) - }) - return pageTmplCache -} - -const pageHTML = ` -{{template "Prolog" .}} -{{template "StatusTable" .}} -{{template "Epilog" .}} - -{{define "Prolog"}} - - - /debug/requests - - - - -

/debug/requests

-{{end}} {{/* end of Prolog */}} - -{{define "StatusTable"}} - - {{range $fam := .Families}} - - - - {{$n := index $.ActiveTraceCount $fam}} - - - {{$f := index $.CompletedTraces $fam}} - {{range $i, $b := $f.Buckets}} - {{$empty := $b.Empty}} - - {{end}} - - {{$nb := len $f.Buckets}} - - - - - - {{end}} -
{{$fam}} - {{if $n}}{{end}} - [{{$n}} active] - {{if $n}}{{end}} - - {{if not $empty}}{{end}} - [{{.Cond}}] - {{if not $empty}}{{end}} - - [minute] - - [hour] - - [total] -
-{{end}} {{/* end of StatusTable */}} - -{{define "Epilog"}} -{{if $.Traces}} -
-

Family: {{$.Family}}

- -{{if or $.Expanded $.Traced}} - [Normal/Summary] -{{else}} - [Normal/Summary] -{{end}} - -{{if or (not $.Expanded) $.Traced}} - [Normal/Expanded] -{{else}} - [Normal/Expanded] -{{end}} - -{{if not $.Active}} - {{if or $.Expanded (not $.Traced)}} - [Traced/Summary] - {{else}} - [Traced/Summary] - {{end}} - {{if or (not $.Expanded) (not $.Traced)}} - [Traced/Expanded] - {{else}} - [Traced/Expanded] - {{end}} -{{end}} - -{{if $.Total}} -

Showing {{len $.Traces}} of {{$.Total}} traces.

-{{end}} - - - - - {{range $tr := $.Traces}} - - - - - {{/* TODO: include traceID/spanID */}} - - {{if $.Expanded}} - {{range $tr.Events}} - - - - - - {{end}} - {{end}} - {{end}} -
- {{if $.Active}}Active{{else}}Completed{{end}} Requests -
WhenElapsed (s)
{{$tr.When}}{{$tr.ElapsedTime}}{{$tr.Title}}
{{.WhenString}}{{elapsed .Elapsed}}{{if or $.ShowSensitive (not .Sensitive)}}... {{.What}}{{else}}[redacted]{{end}}
-{{end}} {{/* if $.Traces */}} - -{{if $.Histogram}} -

Latency (µs) of {{$.Family}} over {{$.HistogramWindow}}

-{{$.Histogram}} -{{end}} {{/* if $.Histogram */}} - - - -{{end}} {{/* end of Epilog */}} -` diff --git a/vendor/golang.org/x/net/trace/trace_go16.go b/vendor/golang.org/x/net/trace/trace_go16.go deleted file mode 100644 index d6081911853..00000000000 --- a/vendor/golang.org/x/net/trace/trace_go16.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.7 - -package trace - -import "golang.org/x/net/context" - -// NewContext returns a copy of the parent context -// and associates it with a Trace. -func NewContext(ctx context.Context, tr Trace) context.Context { - return context.WithValue(ctx, contextKey, tr) -} - -// FromContext returns the Trace bound to the context, if any. -func FromContext(ctx context.Context) (tr Trace, ok bool) { - tr, ok = ctx.Value(contextKey).(Trace) - return -} diff --git a/vendor/golang.org/x/net/trace/trace_go17.go b/vendor/golang.org/x/net/trace/trace_go17.go deleted file mode 100644 index df6e1fba7ca..00000000000 --- a/vendor/golang.org/x/net/trace/trace_go17.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.7 - -package trace - -import "context" - -// NewContext returns a copy of the parent context -// and associates it with a Trace. -func NewContext(ctx context.Context, tr Trace) context.Context { - return context.WithValue(ctx, contextKey, tr) -} - -// FromContext returns the Trace bound to the context, if any. -func FromContext(ctx context.Context) (tr Trace, ok bool) { - tr, ok = ctx.Value(contextKey).(Trace) - return -} diff --git a/vendor/golang.org/x/sync/semaphore/semaphore.go b/vendor/golang.org/x/sync/semaphore/semaphore.go deleted file mode 100644 index e9d2d79a97f..00000000000 --- a/vendor/golang.org/x/sync/semaphore/semaphore.go +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package semaphore provides a weighted semaphore implementation. -package semaphore // import "golang.org/x/sync/semaphore" - -import ( - "container/list" - "sync" - - // Use the old context because packages that depend on this one - // (e.g. cloud.google.com/go/...) must run on Go 1.6. - // TODO(jba): update to "context" when possible. - "golang.org/x/net/context" -) - -type waiter struct { - n int64 - ready chan<- struct{} // Closed when semaphore acquired. -} - -// NewWeighted creates a new weighted semaphore with the given -// maximum combined weight for concurrent access. -func NewWeighted(n int64) *Weighted { - w := &Weighted{size: n} - return w -} - -// Weighted provides a way to bound concurrent access to a resource. -// The callers can request access with a given weight. -type Weighted struct { - size int64 - cur int64 - mu sync.Mutex - waiters list.List -} - -// Acquire acquires the semaphore with a weight of n, blocking only until ctx -// is done. On success, returns nil. On failure, returns ctx.Err() and leaves -// the semaphore unchanged. -// -// If ctx is already done, Acquire may still succeed without blocking. -func (s *Weighted) Acquire(ctx context.Context, n int64) error { - s.mu.Lock() - if s.size-s.cur >= n && s.waiters.Len() == 0 { - s.cur += n - s.mu.Unlock() - return nil - } - - if n > s.size { - // Don't make other Acquire calls block on one that's doomed to fail. - s.mu.Unlock() - <-ctx.Done() - return ctx.Err() - } - - ready := make(chan struct{}) - w := waiter{n: n, ready: ready} - elem := s.waiters.PushBack(w) - s.mu.Unlock() - - select { - case <-ctx.Done(): - err := ctx.Err() - s.mu.Lock() - select { - case <-ready: - // Acquired the semaphore after we were canceled. Rather than trying to - // fix up the queue, just pretend we didn't notice the cancelation. - err = nil - default: - s.waiters.Remove(elem) - } - s.mu.Unlock() - return err - - case <-ready: - return nil - } -} - -// TryAcquire acquires the semaphore with a weight of n without blocking. -// On success, returns true. On failure, returns false and leaves the semaphore unchanged. -func (s *Weighted) TryAcquire(n int64) bool { - s.mu.Lock() - success := s.size-s.cur >= n && s.waiters.Len() == 0 - if success { - s.cur += n - } - s.mu.Unlock() - return success -} - -// Release releases the semaphore with a weight of n. -func (s *Weighted) Release(n int64) { - s.mu.Lock() - s.cur -= n - if s.cur < 0 { - s.mu.Unlock() - panic("semaphore: bad release") - } - for { - next := s.waiters.Front() - if next == nil { - break // No more waiters blocked. - } - - w := next.Value.(waiter) - if s.size-s.cur < w.n { - // Not enough tokens for the next waiter. We could keep going (to try to - // find a waiter with a smaller request), but under load that could cause - // starvation for large requests; instead, we leave all remaining waiters - // blocked. - // - // Consider a semaphore used as a read-write lock, with N tokens, N - // readers, and one writer. Each reader can Acquire(1) to obtain a read - // lock. The writer can Acquire(N) to obtain a write lock, excluding all - // of the readers. If we allow the readers to jump ahead in the queue, - // the writer will starve — there is always one token available for every - // reader. - break - } - - s.cur += w.n - s.waiters.Remove(next) - close(w.ready) - } - s.mu.Unlock() -} diff --git a/vendor/google.golang.org/api/AUTHORS b/vendor/google.golang.org/api/AUTHORS deleted file mode 100644 index f73b7257457..00000000000 --- a/vendor/google.golang.org/api/AUTHORS +++ /dev/null @@ -1,10 +0,0 @@ -# This is the official list of authors for copyright purposes. -# This file is distinct from the CONTRIBUTORS files. -# See the latter for an explanation. - -# Names should be added to this file as -# Name or Organization -# The email address is not required for organizations. - -# Please keep the list sorted. -Google Inc. diff --git a/vendor/google.golang.org/api/CONTRIBUTORS b/vendor/google.golang.org/api/CONTRIBUTORS deleted file mode 100644 index b8928e61641..00000000000 --- a/vendor/google.golang.org/api/CONTRIBUTORS +++ /dev/null @@ -1,54 +0,0 @@ -# This is the official list of people who can contribute -# (and typically have contributed) code to the repository. -# The AUTHORS file lists the copyright holders; this file -# lists people. For example, Google employees are listed here -# but not in AUTHORS, because Google holds the copyright. -# -# The submission process automatically checks to make sure -# that people submitting code are listed in this file (by email address). -# -# Names should be added to this file only after verifying that -# the individual or the individual's organization has agreed to -# the appropriate Contributor License Agreement, found here: -# -# https://cla.developers.google.com/about/google-individual -# https://cla.developers.google.com/about/google-corporate -# -# The CLA can be filled out on the web: -# -# https://cla.developers.google.com/ -# -# When adding J Random Contributor's name to this file, -# either J's name or J's organization's name should be -# added to the AUTHORS file, depending on whether the -# individual or corporate CLA was used. - -# Names should be added to this file like so: -# Name -# -# An entry with two email addresses specifies that the -# first address should be used in the submit logs and -# that the second address should be recognized as the -# same person when interacting with Rietveld. - -# Please keep the list sorted. - -Alain Vongsouvanhalainv -Andrew Gerrand -Brad Fitzpatrick -Eric Koleda -Francesc Campoy -Garrick Evans -Glenn Lewis -Ivan Krasin -Jason Hall -Johan Euphrosine -Kostik Shtoyk -Kunpei Sakai -Matthew Whisenhunt -Michael McGreevy -Nick Craig-Wood -Ross Light -Sarah Adams -Scott Van Woudenberg -Takashi Matsuo diff --git a/vendor/google.golang.org/api/LICENSE b/vendor/google.golang.org/api/LICENSE deleted file mode 100644 index 263aa7a0c12..00000000000 --- a/vendor/google.golang.org/api/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2011 Google Inc. All rights reserved. - -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. diff --git a/vendor/google.golang.org/api/googleapi/internal/uritemplates/LICENSE b/vendor/google.golang.org/api/googleapi/internal/uritemplates/LICENSE deleted file mode 100644 index de9c88cb65c..00000000000 --- a/vendor/google.golang.org/api/googleapi/internal/uritemplates/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -Copyright (c) 2013 Joshua Tacoma - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/google.golang.org/api/googleapi/transport/apikey.go b/vendor/google.golang.org/api/googleapi/transport/apikey.go deleted file mode 100644 index eca1ea25077..00000000000 --- a/vendor/google.golang.org/api/googleapi/transport/apikey.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2012 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package transport contains HTTP transports used to make -// authenticated API requests. -package transport - -import ( - "errors" - "net/http" -) - -// APIKey is an HTTP Transport which wraps an underlying transport and -// appends an API Key "key" parameter to the URL of outgoing requests. -type APIKey struct { - // Key is the API Key to set on requests. - Key string - - // Transport is the underlying HTTP transport. - // If nil, http.DefaultTransport is used. - Transport http.RoundTripper -} - -func (t *APIKey) RoundTrip(req *http.Request) (*http.Response, error) { - rt := t.Transport - if rt == nil { - rt = http.DefaultTransport - if rt == nil { - return nil, errors.New("googleapi/transport: no Transport specified or available") - } - } - newReq := *req - args := newReq.URL.Query() - args.Set("key", t.Key) - newReq.URL.RawQuery = args.Encode() - return rt.RoundTrip(&newReq) -} diff --git a/vendor/google.golang.org/api/internal/creds.go b/vendor/google.golang.org/api/internal/creds.go deleted file mode 100644 index c16b7b629be..00000000000 --- a/vendor/google.golang.org/api/internal/creds.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package internal - -import ( - "fmt" - "io/ioutil" - - "golang.org/x/net/context" - "golang.org/x/oauth2/google" -) - -// Creds returns credential information obtained from DialSettings, or if none, then -// it returns default credential information. -func Creds(ctx context.Context, ds *DialSettings) (*google.DefaultCredentials, error) { - if ds.Credentials != nil { - return ds.Credentials, nil - } - if ds.CredentialsFile != "" { - data, err := ioutil.ReadFile(ds.CredentialsFile) - if err != nil { - return nil, fmt.Errorf("cannot read credentials file: %v", err) - } - return google.CredentialsFromJSON(ctx, data, ds.Scopes...) - } - if ds.TokenSource != nil { - return &google.DefaultCredentials{TokenSource: ds.TokenSource}, nil - } - return google.FindDefaultCredentials(ctx, ds.Scopes...) -} diff --git a/vendor/google.golang.org/api/internal/pool.go b/vendor/google.golang.org/api/internal/pool.go deleted file mode 100644 index 4150feb6bb0..00000000000 --- a/vendor/google.golang.org/api/internal/pool.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package internal - -import ( - "errors" - "google.golang.org/grpc/naming" -) - -// PoolResolver provides a fixed list of addresses to load balance between -// and does not provide further updates. -type PoolResolver struct { - poolSize int - dialOpt *DialSettings - ch chan []*naming.Update -} - -// NewPoolResolver returns a PoolResolver -// This is an EXPERIMENTAL API and may be changed or removed in the future. -func NewPoolResolver(size int, o *DialSettings) *PoolResolver { - return &PoolResolver{poolSize: size, dialOpt: o} -} - -// Resolve returns a Watcher for the endpoint defined by the DialSettings -// provided to NewPoolResolver. -func (r *PoolResolver) Resolve(target string) (naming.Watcher, error) { - if r.dialOpt.Endpoint == "" { - return nil, errors.New("No endpoint configured") - } - addrs := make([]*naming.Update, 0, r.poolSize) - for i := 0; i < r.poolSize; i++ { - addrs = append(addrs, &naming.Update{Op: naming.Add, Addr: r.dialOpt.Endpoint, Metadata: i}) - } - r.ch = make(chan []*naming.Update, 1) - r.ch <- addrs - return r, nil -} - -// Next returns a static list of updates on the first call, -// and blocks indefinitely until Close is called on subsequent calls. -func (r *PoolResolver) Next() ([]*naming.Update, error) { - return <-r.ch, nil -} - -func (r *PoolResolver) Close() { - close(r.ch) -} diff --git a/vendor/google.golang.org/api/internal/settings.go b/vendor/google.golang.org/api/internal/settings.go deleted file mode 100644 index 34dfa5a8219..00000000000 --- a/vendor/google.golang.org/api/internal/settings.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package internal supports the options and transport packages. -package internal - -import ( - "errors" - "net/http" - - "golang.org/x/oauth2" - "golang.org/x/oauth2/google" - "google.golang.org/grpc" -) - -// DialSettings holds information needed to establish a connection with a -// Google API service. -type DialSettings struct { - Endpoint string - Scopes []string - TokenSource oauth2.TokenSource - Credentials *google.DefaultCredentials - CredentialsFile string // if set, Token Source is ignored. - UserAgent string - APIKey string - HTTPClient *http.Client - GRPCDialOpts []grpc.DialOption - GRPCConn *grpc.ClientConn - NoAuth bool -} - -// Validate reports an error if ds is invalid. -func (ds *DialSettings) Validate() error { - hasCreds := ds.APIKey != "" || ds.TokenSource != nil || ds.CredentialsFile != "" || ds.Credentials != nil - if ds.NoAuth && hasCreds { - return errors.New("options.WithoutAuthentication is incompatible with any option that provides credentials") - } - // Credentials should not appear with other options. - // We currently allow TokenSource and CredentialsFile to coexist. - // TODO(jba): make TokenSource & CredentialsFile an error (breaking change). - if ds.Credentials != nil && (ds.APIKey != "" || ds.TokenSource != nil || ds.CredentialsFile != "") { - return errors.New("multiple credential options provided") - } - if ds.HTTPClient != nil && ds.GRPCConn != nil { - return errors.New("WithHTTPClient is incompatible with WithGRPCConn") - } - if ds.HTTPClient != nil && ds.GRPCDialOpts != nil { - return errors.New("WithHTTPClient is incompatible with gRPC dial options") - } - return nil -} diff --git a/vendor/google.golang.org/api/iterator/iterator.go b/vendor/google.golang.org/api/iterator/iterator.go deleted file mode 100644 index e34e5207349..00000000000 --- a/vendor/google.golang.org/api/iterator/iterator.go +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package iterator provides support for standard Google API iterators. -// See https://github.com/GoogleCloudPlatform/gcloud-golang/wiki/Iterator-Guidelines. -package iterator - -import ( - "errors" - "fmt" - "reflect" -) - -// Done is returned by an iterator's Next method when the iteration is -// complete; when there are no more items to return. -var Done = errors.New("no more items in iterator") - -// We don't support mixed calls to Next and NextPage because they play -// with the paging state in incompatible ways. -var errMixed = errors.New("iterator: Next and NextPage called on same iterator") - -// PageInfo contains information about an iterator's paging state. -type PageInfo struct { - // Token is the token used to retrieve the next page of items from the - // API. You may set Token immediately after creating an iterator to - // begin iteration at a particular point. If Token is the empty string, - // the iterator will begin with the first eligible item. - // - // The result of setting Token after the first call to Next is undefined. - // - // After the underlying API method is called to retrieve a page of items, - // Token is set to the next-page token in the response. - Token string - - // MaxSize is the maximum number of items returned by a call to the API. - // Set MaxSize as a hint to optimize the buffering behavior of the iterator. - // If zero, the page size is determined by the underlying service. - // - // Use Pager to retrieve a page of a specific, exact size. - MaxSize int - - // The error state of the iterator. Manipulated by PageInfo.next and Pager. - // This is a latch: it starts as nil, and once set should never change. - err error - - // If true, no more calls to fetch should be made. Set to true when fetch - // returns an empty page token. The iterator is Done when this is true AND - // the buffer is empty. - atEnd bool - - // Function that fetches a page from the underlying service. It should pass - // the pageSize and pageToken arguments to the service, fill the buffer - // with the results from the call, and return the next-page token returned - // by the service. The function must not remove any existing items from the - // buffer. If the underlying RPC takes an int32 page size, pageSize should - // be silently truncated. - fetch func(pageSize int, pageToken string) (nextPageToken string, err error) - - // Function that returns the number of currently buffered items. - bufLen func() int - - // Function that returns the buffer, after setting the buffer variable to nil. - takeBuf func() interface{} - - // Set to true on first call to PageInfo.next or Pager.NextPage. Used to check - // for calls to both Next and NextPage with the same iterator. - nextCalled, nextPageCalled bool -} - -// NewPageInfo exposes internals for iterator implementations. -// It is not a stable interface. -var NewPageInfo = newPageInfo - -// If an iterator can support paging, its iterator-creating method should call -// this (via the NewPageInfo variable above). -// -// The fetch, bufLen and takeBuf arguments provide access to the -// iterator's internal slice of buffered items. They behave as described in -// PageInfo, above. -// -// The return value is the PageInfo.next method bound to the returned PageInfo value. -// (Returning it avoids exporting PageInfo.next.) -func newPageInfo(fetch func(int, string) (string, error), bufLen func() int, takeBuf func() interface{}) (*PageInfo, func() error) { - pi := &PageInfo{ - fetch: fetch, - bufLen: bufLen, - takeBuf: takeBuf, - } - return pi, pi.next -} - -// Remaining returns the number of items available before the iterator makes another API call. -func (pi *PageInfo) Remaining() int { return pi.bufLen() } - -// next provides support for an iterator's Next function. An iterator's Next -// should return the error returned by next if non-nil; else it can assume -// there is at least one item in its buffer, and it should return that item and -// remove it from the buffer. -func (pi *PageInfo) next() error { - pi.nextCalled = true - if pi.err != nil { // Once we get an error, always return it. - // TODO(jba): fix so users can retry on transient errors? Probably not worth it. - return pi.err - } - if pi.nextPageCalled { - pi.err = errMixed - return pi.err - } - // Loop until we get some items or reach the end. - for pi.bufLen() == 0 && !pi.atEnd { - if err := pi.fill(pi.MaxSize); err != nil { - pi.err = err - return pi.err - } - if pi.Token == "" { - pi.atEnd = true - } - } - // Either the buffer is non-empty or pi.atEnd is true (or both). - if pi.bufLen() == 0 { - // The buffer is empty and pi.atEnd is true, i.e. the service has no - // more items. - pi.err = Done - } - return pi.err -} - -// Call the service to fill the buffer, using size and pi.Token. Set pi.Token to the -// next-page token returned by the call. -// If fill returns a non-nil error, the buffer will be empty. -func (pi *PageInfo) fill(size int) error { - tok, err := pi.fetch(size, pi.Token) - if err != nil { - pi.takeBuf() // clear the buffer - return err - } - pi.Token = tok - return nil -} - -// Pageable is implemented by iterators that support paging. -type Pageable interface { - // PageInfo returns paging information associated with the iterator. - PageInfo() *PageInfo -} - -// Pager supports retrieving iterator items a page at a time. -type Pager struct { - pageInfo *PageInfo - pageSize int -} - -// NewPager returns a pager that uses iter. Calls to its NextPage method will -// obtain exactly pageSize items, unless fewer remain. The pageToken argument -// indicates where to start the iteration. Pass the empty string to start at -// the beginning, or pass a token retrieved from a call to Pager.NextPage. -// -// If you use an iterator with a Pager, you must not call Next on the iterator. -func NewPager(iter Pageable, pageSize int, pageToken string) *Pager { - p := &Pager{ - pageInfo: iter.PageInfo(), - pageSize: pageSize, - } - p.pageInfo.Token = pageToken - if pageSize <= 0 { - p.pageInfo.err = errors.New("iterator: page size must be positive") - } - return p -} - -// NextPage retrieves a sequence of items from the iterator and appends them -// to slicep, which must be a pointer to a slice of the iterator's item type. -// Exactly p.pageSize items will be appended, unless fewer remain. -// -// The first return value is the page token to use for the next page of items. -// If empty, there are no more pages. Aside from checking for the end of the -// iteration, the returned page token is only needed if the iteration is to be -// resumed a later time, in another context (possibly another process). -// -// The second return value is non-nil if an error occurred. It will never be -// the special iterator sentinel value Done. To recognize the end of the -// iteration, compare nextPageToken to the empty string. -// -// It is possible for NextPage to return a single zero-length page along with -// an empty page token when there are no more items in the iteration. -func (p *Pager) NextPage(slicep interface{}) (nextPageToken string, err error) { - p.pageInfo.nextPageCalled = true - if p.pageInfo.err != nil { - return "", p.pageInfo.err - } - if p.pageInfo.nextCalled { - p.pageInfo.err = errMixed - return "", p.pageInfo.err - } - if p.pageInfo.bufLen() > 0 { - return "", errors.New("must call NextPage with an empty buffer") - } - // The buffer must be empty here, so takeBuf is a no-op. We call it just to get - // the buffer's type. - wantSliceType := reflect.PtrTo(reflect.ValueOf(p.pageInfo.takeBuf()).Type()) - if slicep == nil { - return "", errors.New("nil passed to Pager.NextPage") - } - vslicep := reflect.ValueOf(slicep) - if vslicep.Type() != wantSliceType { - return "", fmt.Errorf("slicep should be of type %s, got %T", wantSliceType, slicep) - } - for p.pageInfo.bufLen() < p.pageSize { - if err := p.pageInfo.fill(p.pageSize - p.pageInfo.bufLen()); err != nil { - p.pageInfo.err = err - return "", p.pageInfo.err - } - if p.pageInfo.Token == "" { - break - } - } - e := vslicep.Elem() - e.Set(reflect.AppendSlice(e, reflect.ValueOf(p.pageInfo.takeBuf()))) - return p.pageInfo.Token, nil -} diff --git a/vendor/google.golang.org/api/option/credentials_go19.go b/vendor/google.golang.org/api/option/credentials_go19.go deleted file mode 100644 index c08c1149d28..00000000000 --- a/vendor/google.golang.org/api/option/credentials_go19.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2018 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build go1.9 - -package option - -import ( - "golang.org/x/oauth2/google" - "google.golang.org/api/internal" -) - -type withCreds google.Credentials - -func (w *withCreds) Apply(o *internal.DialSettings) { - o.Credentials = (*google.Credentials)(w) -} - -func WithCredentials(creds *google.Credentials) ClientOption { - return (*withCreds)(creds) -} diff --git a/vendor/google.golang.org/api/option/credentials_notgo19.go b/vendor/google.golang.org/api/option/credentials_notgo19.go deleted file mode 100644 index 90d22900102..00000000000 --- a/vendor/google.golang.org/api/option/credentials_notgo19.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2018 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build !go1.9 - -package option - -import ( - "golang.org/x/oauth2/google" - "google.golang.org/api/internal" -) - -type withCreds google.DefaultCredentials - -func (w *withCreds) Apply(o *internal.DialSettings) { - o.Credentials = (*google.DefaultCredentials)(w) -} - -func WithCredentials(creds *google.DefaultCredentials) ClientOption { - return (*withCreds)(creds) -} diff --git a/vendor/google.golang.org/api/option/option.go b/vendor/google.golang.org/api/option/option.go deleted file mode 100644 index ffbee329511..00000000000 --- a/vendor/google.golang.org/api/option/option.go +++ /dev/null @@ -1,175 +0,0 @@ -// Copyright 2017 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package option contains options for Google API clients. -package option - -import ( - "net/http" - - "golang.org/x/oauth2" - "google.golang.org/api/internal" - "google.golang.org/grpc" -) - -// A ClientOption is an option for a Google API client. -type ClientOption interface { - Apply(*internal.DialSettings) -} - -// WithTokenSource returns a ClientOption that specifies an OAuth2 token -// source to be used as the basis for authentication. -func WithTokenSource(s oauth2.TokenSource) ClientOption { - return withTokenSource{s} -} - -type withTokenSource struct{ ts oauth2.TokenSource } - -func (w withTokenSource) Apply(o *internal.DialSettings) { - o.TokenSource = w.ts -} - -type withCredFile string - -func (w withCredFile) Apply(o *internal.DialSettings) { - o.CredentialsFile = string(w) -} - -// WithCredentialsFile returns a ClientOption that authenticates -// API calls with the given service account or refresh token JSON -// credentials file. -func WithCredentialsFile(filename string) ClientOption { - return withCredFile(filename) -} - -// WithServiceAccountFile returns a ClientOption that uses a Google service -// account credentials file to authenticate. -// -// Deprecated: Use WithCredentialsFile instead. -func WithServiceAccountFile(filename string) ClientOption { - return WithCredentialsFile(filename) -} - -// WithEndpoint returns a ClientOption that overrides the default endpoint -// to be used for a service. -func WithEndpoint(url string) ClientOption { - return withEndpoint(url) -} - -type withEndpoint string - -func (w withEndpoint) Apply(o *internal.DialSettings) { - o.Endpoint = string(w) -} - -// WithScopes returns a ClientOption that overrides the default OAuth2 scopes -// to be used for a service. -func WithScopes(scope ...string) ClientOption { - return withScopes(scope) -} - -type withScopes []string - -func (w withScopes) Apply(o *internal.DialSettings) { - s := make([]string, len(w)) - copy(s, w) - o.Scopes = s -} - -// WithUserAgent returns a ClientOption that sets the User-Agent. -func WithUserAgent(ua string) ClientOption { - return withUA(ua) -} - -type withUA string - -func (w withUA) Apply(o *internal.DialSettings) { o.UserAgent = string(w) } - -// WithHTTPClient returns a ClientOption that specifies the HTTP client to use -// as the basis of communications. This option may only be used with services -// that support HTTP as their communication transport. When used, the -// WithHTTPClient option takes precedent over all other supplied options. -func WithHTTPClient(client *http.Client) ClientOption { - return withHTTPClient{client} -} - -type withHTTPClient struct{ client *http.Client } - -func (w withHTTPClient) Apply(o *internal.DialSettings) { - o.HTTPClient = w.client -} - -// WithGRPCConn returns a ClientOption that specifies the gRPC client -// connection to use as the basis of communications. This option many only be -// used with services that support gRPC as their communication transport. When -// used, the WithGRPCConn option takes precedent over all other supplied -// options. -func WithGRPCConn(conn *grpc.ClientConn) ClientOption { - return withGRPCConn{conn} -} - -type withGRPCConn struct{ conn *grpc.ClientConn } - -func (w withGRPCConn) Apply(o *internal.DialSettings) { - o.GRPCConn = w.conn -} - -// WithGRPCDialOption returns a ClientOption that appends a new grpc.DialOption -// to an underlying gRPC dial. It does not work with WithGRPCConn. -func WithGRPCDialOption(opt grpc.DialOption) ClientOption { - return withGRPCDialOption{opt} -} - -type withGRPCDialOption struct{ opt grpc.DialOption } - -func (w withGRPCDialOption) Apply(o *internal.DialSettings) { - o.GRPCDialOpts = append(o.GRPCDialOpts, w.opt) -} - -// WithGRPCConnectionPool returns a ClientOption that creates a pool of gRPC -// connections that requests will be balanced between. -// This is an EXPERIMENTAL API and may be changed or removed in the future. -func WithGRPCConnectionPool(size int) ClientOption { - return withGRPCConnectionPool(size) -} - -type withGRPCConnectionPool int - -func (w withGRPCConnectionPool) Apply(o *internal.DialSettings) { - balancer := grpc.RoundRobin(internal.NewPoolResolver(int(w), o)) - o.GRPCDialOpts = append(o.GRPCDialOpts, grpc.WithBalancer(balancer)) -} - -// WithAPIKey returns a ClientOption that specifies an API key to be used -// as the basis for authentication. -func WithAPIKey(apiKey string) ClientOption { - return withAPIKey(apiKey) -} - -type withAPIKey string - -func (w withAPIKey) Apply(o *internal.DialSettings) { o.APIKey = string(w) } - -// WithoutAuthentication returns a ClientOption that specifies that no -// authentication should be used. It is suitable only for testing and for -// accessing public resources, like public Google Cloud Storage buckets. -// It is an error to provide both WithoutAuthentication and any of WithAPIKey, -// WithTokenSource, WithCredentialsFile or WithServiceAccountFile. -func WithoutAuthentication() ClientOption { - return withoutAuthentication{} -} - -type withoutAuthentication struct{} - -func (w withoutAuthentication) Apply(o *internal.DialSettings) { o.NoAuth = true } diff --git a/vendor/google.golang.org/api/support/bundler/bundler.go b/vendor/google.golang.org/api/support/bundler/bundler.go deleted file mode 100644 index 8d8fb7f0471..00000000000 --- a/vendor/google.golang.org/api/support/bundler/bundler.go +++ /dev/null @@ -1,349 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package bundler supports bundling (batching) of items. Bundling amortizes an -// action with fixed costs over multiple items. For example, if an API provides -// an RPC that accepts a list of items as input, but clients would prefer -// adding items one at a time, then a Bundler can accept individual items from -// the client and bundle many of them into a single RPC. -// -// This package is experimental and subject to change without notice. -package bundler - -import ( - "errors" - "math" - "reflect" - "sync" - "time" - - "golang.org/x/net/context" - "golang.org/x/sync/semaphore" -) - -const ( - DefaultDelayThreshold = time.Second - DefaultBundleCountThreshold = 10 - DefaultBundleByteThreshold = 1e6 // 1M - DefaultBufferedByteLimit = 1e9 // 1G -) - -var ( - // ErrOverflow indicates that Bundler's stored bytes exceeds its BufferedByteLimit. - ErrOverflow = errors.New("bundler reached buffered byte limit") - - // ErrOversizedItem indicates that an item's size exceeds the maximum bundle size. - ErrOversizedItem = errors.New("item size exceeds bundle byte limit") -) - -// A Bundler collects items added to it into a bundle until the bundle -// exceeds a given size, then calls a user-provided function to handle the bundle. -type Bundler struct { - // Starting from the time that the first message is added to a bundle, once - // this delay has passed, handle the bundle. The default is DefaultDelayThreshold. - DelayThreshold time.Duration - - // Once a bundle has this many items, handle the bundle. Since only one - // item at a time is added to a bundle, no bundle will exceed this - // threshold, so it also serves as a limit. The default is - // DefaultBundleCountThreshold. - BundleCountThreshold int - - // Once the number of bytes in current bundle reaches this threshold, handle - // the bundle. The default is DefaultBundleByteThreshold. This triggers handling, - // but does not cap the total size of a bundle. - BundleByteThreshold int - - // The maximum size of a bundle, in bytes. Zero means unlimited. - BundleByteLimit int - - // The maximum number of bytes that the Bundler will keep in memory before - // returning ErrOverflow. The default is DefaultBufferedByteLimit. - BufferedByteLimit int - - // The maximum number of handler invocations that can be running at once. - // The default is 1. - HandlerLimit int - - handler func(interface{}) // called to handle a bundle - itemSliceZero reflect.Value // nil (zero value) for slice of items - flushTimer *time.Timer // implements DelayThreshold - - mu sync.Mutex - sem *semaphore.Weighted // enforces BufferedByteLimit - semOnce sync.Once - curBundle bundle // incoming items added to this bundle - - // Each bundle is assigned a unique ticket that determines the order in which the - // handler is called. The ticket is assigned with mu locked, but waiting for tickets - // to be handled is done via mu2 and cond, below. - nextTicket uint64 // next ticket to be assigned - - mu2 sync.Mutex - cond *sync.Cond - nextHandled uint64 // next ticket to be handled - - // In this implementation, active uses space proportional to HandlerLimit, and - // waitUntilAllHandled takes time proportional to HandlerLimit each time an acquire - // or release occurs, so large values of HandlerLimit max may cause performance - // issues. - active map[uint64]bool // tickets of bundles actively being handled -} - -type bundle struct { - items reflect.Value // slice of item type - size int // size in bytes of all items -} - -// NewBundler creates a new Bundler. -// -// itemExample is a value of the type that will be bundled. For example, if you -// want to create bundles of *Entry, you could pass &Entry{} for itemExample. -// -// handler is a function that will be called on each bundle. If itemExample is -// of type T, the argument to handler is of type []T. handler is always called -// sequentially for each bundle, and never in parallel. -// -// Configure the Bundler by setting its thresholds and limits before calling -// any of its methods. -func NewBundler(itemExample interface{}, handler func(interface{})) *Bundler { - b := &Bundler{ - DelayThreshold: DefaultDelayThreshold, - BundleCountThreshold: DefaultBundleCountThreshold, - BundleByteThreshold: DefaultBundleByteThreshold, - BufferedByteLimit: DefaultBufferedByteLimit, - HandlerLimit: 1, - - handler: handler, - itemSliceZero: reflect.Zero(reflect.SliceOf(reflect.TypeOf(itemExample))), - active: map[uint64]bool{}, - } - b.curBundle.items = b.itemSliceZero - b.cond = sync.NewCond(&b.mu2) - return b -} - -func (b *Bundler) initSemaphores() { - // Create the semaphores lazily, because the user may set limits - // after NewBundler. - b.semOnce.Do(func() { - b.sem = semaphore.NewWeighted(int64(b.BufferedByteLimit)) - }) -} - -// Add adds item to the current bundle. It marks the bundle for handling and -// starts a new one if any of the thresholds or limits are exceeded. -// -// If the item's size exceeds the maximum bundle size (Bundler.BundleByteLimit), then -// the item can never be handled. Add returns ErrOversizedItem in this case. -// -// If adding the item would exceed the maximum memory allowed -// (Bundler.BufferedByteLimit) or an AddWait call is blocked waiting for -// memory, Add returns ErrOverflow. -// -// Add never blocks. -func (b *Bundler) Add(item interface{}, size int) error { - // If this item exceeds the maximum size of a bundle, - // we can never send it. - if b.BundleByteLimit > 0 && size > b.BundleByteLimit { - return ErrOversizedItem - } - // If adding this item would exceed our allotted memory - // footprint, we can't accept it. - // (TryAcquire also returns false if anything is waiting on the semaphore, - // so calls to Add and AddWait shouldn't be mixed.) - b.initSemaphores() - if !b.sem.TryAcquire(int64(size)) { - return ErrOverflow - } - b.add(item, size) - return nil -} - -// add adds item to the current bundle. It marks the bundle for handling and -// starts a new one if any of the thresholds or limits are exceeded. -func (b *Bundler) add(item interface{}, size int) { - b.mu.Lock() - defer b.mu.Unlock() - - // If adding this item to the current bundle would cause it to exceed the - // maximum bundle size, close the current bundle and start a new one. - if b.BundleByteLimit > 0 && b.curBundle.size+size > b.BundleByteLimit { - b.startFlushLocked() - } - // Add the item. - b.curBundle.items = reflect.Append(b.curBundle.items, reflect.ValueOf(item)) - b.curBundle.size += size - - // Start a timer to flush the item if one isn't already running. - // startFlushLocked clears the timer and closes the bundle at the same time, - // so we only allocate a new timer for the first item in each bundle. - // (We could try to call Reset on the timer instead, but that would add a lot - // of complexity to the code just to save one small allocation.) - if b.flushTimer == nil { - b.flushTimer = time.AfterFunc(b.DelayThreshold, b.Flush) - } - - // If the current bundle equals the count threshold, close it. - if b.curBundle.items.Len() == b.BundleCountThreshold { - b.startFlushLocked() - } - // If the current bundle equals or exceeds the byte threshold, close it. - if b.curBundle.size >= b.BundleByteThreshold { - b.startFlushLocked() - } -} - -// AddWait adds item to the current bundle. It marks the bundle for handling and -// starts a new one if any of the thresholds or limits are exceeded. -// -// If the item's size exceeds the maximum bundle size (Bundler.BundleByteLimit), then -// the item can never be handled. AddWait returns ErrOversizedItem in this case. -// -// If adding the item would exceed the maximum memory allowed (Bundler.BufferedByteLimit), -// AddWait blocks until space is available or ctx is done. -// -// Calls to Add and AddWait should not be mixed on the same Bundler. -func (b *Bundler) AddWait(ctx context.Context, item interface{}, size int) error { - // If this item exceeds the maximum size of a bundle, - // we can never send it. - if b.BundleByteLimit > 0 && size > b.BundleByteLimit { - return ErrOversizedItem - } - // If adding this item would exceed our allotted memory footprint, block - // until space is available. The semaphore is FIFO, so there will be no - // starvation. - b.initSemaphores() - if err := b.sem.Acquire(ctx, int64(size)); err != nil { - return err - } - // Here, we've reserved space for item. Other goroutines can call AddWait - // and even acquire space, but no one can take away our reservation - // (assuming sem.Release is used correctly). So there is no race condition - // resulting from locking the mutex after sem.Acquire returns. - b.add(item, size) - return nil -} - -// Flush invokes the handler for all remaining items in the Bundler and waits -// for it to return. -func (b *Bundler) Flush() { - b.mu.Lock() - b.startFlushLocked() - // Here, all bundles with tickets < b.nextTicket are - // either finished or active. Those are the ones - // we want to wait for. - t := b.nextTicket - b.mu.Unlock() - b.initSemaphores() - b.waitUntilAllHandled(t) -} - -func (b *Bundler) startFlushLocked() { - if b.flushTimer != nil { - b.flushTimer.Stop() - b.flushTimer = nil - } - if b.curBundle.items.Len() == 0 { - return - } - // Here, both semaphores must have been initialized. - bun := b.curBundle - b.curBundle = bundle{items: b.itemSliceZero} - ticket := b.nextTicket - b.nextTicket++ - go func() { - defer func() { - b.sem.Release(int64(bun.size)) - b.release(ticket) - }() - b.acquire(ticket) - b.handler(bun.items.Interface()) - }() -} - -// acquire blocks until ticket is the next to be served, then returns. In order for N -// acquire calls to return, the tickets must be in the range [0, N). A ticket must -// not be presented to acquire more than once. -func (b *Bundler) acquire(ticket uint64) { - b.mu2.Lock() - defer b.mu2.Unlock() - if ticket < b.nextHandled { - panic("bundler: acquire: arg too small") - } - for !(ticket == b.nextHandled && len(b.active) < b.HandlerLimit) { - b.cond.Wait() - } - // Here, - // ticket == b.nextHandled: the caller is the next one to be handled; - // and len(b.active) < b.HandlerLimit: there is space available. - b.active[ticket] = true - b.nextHandled++ - // Broadcast, not Signal: although at most one acquire waiter can make progress, - // there might be waiters in waitUntilAllHandled. - b.cond.Broadcast() -} - -// If a ticket is used for a call to acquire, it must later be passed to release. A -// ticket must not be presented to release more than once. -func (b *Bundler) release(ticket uint64) { - b.mu2.Lock() - defer b.mu2.Unlock() - if !b.active[ticket] { - panic("bundler: release: not an active ticket") - } - delete(b.active, ticket) - b.cond.Broadcast() -} - -// waitUntilAllHandled blocks until all tickets < n have called release, meaning -// all bundles with tickets < n have been handled. -func (b *Bundler) waitUntilAllHandled(n uint64) { - // Proof of correctness of this function. - // "N is acquired" means acquire(N) has returned. - // "N is released" means release(N) has returned. - // 1. If N is acquired, N-1 is acquired. - // Follows from the loop test in acquire, and the fact - // that nextHandled is incremented by 1. - // 2. If nextHandled >= N, then N-1 is acquired. - // Because we only increment nextHandled to N after N-1 is acquired. - // 3. If nextHandled >= N, then all n < N is acquired. - // Follows from #1 and #2. - // 4. If N is acquired and N is not in active, then N is released. - // Because we put N in active before acquire returns, and only - // remove it when it is released. - // Let min(active) be the smallest member of active, or infinity if active is empty. - // 5. If nextHandled >= N and N <= min(active), then all n < N is released. - // From nextHandled >= N and #3, all n < N is acquired. - // N <= min(active) implies n < min(active) for all n < N. So all n < N is not in active. - // So from #4, all n < N is released. - // The loop test below is the antecedent of #5. - b.mu2.Lock() - defer b.mu2.Unlock() - for !(b.nextHandled >= n && n <= min(b.active)) { - b.cond.Wait() - } -} - -// min returns the minimum value of the set s, or the largest uint64 if -// s is empty. -func min(s map[uint64]bool) uint64 { - var m uint64 = math.MaxUint64 - for n := range s { - if n < m { - m = n - } - } - return m -} diff --git a/vendor/google.golang.org/api/transport/dial.go b/vendor/google.golang.org/api/transport/dial.go deleted file mode 100644 index c4c37191bf0..00000000000 --- a/vendor/google.golang.org/api/transport/dial.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package transport supports network connections to HTTP and GRPC servers. -// This package is not intended for use by end developers. Use the -// google.golang.org/api/option package to configure API clients. -package transport - -import ( - "net/http" - - "golang.org/x/net/context" - "google.golang.org/grpc" - - "google.golang.org/api/option" - gtransport "google.golang.org/api/transport/grpc" - htransport "google.golang.org/api/transport/http" -) - -// NewHTTPClient returns an HTTP client for use communicating with a Google cloud -// service, configured with the given ClientOptions. It also returns the endpoint -// for the service as specified in the options. -func NewHTTPClient(ctx context.Context, opts ...option.ClientOption) (*http.Client, string, error) { - return htransport.NewClient(ctx, opts...) -} - -// DialGRPC returns a GRPC connection for use communicating with a Google cloud -// service, configured with the given ClientOptions. -func DialGRPC(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) { - return gtransport.Dial(ctx, opts...) -} - -// DialGRPCInsecure returns an insecure GRPC connection for use communicating -// with fake or mock Google cloud service implementations, such as emulators. -// The connection is configured with the given ClientOptions. -func DialGRPCInsecure(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) { - return gtransport.DialInsecure(ctx, opts...) -} diff --git a/vendor/google.golang.org/api/transport/go19.go b/vendor/google.golang.org/api/transport/go19.go deleted file mode 100644 index 0177e5600cf..00000000000 --- a/vendor/google.golang.org/api/transport/go19.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2018 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build go1.9 - -package transport - -import ( - "golang.org/x/net/context" - "golang.org/x/oauth2/google" - "google.golang.org/api/internal" - "google.golang.org/api/option" -) - -// Creds constructs a google.Credentials from the information in the options, -// or obtains the default credentials in the same way as google.FindDefaultCredentials. -func Creds(ctx context.Context, opts ...option.ClientOption) (*google.Credentials, error) { - var ds internal.DialSettings - for _, opt := range opts { - opt.Apply(&ds) - } - return internal.Creds(ctx, &ds) -} diff --git a/vendor/google.golang.org/api/transport/grpc/dial.go b/vendor/google.golang.org/api/transport/grpc/dial.go deleted file mode 100644 index 2b8ed6b0b80..00000000000 --- a/vendor/google.golang.org/api/transport/grpc/dial.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package transport/grpc supports network connections to GRPC servers. -// This package is not intended for use by end developers. Use the -// google.golang.org/api/option package to configure API clients. -package grpc - -import ( - "errors" - - "golang.org/x/net/context" - "google.golang.org/api/internal" - "google.golang.org/api/option" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/credentials/oauth" -) - -// Set at init time by dial_appengine.go. If nil, we're not on App Engine. -var appengineDialerHook func(context.Context) grpc.DialOption - -// Dial returns a GRPC connection for use communicating with a Google cloud -// service, configured with the given ClientOptions. -func Dial(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) { - return dial(ctx, false, opts) -} - -// DialInsecure returns an insecure GRPC connection for use communicating -// with fake or mock Google cloud service implementations, such as emulators. -// The connection is configured with the given ClientOptions. -func DialInsecure(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) { - return dial(ctx, true, opts) -} - -func dial(ctx context.Context, insecure bool, opts []option.ClientOption) (*grpc.ClientConn, error) { - var o internal.DialSettings - for _, opt := range opts { - opt.Apply(&o) - } - if err := o.Validate(); err != nil { - return nil, err - } - if o.HTTPClient != nil { - return nil, errors.New("unsupported HTTP client specified") - } - if o.GRPCConn != nil { - return o.GRPCConn, nil - } - var grpcOpts []grpc.DialOption - if insecure { - grpcOpts = []grpc.DialOption{grpc.WithInsecure()} - } else if !o.NoAuth { - creds, err := internal.Creds(ctx, &o) - if err != nil { - return nil, err - } - grpcOpts = []grpc.DialOption{ - grpc.WithPerRPCCredentials(oauth.TokenSource{creds.TokenSource}), - grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")), - } - } - if appengineDialerHook != nil { - // Use the Socket API on App Engine. - grpcOpts = append(grpcOpts, appengineDialerHook(ctx)) - } - // Add tracing, but before the other options, so that clients can override the - // gRPC stats handler. - // This assumes that gRPC options are processed in order, left to right. - grpcOpts = addOCStatsHandler(grpcOpts) - grpcOpts = append(grpcOpts, o.GRPCDialOpts...) - if o.UserAgent != "" { - grpcOpts = append(grpcOpts, grpc.WithUserAgent(o.UserAgent)) - } - return grpc.DialContext(ctx, o.Endpoint, grpcOpts...) -} diff --git a/vendor/google.golang.org/api/transport/grpc/dial_appengine.go b/vendor/google.golang.org/api/transport/grpc/dial_appengine.go deleted file mode 100644 index a40cef2506a..00000000000 --- a/vendor/google.golang.org/api/transport/grpc/dial_appengine.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build appengine - -package grpc - -import ( - "net" - "time" - - "golang.org/x/net/context" - "google.golang.org/appengine" - "google.golang.org/appengine/socket" - "google.golang.org/grpc" -) - -func init() { - // NOTE: dev_appserver doesn't currently support SSL. - // When it does, this code can be removed. - if appengine.IsDevAppServer() { - return - } - - appengineDialerHook = func(ctx context.Context) grpc.DialOption { - return grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) { - return socket.DialTimeout(ctx, "tcp", addr, timeout) - }) - } -} diff --git a/vendor/google.golang.org/api/transport/grpc/go18.go b/vendor/google.golang.org/api/transport/grpc/go18.go deleted file mode 100644 index a4b4a994535..00000000000 --- a/vendor/google.golang.org/api/transport/grpc/go18.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2018 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build go1.8 - -package grpc - -import ( - "go.opencensus.io/plugin/ocgrpc" - "google.golang.org/grpc" -) - -func addOCStatsHandler(opts []grpc.DialOption) []grpc.DialOption { - return append(opts, grpc.WithStatsHandler(&ocgrpc.ClientHandler{})) -} diff --git a/vendor/google.golang.org/api/transport/grpc/not_go18.go b/vendor/google.golang.org/api/transport/grpc/not_go18.go deleted file mode 100644 index f509d8636c5..00000000000 --- a/vendor/google.golang.org/api/transport/grpc/not_go18.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2018 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build !go1.8 - -package grpc - -import "google.golang.org/grpc" - -func addOCStatsHandler(opts []grpc.DialOption) []grpc.DialOption { return opts } diff --git a/vendor/google.golang.org/api/transport/http/dial.go b/vendor/google.golang.org/api/transport/http/dial.go deleted file mode 100644 index 5184ff512c6..00000000000 --- a/vendor/google.golang.org/api/transport/http/dial.go +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package transport/http supports network connections to HTTP servers. -// This package is not intended for use by end developers. Use the -// google.golang.org/api/option package to configure API clients. -package http - -import ( - "errors" - "net/http" - - "golang.org/x/net/context" - "golang.org/x/oauth2" - "google.golang.org/api/googleapi/transport" - "google.golang.org/api/internal" - "google.golang.org/api/option" -) - -// NewClient returns an HTTP client for use communicating with a Google cloud -// service, configured with the given ClientOptions. It also returns the endpoint -// for the service as specified in the options. -func NewClient(ctx context.Context, opts ...option.ClientOption) (*http.Client, string, error) { - settings, err := newSettings(opts) - if err != nil { - return nil, "", err - } - // TODO(cbro): consider injecting the User-Agent even if an explicit HTTP client is provided? - if settings.HTTPClient != nil { - return settings.HTTPClient, settings.Endpoint, nil - } - trans, err := newTransport(ctx, defaultBaseTransport(ctx), settings) - if err != nil { - return nil, "", err - } - return &http.Client{Transport: trans}, settings.Endpoint, nil -} - -// NewTransport creates an http.RoundTripper for use communicating with a Google -// cloud service, configured with the given ClientOptions. Its RoundTrip method delegates to base. -func NewTransport(ctx context.Context, base http.RoundTripper, opts ...option.ClientOption) (http.RoundTripper, error) { - settings, err := newSettings(opts) - if err != nil { - return nil, err - } - if settings.HTTPClient != nil { - return nil, errors.New("transport/http: WithHTTPClient passed to NewTransport") - } - return newTransport(ctx, base, settings) -} - -func newTransport(ctx context.Context, base http.RoundTripper, settings *internal.DialSettings) (http.RoundTripper, error) { - trans := base - trans = userAgentTransport{ - base: trans, - userAgent: settings.UserAgent, - } - trans = addOCTransport(trans) - switch { - case settings.NoAuth: - // Do nothing. - case settings.APIKey != "": - trans = &transport.APIKey{ - Transport: trans, - Key: settings.APIKey, - } - default: - creds, err := internal.Creds(ctx, settings) - if err != nil { - return nil, err - } - trans = &oauth2.Transport{ - Base: trans, - Source: creds.TokenSource, - } - } - return trans, nil -} - -func newSettings(opts []option.ClientOption) (*internal.DialSettings, error) { - var o internal.DialSettings - for _, opt := range opts { - opt.Apply(&o) - } - if err := o.Validate(); err != nil { - return nil, err - } - if o.GRPCConn != nil { - return nil, errors.New("unsupported gRPC connection specified") - } - return &o, nil -} - -type userAgentTransport struct { - userAgent string - base http.RoundTripper -} - -func (t userAgentTransport) RoundTrip(req *http.Request) (*http.Response, error) { - rt := t.base - if rt == nil { - return nil, errors.New("transport: no Transport specified") - } - if t.userAgent == "" { - return rt.RoundTrip(req) - } - newReq := *req - newReq.Header = make(http.Header) - for k, vv := range req.Header { - newReq.Header[k] = vv - } - // TODO(cbro): append to existing User-Agent header? - newReq.Header["User-Agent"] = []string{t.userAgent} - return rt.RoundTrip(&newReq) -} - -// Set at init time by dial_appengine.go. If nil, we're not on App Engine. -var appengineUrlfetchHook func(context.Context) http.RoundTripper - -// defaultBaseTransport returns the base HTTP transport. -// On App Engine, this is urlfetch.Transport, otherwise it's http.DefaultTransport. -func defaultBaseTransport(ctx context.Context) http.RoundTripper { - if appengineUrlfetchHook != nil { - return appengineUrlfetchHook(ctx) - } - return http.DefaultTransport -} diff --git a/vendor/google.golang.org/api/transport/http/dial_appengine.go b/vendor/google.golang.org/api/transport/http/dial_appengine.go deleted file mode 100644 index 0cdef74ac13..00000000000 --- a/vendor/google.golang.org/api/transport/http/dial_appengine.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build appengine - -package http - -import ( - "net/http" - - "golang.org/x/net/context" - "google.golang.org/appengine/urlfetch" -) - -func init() { - appengineUrlfetchHook = func(ctx context.Context) http.RoundTripper { - return &urlfetch.Transport{Context: ctx} - } -} diff --git a/vendor/google.golang.org/api/transport/http/go18.go b/vendor/google.golang.org/api/transport/http/go18.go deleted file mode 100644 index 1d4bb8e7fb4..00000000000 --- a/vendor/google.golang.org/api/transport/http/go18.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2018 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build go1.8 - -package http - -import ( - "net/http" - - "go.opencensus.io/exporter/stackdriver/propagation" - "go.opencensus.io/plugin/ochttp" -) - -func addOCTransport(trans http.RoundTripper) http.RoundTripper { - return &ochttp.Transport{ - Base: trans, - Propagation: &propagation.HTTPFormat{}, - } -} diff --git a/vendor/google.golang.org/api/transport/http/not_go18.go b/vendor/google.golang.org/api/transport/http/not_go18.go deleted file mode 100644 index 628a21a84d6..00000000000 --- a/vendor/google.golang.org/api/transport/http/not_go18.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2018 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build !go1.8 - -package http - -import "net/http" - -func addOCTransport(trans http.RoundTripper) http.RoundTripper { return trans } diff --git a/vendor/google.golang.org/api/transport/not_go19.go b/vendor/google.golang.org/api/transport/not_go19.go deleted file mode 100644 index 4489bc9b6e4..00000000000 --- a/vendor/google.golang.org/api/transport/not_go19.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2018 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build !go1.9 - -package transport - -import ( - "golang.org/x/net/context" - "golang.org/x/oauth2/google" - "google.golang.org/api/internal" - "google.golang.org/api/option" -) - -// Creds constructs a google.DefaultCredentials from the information in the options, -// or obtains the default credentials in the same way as google.FindDefaultCredentials. -func Creds(ctx context.Context, opts ...option.ClientOption) (*google.DefaultCredentials, error) { - var ds internal.DialSettings - for _, opt := range opts { - opt.Apply(&ds) - } - return internal.Creds(ctx, &ds) -} diff --git a/vendor/google.golang.org/appengine/internal/socket/socket_service.pb.go b/vendor/google.golang.org/appengine/internal/socket/socket_service.pb.go deleted file mode 100644 index 60628ec9b9c..00000000000 --- a/vendor/google.golang.org/appengine/internal/socket/socket_service.pb.go +++ /dev/null @@ -1,1858 +0,0 @@ -// Code generated by protoc-gen-go. -// source: google.golang.org/appengine/internal/socket/socket_service.proto -// DO NOT EDIT! - -/* -Package socket is a generated protocol buffer package. - -It is generated from these files: - google.golang.org/appengine/internal/socket/socket_service.proto - -It has these top-level messages: - RemoteSocketServiceError - AddressPort - CreateSocketRequest - CreateSocketReply - BindRequest - BindReply - GetSocketNameRequest - GetSocketNameReply - GetPeerNameRequest - GetPeerNameReply - SocketOption - SetSocketOptionsRequest - SetSocketOptionsReply - GetSocketOptionsRequest - GetSocketOptionsReply - ConnectRequest - ConnectReply - ListenRequest - ListenReply - AcceptRequest - AcceptReply - ShutDownRequest - ShutDownReply - CloseRequest - CloseReply - SendRequest - SendReply - ReceiveRequest - ReceiveReply - PollEvent - PollRequest - PollReply - ResolveRequest - ResolveReply -*/ -package socket - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -type RemoteSocketServiceError_ErrorCode int32 - -const ( - RemoteSocketServiceError_SYSTEM_ERROR RemoteSocketServiceError_ErrorCode = 1 - RemoteSocketServiceError_GAI_ERROR RemoteSocketServiceError_ErrorCode = 2 - RemoteSocketServiceError_FAILURE RemoteSocketServiceError_ErrorCode = 4 - RemoteSocketServiceError_PERMISSION_DENIED RemoteSocketServiceError_ErrorCode = 5 - RemoteSocketServiceError_INVALID_REQUEST RemoteSocketServiceError_ErrorCode = 6 - RemoteSocketServiceError_SOCKET_CLOSED RemoteSocketServiceError_ErrorCode = 7 -) - -var RemoteSocketServiceError_ErrorCode_name = map[int32]string{ - 1: "SYSTEM_ERROR", - 2: "GAI_ERROR", - 4: "FAILURE", - 5: "PERMISSION_DENIED", - 6: "INVALID_REQUEST", - 7: "SOCKET_CLOSED", -} -var RemoteSocketServiceError_ErrorCode_value = map[string]int32{ - "SYSTEM_ERROR": 1, - "GAI_ERROR": 2, - "FAILURE": 4, - "PERMISSION_DENIED": 5, - "INVALID_REQUEST": 6, - "SOCKET_CLOSED": 7, -} - -func (x RemoteSocketServiceError_ErrorCode) Enum() *RemoteSocketServiceError_ErrorCode { - p := new(RemoteSocketServiceError_ErrorCode) - *p = x - return p -} -func (x RemoteSocketServiceError_ErrorCode) String() string { - return proto.EnumName(RemoteSocketServiceError_ErrorCode_name, int32(x)) -} -func (x *RemoteSocketServiceError_ErrorCode) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(RemoteSocketServiceError_ErrorCode_value, data, "RemoteSocketServiceError_ErrorCode") - if err != nil { - return err - } - *x = RemoteSocketServiceError_ErrorCode(value) - return nil -} - -type RemoteSocketServiceError_SystemError int32 - -const ( - RemoteSocketServiceError_SYS_SUCCESS RemoteSocketServiceError_SystemError = 0 - RemoteSocketServiceError_SYS_EPERM RemoteSocketServiceError_SystemError = 1 - RemoteSocketServiceError_SYS_ENOENT RemoteSocketServiceError_SystemError = 2 - RemoteSocketServiceError_SYS_ESRCH RemoteSocketServiceError_SystemError = 3 - RemoteSocketServiceError_SYS_EINTR RemoteSocketServiceError_SystemError = 4 - RemoteSocketServiceError_SYS_EIO RemoteSocketServiceError_SystemError = 5 - RemoteSocketServiceError_SYS_ENXIO RemoteSocketServiceError_SystemError = 6 - RemoteSocketServiceError_SYS_E2BIG RemoteSocketServiceError_SystemError = 7 - RemoteSocketServiceError_SYS_ENOEXEC RemoteSocketServiceError_SystemError = 8 - RemoteSocketServiceError_SYS_EBADF RemoteSocketServiceError_SystemError = 9 - RemoteSocketServiceError_SYS_ECHILD RemoteSocketServiceError_SystemError = 10 - RemoteSocketServiceError_SYS_EAGAIN RemoteSocketServiceError_SystemError = 11 - RemoteSocketServiceError_SYS_EWOULDBLOCK RemoteSocketServiceError_SystemError = 11 - RemoteSocketServiceError_SYS_ENOMEM RemoteSocketServiceError_SystemError = 12 - RemoteSocketServiceError_SYS_EACCES RemoteSocketServiceError_SystemError = 13 - RemoteSocketServiceError_SYS_EFAULT RemoteSocketServiceError_SystemError = 14 - RemoteSocketServiceError_SYS_ENOTBLK RemoteSocketServiceError_SystemError = 15 - RemoteSocketServiceError_SYS_EBUSY RemoteSocketServiceError_SystemError = 16 - RemoteSocketServiceError_SYS_EEXIST RemoteSocketServiceError_SystemError = 17 - RemoteSocketServiceError_SYS_EXDEV RemoteSocketServiceError_SystemError = 18 - RemoteSocketServiceError_SYS_ENODEV RemoteSocketServiceError_SystemError = 19 - RemoteSocketServiceError_SYS_ENOTDIR RemoteSocketServiceError_SystemError = 20 - RemoteSocketServiceError_SYS_EISDIR RemoteSocketServiceError_SystemError = 21 - RemoteSocketServiceError_SYS_EINVAL RemoteSocketServiceError_SystemError = 22 - RemoteSocketServiceError_SYS_ENFILE RemoteSocketServiceError_SystemError = 23 - RemoteSocketServiceError_SYS_EMFILE RemoteSocketServiceError_SystemError = 24 - RemoteSocketServiceError_SYS_ENOTTY RemoteSocketServiceError_SystemError = 25 - RemoteSocketServiceError_SYS_ETXTBSY RemoteSocketServiceError_SystemError = 26 - RemoteSocketServiceError_SYS_EFBIG RemoteSocketServiceError_SystemError = 27 - RemoteSocketServiceError_SYS_ENOSPC RemoteSocketServiceError_SystemError = 28 - RemoteSocketServiceError_SYS_ESPIPE RemoteSocketServiceError_SystemError = 29 - RemoteSocketServiceError_SYS_EROFS RemoteSocketServiceError_SystemError = 30 - RemoteSocketServiceError_SYS_EMLINK RemoteSocketServiceError_SystemError = 31 - RemoteSocketServiceError_SYS_EPIPE RemoteSocketServiceError_SystemError = 32 - RemoteSocketServiceError_SYS_EDOM RemoteSocketServiceError_SystemError = 33 - RemoteSocketServiceError_SYS_ERANGE RemoteSocketServiceError_SystemError = 34 - RemoteSocketServiceError_SYS_EDEADLK RemoteSocketServiceError_SystemError = 35 - RemoteSocketServiceError_SYS_EDEADLOCK RemoteSocketServiceError_SystemError = 35 - RemoteSocketServiceError_SYS_ENAMETOOLONG RemoteSocketServiceError_SystemError = 36 - RemoteSocketServiceError_SYS_ENOLCK RemoteSocketServiceError_SystemError = 37 - RemoteSocketServiceError_SYS_ENOSYS RemoteSocketServiceError_SystemError = 38 - RemoteSocketServiceError_SYS_ENOTEMPTY RemoteSocketServiceError_SystemError = 39 - RemoteSocketServiceError_SYS_ELOOP RemoteSocketServiceError_SystemError = 40 - RemoteSocketServiceError_SYS_ENOMSG RemoteSocketServiceError_SystemError = 42 - RemoteSocketServiceError_SYS_EIDRM RemoteSocketServiceError_SystemError = 43 - RemoteSocketServiceError_SYS_ECHRNG RemoteSocketServiceError_SystemError = 44 - RemoteSocketServiceError_SYS_EL2NSYNC RemoteSocketServiceError_SystemError = 45 - RemoteSocketServiceError_SYS_EL3HLT RemoteSocketServiceError_SystemError = 46 - RemoteSocketServiceError_SYS_EL3RST RemoteSocketServiceError_SystemError = 47 - RemoteSocketServiceError_SYS_ELNRNG RemoteSocketServiceError_SystemError = 48 - RemoteSocketServiceError_SYS_EUNATCH RemoteSocketServiceError_SystemError = 49 - RemoteSocketServiceError_SYS_ENOCSI RemoteSocketServiceError_SystemError = 50 - RemoteSocketServiceError_SYS_EL2HLT RemoteSocketServiceError_SystemError = 51 - RemoteSocketServiceError_SYS_EBADE RemoteSocketServiceError_SystemError = 52 - RemoteSocketServiceError_SYS_EBADR RemoteSocketServiceError_SystemError = 53 - RemoteSocketServiceError_SYS_EXFULL RemoteSocketServiceError_SystemError = 54 - RemoteSocketServiceError_SYS_ENOANO RemoteSocketServiceError_SystemError = 55 - RemoteSocketServiceError_SYS_EBADRQC RemoteSocketServiceError_SystemError = 56 - RemoteSocketServiceError_SYS_EBADSLT RemoteSocketServiceError_SystemError = 57 - RemoteSocketServiceError_SYS_EBFONT RemoteSocketServiceError_SystemError = 59 - RemoteSocketServiceError_SYS_ENOSTR RemoteSocketServiceError_SystemError = 60 - RemoteSocketServiceError_SYS_ENODATA RemoteSocketServiceError_SystemError = 61 - RemoteSocketServiceError_SYS_ETIME RemoteSocketServiceError_SystemError = 62 - RemoteSocketServiceError_SYS_ENOSR RemoteSocketServiceError_SystemError = 63 - RemoteSocketServiceError_SYS_ENONET RemoteSocketServiceError_SystemError = 64 - RemoteSocketServiceError_SYS_ENOPKG RemoteSocketServiceError_SystemError = 65 - RemoteSocketServiceError_SYS_EREMOTE RemoteSocketServiceError_SystemError = 66 - RemoteSocketServiceError_SYS_ENOLINK RemoteSocketServiceError_SystemError = 67 - RemoteSocketServiceError_SYS_EADV RemoteSocketServiceError_SystemError = 68 - RemoteSocketServiceError_SYS_ESRMNT RemoteSocketServiceError_SystemError = 69 - RemoteSocketServiceError_SYS_ECOMM RemoteSocketServiceError_SystemError = 70 - RemoteSocketServiceError_SYS_EPROTO RemoteSocketServiceError_SystemError = 71 - RemoteSocketServiceError_SYS_EMULTIHOP RemoteSocketServiceError_SystemError = 72 - RemoteSocketServiceError_SYS_EDOTDOT RemoteSocketServiceError_SystemError = 73 - RemoteSocketServiceError_SYS_EBADMSG RemoteSocketServiceError_SystemError = 74 - RemoteSocketServiceError_SYS_EOVERFLOW RemoteSocketServiceError_SystemError = 75 - RemoteSocketServiceError_SYS_ENOTUNIQ RemoteSocketServiceError_SystemError = 76 - RemoteSocketServiceError_SYS_EBADFD RemoteSocketServiceError_SystemError = 77 - RemoteSocketServiceError_SYS_EREMCHG RemoteSocketServiceError_SystemError = 78 - RemoteSocketServiceError_SYS_ELIBACC RemoteSocketServiceError_SystemError = 79 - RemoteSocketServiceError_SYS_ELIBBAD RemoteSocketServiceError_SystemError = 80 - RemoteSocketServiceError_SYS_ELIBSCN RemoteSocketServiceError_SystemError = 81 - RemoteSocketServiceError_SYS_ELIBMAX RemoteSocketServiceError_SystemError = 82 - RemoteSocketServiceError_SYS_ELIBEXEC RemoteSocketServiceError_SystemError = 83 - RemoteSocketServiceError_SYS_EILSEQ RemoteSocketServiceError_SystemError = 84 - RemoteSocketServiceError_SYS_ERESTART RemoteSocketServiceError_SystemError = 85 - RemoteSocketServiceError_SYS_ESTRPIPE RemoteSocketServiceError_SystemError = 86 - RemoteSocketServiceError_SYS_EUSERS RemoteSocketServiceError_SystemError = 87 - RemoteSocketServiceError_SYS_ENOTSOCK RemoteSocketServiceError_SystemError = 88 - RemoteSocketServiceError_SYS_EDESTADDRREQ RemoteSocketServiceError_SystemError = 89 - RemoteSocketServiceError_SYS_EMSGSIZE RemoteSocketServiceError_SystemError = 90 - RemoteSocketServiceError_SYS_EPROTOTYPE RemoteSocketServiceError_SystemError = 91 - RemoteSocketServiceError_SYS_ENOPROTOOPT RemoteSocketServiceError_SystemError = 92 - RemoteSocketServiceError_SYS_EPROTONOSUPPORT RemoteSocketServiceError_SystemError = 93 - RemoteSocketServiceError_SYS_ESOCKTNOSUPPORT RemoteSocketServiceError_SystemError = 94 - RemoteSocketServiceError_SYS_EOPNOTSUPP RemoteSocketServiceError_SystemError = 95 - RemoteSocketServiceError_SYS_ENOTSUP RemoteSocketServiceError_SystemError = 95 - RemoteSocketServiceError_SYS_EPFNOSUPPORT RemoteSocketServiceError_SystemError = 96 - RemoteSocketServiceError_SYS_EAFNOSUPPORT RemoteSocketServiceError_SystemError = 97 - RemoteSocketServiceError_SYS_EADDRINUSE RemoteSocketServiceError_SystemError = 98 - RemoteSocketServiceError_SYS_EADDRNOTAVAIL RemoteSocketServiceError_SystemError = 99 - RemoteSocketServiceError_SYS_ENETDOWN RemoteSocketServiceError_SystemError = 100 - RemoteSocketServiceError_SYS_ENETUNREACH RemoteSocketServiceError_SystemError = 101 - RemoteSocketServiceError_SYS_ENETRESET RemoteSocketServiceError_SystemError = 102 - RemoteSocketServiceError_SYS_ECONNABORTED RemoteSocketServiceError_SystemError = 103 - RemoteSocketServiceError_SYS_ECONNRESET RemoteSocketServiceError_SystemError = 104 - RemoteSocketServiceError_SYS_ENOBUFS RemoteSocketServiceError_SystemError = 105 - RemoteSocketServiceError_SYS_EISCONN RemoteSocketServiceError_SystemError = 106 - RemoteSocketServiceError_SYS_ENOTCONN RemoteSocketServiceError_SystemError = 107 - RemoteSocketServiceError_SYS_ESHUTDOWN RemoteSocketServiceError_SystemError = 108 - RemoteSocketServiceError_SYS_ETOOMANYREFS RemoteSocketServiceError_SystemError = 109 - RemoteSocketServiceError_SYS_ETIMEDOUT RemoteSocketServiceError_SystemError = 110 - RemoteSocketServiceError_SYS_ECONNREFUSED RemoteSocketServiceError_SystemError = 111 - RemoteSocketServiceError_SYS_EHOSTDOWN RemoteSocketServiceError_SystemError = 112 - RemoteSocketServiceError_SYS_EHOSTUNREACH RemoteSocketServiceError_SystemError = 113 - RemoteSocketServiceError_SYS_EALREADY RemoteSocketServiceError_SystemError = 114 - RemoteSocketServiceError_SYS_EINPROGRESS RemoteSocketServiceError_SystemError = 115 - RemoteSocketServiceError_SYS_ESTALE RemoteSocketServiceError_SystemError = 116 - RemoteSocketServiceError_SYS_EUCLEAN RemoteSocketServiceError_SystemError = 117 - RemoteSocketServiceError_SYS_ENOTNAM RemoteSocketServiceError_SystemError = 118 - RemoteSocketServiceError_SYS_ENAVAIL RemoteSocketServiceError_SystemError = 119 - RemoteSocketServiceError_SYS_EISNAM RemoteSocketServiceError_SystemError = 120 - RemoteSocketServiceError_SYS_EREMOTEIO RemoteSocketServiceError_SystemError = 121 - RemoteSocketServiceError_SYS_EDQUOT RemoteSocketServiceError_SystemError = 122 - RemoteSocketServiceError_SYS_ENOMEDIUM RemoteSocketServiceError_SystemError = 123 - RemoteSocketServiceError_SYS_EMEDIUMTYPE RemoteSocketServiceError_SystemError = 124 - RemoteSocketServiceError_SYS_ECANCELED RemoteSocketServiceError_SystemError = 125 - RemoteSocketServiceError_SYS_ENOKEY RemoteSocketServiceError_SystemError = 126 - RemoteSocketServiceError_SYS_EKEYEXPIRED RemoteSocketServiceError_SystemError = 127 - RemoteSocketServiceError_SYS_EKEYREVOKED RemoteSocketServiceError_SystemError = 128 - RemoteSocketServiceError_SYS_EKEYREJECTED RemoteSocketServiceError_SystemError = 129 - RemoteSocketServiceError_SYS_EOWNERDEAD RemoteSocketServiceError_SystemError = 130 - RemoteSocketServiceError_SYS_ENOTRECOVERABLE RemoteSocketServiceError_SystemError = 131 - RemoteSocketServiceError_SYS_ERFKILL RemoteSocketServiceError_SystemError = 132 -) - -var RemoteSocketServiceError_SystemError_name = map[int32]string{ - 0: "SYS_SUCCESS", - 1: "SYS_EPERM", - 2: "SYS_ENOENT", - 3: "SYS_ESRCH", - 4: "SYS_EINTR", - 5: "SYS_EIO", - 6: "SYS_ENXIO", - 7: "SYS_E2BIG", - 8: "SYS_ENOEXEC", - 9: "SYS_EBADF", - 10: "SYS_ECHILD", - 11: "SYS_EAGAIN", - // Duplicate value: 11: "SYS_EWOULDBLOCK", - 12: "SYS_ENOMEM", - 13: "SYS_EACCES", - 14: "SYS_EFAULT", - 15: "SYS_ENOTBLK", - 16: "SYS_EBUSY", - 17: "SYS_EEXIST", - 18: "SYS_EXDEV", - 19: "SYS_ENODEV", - 20: "SYS_ENOTDIR", - 21: "SYS_EISDIR", - 22: "SYS_EINVAL", - 23: "SYS_ENFILE", - 24: "SYS_EMFILE", - 25: "SYS_ENOTTY", - 26: "SYS_ETXTBSY", - 27: "SYS_EFBIG", - 28: "SYS_ENOSPC", - 29: "SYS_ESPIPE", - 30: "SYS_EROFS", - 31: "SYS_EMLINK", - 32: "SYS_EPIPE", - 33: "SYS_EDOM", - 34: "SYS_ERANGE", - 35: "SYS_EDEADLK", - // Duplicate value: 35: "SYS_EDEADLOCK", - 36: "SYS_ENAMETOOLONG", - 37: "SYS_ENOLCK", - 38: "SYS_ENOSYS", - 39: "SYS_ENOTEMPTY", - 40: "SYS_ELOOP", - 42: "SYS_ENOMSG", - 43: "SYS_EIDRM", - 44: "SYS_ECHRNG", - 45: "SYS_EL2NSYNC", - 46: "SYS_EL3HLT", - 47: "SYS_EL3RST", - 48: "SYS_ELNRNG", - 49: "SYS_EUNATCH", - 50: "SYS_ENOCSI", - 51: "SYS_EL2HLT", - 52: "SYS_EBADE", - 53: "SYS_EBADR", - 54: "SYS_EXFULL", - 55: "SYS_ENOANO", - 56: "SYS_EBADRQC", - 57: "SYS_EBADSLT", - 59: "SYS_EBFONT", - 60: "SYS_ENOSTR", - 61: "SYS_ENODATA", - 62: "SYS_ETIME", - 63: "SYS_ENOSR", - 64: "SYS_ENONET", - 65: "SYS_ENOPKG", - 66: "SYS_EREMOTE", - 67: "SYS_ENOLINK", - 68: "SYS_EADV", - 69: "SYS_ESRMNT", - 70: "SYS_ECOMM", - 71: "SYS_EPROTO", - 72: "SYS_EMULTIHOP", - 73: "SYS_EDOTDOT", - 74: "SYS_EBADMSG", - 75: "SYS_EOVERFLOW", - 76: "SYS_ENOTUNIQ", - 77: "SYS_EBADFD", - 78: "SYS_EREMCHG", - 79: "SYS_ELIBACC", - 80: "SYS_ELIBBAD", - 81: "SYS_ELIBSCN", - 82: "SYS_ELIBMAX", - 83: "SYS_ELIBEXEC", - 84: "SYS_EILSEQ", - 85: "SYS_ERESTART", - 86: "SYS_ESTRPIPE", - 87: "SYS_EUSERS", - 88: "SYS_ENOTSOCK", - 89: "SYS_EDESTADDRREQ", - 90: "SYS_EMSGSIZE", - 91: "SYS_EPROTOTYPE", - 92: "SYS_ENOPROTOOPT", - 93: "SYS_EPROTONOSUPPORT", - 94: "SYS_ESOCKTNOSUPPORT", - 95: "SYS_EOPNOTSUPP", - // Duplicate value: 95: "SYS_ENOTSUP", - 96: "SYS_EPFNOSUPPORT", - 97: "SYS_EAFNOSUPPORT", - 98: "SYS_EADDRINUSE", - 99: "SYS_EADDRNOTAVAIL", - 100: "SYS_ENETDOWN", - 101: "SYS_ENETUNREACH", - 102: "SYS_ENETRESET", - 103: "SYS_ECONNABORTED", - 104: "SYS_ECONNRESET", - 105: "SYS_ENOBUFS", - 106: "SYS_EISCONN", - 107: "SYS_ENOTCONN", - 108: "SYS_ESHUTDOWN", - 109: "SYS_ETOOMANYREFS", - 110: "SYS_ETIMEDOUT", - 111: "SYS_ECONNREFUSED", - 112: "SYS_EHOSTDOWN", - 113: "SYS_EHOSTUNREACH", - 114: "SYS_EALREADY", - 115: "SYS_EINPROGRESS", - 116: "SYS_ESTALE", - 117: "SYS_EUCLEAN", - 118: "SYS_ENOTNAM", - 119: "SYS_ENAVAIL", - 120: "SYS_EISNAM", - 121: "SYS_EREMOTEIO", - 122: "SYS_EDQUOT", - 123: "SYS_ENOMEDIUM", - 124: "SYS_EMEDIUMTYPE", - 125: "SYS_ECANCELED", - 126: "SYS_ENOKEY", - 127: "SYS_EKEYEXPIRED", - 128: "SYS_EKEYREVOKED", - 129: "SYS_EKEYREJECTED", - 130: "SYS_EOWNERDEAD", - 131: "SYS_ENOTRECOVERABLE", - 132: "SYS_ERFKILL", -} -var RemoteSocketServiceError_SystemError_value = map[string]int32{ - "SYS_SUCCESS": 0, - "SYS_EPERM": 1, - "SYS_ENOENT": 2, - "SYS_ESRCH": 3, - "SYS_EINTR": 4, - "SYS_EIO": 5, - "SYS_ENXIO": 6, - "SYS_E2BIG": 7, - "SYS_ENOEXEC": 8, - "SYS_EBADF": 9, - "SYS_ECHILD": 10, - "SYS_EAGAIN": 11, - "SYS_EWOULDBLOCK": 11, - "SYS_ENOMEM": 12, - "SYS_EACCES": 13, - "SYS_EFAULT": 14, - "SYS_ENOTBLK": 15, - "SYS_EBUSY": 16, - "SYS_EEXIST": 17, - "SYS_EXDEV": 18, - "SYS_ENODEV": 19, - "SYS_ENOTDIR": 20, - "SYS_EISDIR": 21, - "SYS_EINVAL": 22, - "SYS_ENFILE": 23, - "SYS_EMFILE": 24, - "SYS_ENOTTY": 25, - "SYS_ETXTBSY": 26, - "SYS_EFBIG": 27, - "SYS_ENOSPC": 28, - "SYS_ESPIPE": 29, - "SYS_EROFS": 30, - "SYS_EMLINK": 31, - "SYS_EPIPE": 32, - "SYS_EDOM": 33, - "SYS_ERANGE": 34, - "SYS_EDEADLK": 35, - "SYS_EDEADLOCK": 35, - "SYS_ENAMETOOLONG": 36, - "SYS_ENOLCK": 37, - "SYS_ENOSYS": 38, - "SYS_ENOTEMPTY": 39, - "SYS_ELOOP": 40, - "SYS_ENOMSG": 42, - "SYS_EIDRM": 43, - "SYS_ECHRNG": 44, - "SYS_EL2NSYNC": 45, - "SYS_EL3HLT": 46, - "SYS_EL3RST": 47, - "SYS_ELNRNG": 48, - "SYS_EUNATCH": 49, - "SYS_ENOCSI": 50, - "SYS_EL2HLT": 51, - "SYS_EBADE": 52, - "SYS_EBADR": 53, - "SYS_EXFULL": 54, - "SYS_ENOANO": 55, - "SYS_EBADRQC": 56, - "SYS_EBADSLT": 57, - "SYS_EBFONT": 59, - "SYS_ENOSTR": 60, - "SYS_ENODATA": 61, - "SYS_ETIME": 62, - "SYS_ENOSR": 63, - "SYS_ENONET": 64, - "SYS_ENOPKG": 65, - "SYS_EREMOTE": 66, - "SYS_ENOLINK": 67, - "SYS_EADV": 68, - "SYS_ESRMNT": 69, - "SYS_ECOMM": 70, - "SYS_EPROTO": 71, - "SYS_EMULTIHOP": 72, - "SYS_EDOTDOT": 73, - "SYS_EBADMSG": 74, - "SYS_EOVERFLOW": 75, - "SYS_ENOTUNIQ": 76, - "SYS_EBADFD": 77, - "SYS_EREMCHG": 78, - "SYS_ELIBACC": 79, - "SYS_ELIBBAD": 80, - "SYS_ELIBSCN": 81, - "SYS_ELIBMAX": 82, - "SYS_ELIBEXEC": 83, - "SYS_EILSEQ": 84, - "SYS_ERESTART": 85, - "SYS_ESTRPIPE": 86, - "SYS_EUSERS": 87, - "SYS_ENOTSOCK": 88, - "SYS_EDESTADDRREQ": 89, - "SYS_EMSGSIZE": 90, - "SYS_EPROTOTYPE": 91, - "SYS_ENOPROTOOPT": 92, - "SYS_EPROTONOSUPPORT": 93, - "SYS_ESOCKTNOSUPPORT": 94, - "SYS_EOPNOTSUPP": 95, - "SYS_ENOTSUP": 95, - "SYS_EPFNOSUPPORT": 96, - "SYS_EAFNOSUPPORT": 97, - "SYS_EADDRINUSE": 98, - "SYS_EADDRNOTAVAIL": 99, - "SYS_ENETDOWN": 100, - "SYS_ENETUNREACH": 101, - "SYS_ENETRESET": 102, - "SYS_ECONNABORTED": 103, - "SYS_ECONNRESET": 104, - "SYS_ENOBUFS": 105, - "SYS_EISCONN": 106, - "SYS_ENOTCONN": 107, - "SYS_ESHUTDOWN": 108, - "SYS_ETOOMANYREFS": 109, - "SYS_ETIMEDOUT": 110, - "SYS_ECONNREFUSED": 111, - "SYS_EHOSTDOWN": 112, - "SYS_EHOSTUNREACH": 113, - "SYS_EALREADY": 114, - "SYS_EINPROGRESS": 115, - "SYS_ESTALE": 116, - "SYS_EUCLEAN": 117, - "SYS_ENOTNAM": 118, - "SYS_ENAVAIL": 119, - "SYS_EISNAM": 120, - "SYS_EREMOTEIO": 121, - "SYS_EDQUOT": 122, - "SYS_ENOMEDIUM": 123, - "SYS_EMEDIUMTYPE": 124, - "SYS_ECANCELED": 125, - "SYS_ENOKEY": 126, - "SYS_EKEYEXPIRED": 127, - "SYS_EKEYREVOKED": 128, - "SYS_EKEYREJECTED": 129, - "SYS_EOWNERDEAD": 130, - "SYS_ENOTRECOVERABLE": 131, - "SYS_ERFKILL": 132, -} - -func (x RemoteSocketServiceError_SystemError) Enum() *RemoteSocketServiceError_SystemError { - p := new(RemoteSocketServiceError_SystemError) - *p = x - return p -} -func (x RemoteSocketServiceError_SystemError) String() string { - return proto.EnumName(RemoteSocketServiceError_SystemError_name, int32(x)) -} -func (x *RemoteSocketServiceError_SystemError) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(RemoteSocketServiceError_SystemError_value, data, "RemoteSocketServiceError_SystemError") - if err != nil { - return err - } - *x = RemoteSocketServiceError_SystemError(value) - return nil -} - -type CreateSocketRequest_SocketFamily int32 - -const ( - CreateSocketRequest_IPv4 CreateSocketRequest_SocketFamily = 1 - CreateSocketRequest_IPv6 CreateSocketRequest_SocketFamily = 2 -) - -var CreateSocketRequest_SocketFamily_name = map[int32]string{ - 1: "IPv4", - 2: "IPv6", -} -var CreateSocketRequest_SocketFamily_value = map[string]int32{ - "IPv4": 1, - "IPv6": 2, -} - -func (x CreateSocketRequest_SocketFamily) Enum() *CreateSocketRequest_SocketFamily { - p := new(CreateSocketRequest_SocketFamily) - *p = x - return p -} -func (x CreateSocketRequest_SocketFamily) String() string { - return proto.EnumName(CreateSocketRequest_SocketFamily_name, int32(x)) -} -func (x *CreateSocketRequest_SocketFamily) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(CreateSocketRequest_SocketFamily_value, data, "CreateSocketRequest_SocketFamily") - if err != nil { - return err - } - *x = CreateSocketRequest_SocketFamily(value) - return nil -} - -type CreateSocketRequest_SocketProtocol int32 - -const ( - CreateSocketRequest_TCP CreateSocketRequest_SocketProtocol = 1 - CreateSocketRequest_UDP CreateSocketRequest_SocketProtocol = 2 -) - -var CreateSocketRequest_SocketProtocol_name = map[int32]string{ - 1: "TCP", - 2: "UDP", -} -var CreateSocketRequest_SocketProtocol_value = map[string]int32{ - "TCP": 1, - "UDP": 2, -} - -func (x CreateSocketRequest_SocketProtocol) Enum() *CreateSocketRequest_SocketProtocol { - p := new(CreateSocketRequest_SocketProtocol) - *p = x - return p -} -func (x CreateSocketRequest_SocketProtocol) String() string { - return proto.EnumName(CreateSocketRequest_SocketProtocol_name, int32(x)) -} -func (x *CreateSocketRequest_SocketProtocol) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(CreateSocketRequest_SocketProtocol_value, data, "CreateSocketRequest_SocketProtocol") - if err != nil { - return err - } - *x = CreateSocketRequest_SocketProtocol(value) - return nil -} - -type SocketOption_SocketOptionLevel int32 - -const ( - SocketOption_SOCKET_SOL_IP SocketOption_SocketOptionLevel = 0 - SocketOption_SOCKET_SOL_SOCKET SocketOption_SocketOptionLevel = 1 - SocketOption_SOCKET_SOL_TCP SocketOption_SocketOptionLevel = 6 - SocketOption_SOCKET_SOL_UDP SocketOption_SocketOptionLevel = 17 -) - -var SocketOption_SocketOptionLevel_name = map[int32]string{ - 0: "SOCKET_SOL_IP", - 1: "SOCKET_SOL_SOCKET", - 6: "SOCKET_SOL_TCP", - 17: "SOCKET_SOL_UDP", -} -var SocketOption_SocketOptionLevel_value = map[string]int32{ - "SOCKET_SOL_IP": 0, - "SOCKET_SOL_SOCKET": 1, - "SOCKET_SOL_TCP": 6, - "SOCKET_SOL_UDP": 17, -} - -func (x SocketOption_SocketOptionLevel) Enum() *SocketOption_SocketOptionLevel { - p := new(SocketOption_SocketOptionLevel) - *p = x - return p -} -func (x SocketOption_SocketOptionLevel) String() string { - return proto.EnumName(SocketOption_SocketOptionLevel_name, int32(x)) -} -func (x *SocketOption_SocketOptionLevel) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(SocketOption_SocketOptionLevel_value, data, "SocketOption_SocketOptionLevel") - if err != nil { - return err - } - *x = SocketOption_SocketOptionLevel(value) - return nil -} - -type SocketOption_SocketOptionName int32 - -const ( - SocketOption_SOCKET_SO_DEBUG SocketOption_SocketOptionName = 1 - SocketOption_SOCKET_SO_REUSEADDR SocketOption_SocketOptionName = 2 - SocketOption_SOCKET_SO_TYPE SocketOption_SocketOptionName = 3 - SocketOption_SOCKET_SO_ERROR SocketOption_SocketOptionName = 4 - SocketOption_SOCKET_SO_DONTROUTE SocketOption_SocketOptionName = 5 - SocketOption_SOCKET_SO_BROADCAST SocketOption_SocketOptionName = 6 - SocketOption_SOCKET_SO_SNDBUF SocketOption_SocketOptionName = 7 - SocketOption_SOCKET_SO_RCVBUF SocketOption_SocketOptionName = 8 - SocketOption_SOCKET_SO_KEEPALIVE SocketOption_SocketOptionName = 9 - SocketOption_SOCKET_SO_OOBINLINE SocketOption_SocketOptionName = 10 - SocketOption_SOCKET_SO_LINGER SocketOption_SocketOptionName = 13 - SocketOption_SOCKET_SO_RCVTIMEO SocketOption_SocketOptionName = 20 - SocketOption_SOCKET_SO_SNDTIMEO SocketOption_SocketOptionName = 21 - SocketOption_SOCKET_IP_TOS SocketOption_SocketOptionName = 1 - SocketOption_SOCKET_IP_TTL SocketOption_SocketOptionName = 2 - SocketOption_SOCKET_IP_HDRINCL SocketOption_SocketOptionName = 3 - SocketOption_SOCKET_IP_OPTIONS SocketOption_SocketOptionName = 4 - SocketOption_SOCKET_TCP_NODELAY SocketOption_SocketOptionName = 1 - SocketOption_SOCKET_TCP_MAXSEG SocketOption_SocketOptionName = 2 - SocketOption_SOCKET_TCP_CORK SocketOption_SocketOptionName = 3 - SocketOption_SOCKET_TCP_KEEPIDLE SocketOption_SocketOptionName = 4 - SocketOption_SOCKET_TCP_KEEPINTVL SocketOption_SocketOptionName = 5 - SocketOption_SOCKET_TCP_KEEPCNT SocketOption_SocketOptionName = 6 - SocketOption_SOCKET_TCP_SYNCNT SocketOption_SocketOptionName = 7 - SocketOption_SOCKET_TCP_LINGER2 SocketOption_SocketOptionName = 8 - SocketOption_SOCKET_TCP_DEFER_ACCEPT SocketOption_SocketOptionName = 9 - SocketOption_SOCKET_TCP_WINDOW_CLAMP SocketOption_SocketOptionName = 10 - SocketOption_SOCKET_TCP_INFO SocketOption_SocketOptionName = 11 - SocketOption_SOCKET_TCP_QUICKACK SocketOption_SocketOptionName = 12 -) - -var SocketOption_SocketOptionName_name = map[int32]string{ - 1: "SOCKET_SO_DEBUG", - 2: "SOCKET_SO_REUSEADDR", - 3: "SOCKET_SO_TYPE", - 4: "SOCKET_SO_ERROR", - 5: "SOCKET_SO_DONTROUTE", - 6: "SOCKET_SO_BROADCAST", - 7: "SOCKET_SO_SNDBUF", - 8: "SOCKET_SO_RCVBUF", - 9: "SOCKET_SO_KEEPALIVE", - 10: "SOCKET_SO_OOBINLINE", - 13: "SOCKET_SO_LINGER", - 20: "SOCKET_SO_RCVTIMEO", - 21: "SOCKET_SO_SNDTIMEO", - // Duplicate value: 1: "SOCKET_IP_TOS", - // Duplicate value: 2: "SOCKET_IP_TTL", - // Duplicate value: 3: "SOCKET_IP_HDRINCL", - // Duplicate value: 4: "SOCKET_IP_OPTIONS", - // Duplicate value: 1: "SOCKET_TCP_NODELAY", - // Duplicate value: 2: "SOCKET_TCP_MAXSEG", - // Duplicate value: 3: "SOCKET_TCP_CORK", - // Duplicate value: 4: "SOCKET_TCP_KEEPIDLE", - // Duplicate value: 5: "SOCKET_TCP_KEEPINTVL", - // Duplicate value: 6: "SOCKET_TCP_KEEPCNT", - // Duplicate value: 7: "SOCKET_TCP_SYNCNT", - // Duplicate value: 8: "SOCKET_TCP_LINGER2", - // Duplicate value: 9: "SOCKET_TCP_DEFER_ACCEPT", - // Duplicate value: 10: "SOCKET_TCP_WINDOW_CLAMP", - 11: "SOCKET_TCP_INFO", - 12: "SOCKET_TCP_QUICKACK", -} -var SocketOption_SocketOptionName_value = map[string]int32{ - "SOCKET_SO_DEBUG": 1, - "SOCKET_SO_REUSEADDR": 2, - "SOCKET_SO_TYPE": 3, - "SOCKET_SO_ERROR": 4, - "SOCKET_SO_DONTROUTE": 5, - "SOCKET_SO_BROADCAST": 6, - "SOCKET_SO_SNDBUF": 7, - "SOCKET_SO_RCVBUF": 8, - "SOCKET_SO_KEEPALIVE": 9, - "SOCKET_SO_OOBINLINE": 10, - "SOCKET_SO_LINGER": 13, - "SOCKET_SO_RCVTIMEO": 20, - "SOCKET_SO_SNDTIMEO": 21, - "SOCKET_IP_TOS": 1, - "SOCKET_IP_TTL": 2, - "SOCKET_IP_HDRINCL": 3, - "SOCKET_IP_OPTIONS": 4, - "SOCKET_TCP_NODELAY": 1, - "SOCKET_TCP_MAXSEG": 2, - "SOCKET_TCP_CORK": 3, - "SOCKET_TCP_KEEPIDLE": 4, - "SOCKET_TCP_KEEPINTVL": 5, - "SOCKET_TCP_KEEPCNT": 6, - "SOCKET_TCP_SYNCNT": 7, - "SOCKET_TCP_LINGER2": 8, - "SOCKET_TCP_DEFER_ACCEPT": 9, - "SOCKET_TCP_WINDOW_CLAMP": 10, - "SOCKET_TCP_INFO": 11, - "SOCKET_TCP_QUICKACK": 12, -} - -func (x SocketOption_SocketOptionName) Enum() *SocketOption_SocketOptionName { - p := new(SocketOption_SocketOptionName) - *p = x - return p -} -func (x SocketOption_SocketOptionName) String() string { - return proto.EnumName(SocketOption_SocketOptionName_name, int32(x)) -} -func (x *SocketOption_SocketOptionName) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(SocketOption_SocketOptionName_value, data, "SocketOption_SocketOptionName") - if err != nil { - return err - } - *x = SocketOption_SocketOptionName(value) - return nil -} - -type ShutDownRequest_How int32 - -const ( - ShutDownRequest_SOCKET_SHUT_RD ShutDownRequest_How = 1 - ShutDownRequest_SOCKET_SHUT_WR ShutDownRequest_How = 2 - ShutDownRequest_SOCKET_SHUT_RDWR ShutDownRequest_How = 3 -) - -var ShutDownRequest_How_name = map[int32]string{ - 1: "SOCKET_SHUT_RD", - 2: "SOCKET_SHUT_WR", - 3: "SOCKET_SHUT_RDWR", -} -var ShutDownRequest_How_value = map[string]int32{ - "SOCKET_SHUT_RD": 1, - "SOCKET_SHUT_WR": 2, - "SOCKET_SHUT_RDWR": 3, -} - -func (x ShutDownRequest_How) Enum() *ShutDownRequest_How { - p := new(ShutDownRequest_How) - *p = x - return p -} -func (x ShutDownRequest_How) String() string { - return proto.EnumName(ShutDownRequest_How_name, int32(x)) -} -func (x *ShutDownRequest_How) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(ShutDownRequest_How_value, data, "ShutDownRequest_How") - if err != nil { - return err - } - *x = ShutDownRequest_How(value) - return nil -} - -type ReceiveRequest_Flags int32 - -const ( - ReceiveRequest_MSG_OOB ReceiveRequest_Flags = 1 - ReceiveRequest_MSG_PEEK ReceiveRequest_Flags = 2 -) - -var ReceiveRequest_Flags_name = map[int32]string{ - 1: "MSG_OOB", - 2: "MSG_PEEK", -} -var ReceiveRequest_Flags_value = map[string]int32{ - "MSG_OOB": 1, - "MSG_PEEK": 2, -} - -func (x ReceiveRequest_Flags) Enum() *ReceiveRequest_Flags { - p := new(ReceiveRequest_Flags) - *p = x - return p -} -func (x ReceiveRequest_Flags) String() string { - return proto.EnumName(ReceiveRequest_Flags_name, int32(x)) -} -func (x *ReceiveRequest_Flags) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(ReceiveRequest_Flags_value, data, "ReceiveRequest_Flags") - if err != nil { - return err - } - *x = ReceiveRequest_Flags(value) - return nil -} - -type PollEvent_PollEventFlag int32 - -const ( - PollEvent_SOCKET_POLLNONE PollEvent_PollEventFlag = 0 - PollEvent_SOCKET_POLLIN PollEvent_PollEventFlag = 1 - PollEvent_SOCKET_POLLPRI PollEvent_PollEventFlag = 2 - PollEvent_SOCKET_POLLOUT PollEvent_PollEventFlag = 4 - PollEvent_SOCKET_POLLERR PollEvent_PollEventFlag = 8 - PollEvent_SOCKET_POLLHUP PollEvent_PollEventFlag = 16 - PollEvent_SOCKET_POLLNVAL PollEvent_PollEventFlag = 32 - PollEvent_SOCKET_POLLRDNORM PollEvent_PollEventFlag = 64 - PollEvent_SOCKET_POLLRDBAND PollEvent_PollEventFlag = 128 - PollEvent_SOCKET_POLLWRNORM PollEvent_PollEventFlag = 256 - PollEvent_SOCKET_POLLWRBAND PollEvent_PollEventFlag = 512 - PollEvent_SOCKET_POLLMSG PollEvent_PollEventFlag = 1024 - PollEvent_SOCKET_POLLREMOVE PollEvent_PollEventFlag = 4096 - PollEvent_SOCKET_POLLRDHUP PollEvent_PollEventFlag = 8192 -) - -var PollEvent_PollEventFlag_name = map[int32]string{ - 0: "SOCKET_POLLNONE", - 1: "SOCKET_POLLIN", - 2: "SOCKET_POLLPRI", - 4: "SOCKET_POLLOUT", - 8: "SOCKET_POLLERR", - 16: "SOCKET_POLLHUP", - 32: "SOCKET_POLLNVAL", - 64: "SOCKET_POLLRDNORM", - 128: "SOCKET_POLLRDBAND", - 256: "SOCKET_POLLWRNORM", - 512: "SOCKET_POLLWRBAND", - 1024: "SOCKET_POLLMSG", - 4096: "SOCKET_POLLREMOVE", - 8192: "SOCKET_POLLRDHUP", -} -var PollEvent_PollEventFlag_value = map[string]int32{ - "SOCKET_POLLNONE": 0, - "SOCKET_POLLIN": 1, - "SOCKET_POLLPRI": 2, - "SOCKET_POLLOUT": 4, - "SOCKET_POLLERR": 8, - "SOCKET_POLLHUP": 16, - "SOCKET_POLLNVAL": 32, - "SOCKET_POLLRDNORM": 64, - "SOCKET_POLLRDBAND": 128, - "SOCKET_POLLWRNORM": 256, - "SOCKET_POLLWRBAND": 512, - "SOCKET_POLLMSG": 1024, - "SOCKET_POLLREMOVE": 4096, - "SOCKET_POLLRDHUP": 8192, -} - -func (x PollEvent_PollEventFlag) Enum() *PollEvent_PollEventFlag { - p := new(PollEvent_PollEventFlag) - *p = x - return p -} -func (x PollEvent_PollEventFlag) String() string { - return proto.EnumName(PollEvent_PollEventFlag_name, int32(x)) -} -func (x *PollEvent_PollEventFlag) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(PollEvent_PollEventFlag_value, data, "PollEvent_PollEventFlag") - if err != nil { - return err - } - *x = PollEvent_PollEventFlag(value) - return nil -} - -type ResolveReply_ErrorCode int32 - -const ( - ResolveReply_SOCKET_EAI_ADDRFAMILY ResolveReply_ErrorCode = 1 - ResolveReply_SOCKET_EAI_AGAIN ResolveReply_ErrorCode = 2 - ResolveReply_SOCKET_EAI_BADFLAGS ResolveReply_ErrorCode = 3 - ResolveReply_SOCKET_EAI_FAIL ResolveReply_ErrorCode = 4 - ResolveReply_SOCKET_EAI_FAMILY ResolveReply_ErrorCode = 5 - ResolveReply_SOCKET_EAI_MEMORY ResolveReply_ErrorCode = 6 - ResolveReply_SOCKET_EAI_NODATA ResolveReply_ErrorCode = 7 - ResolveReply_SOCKET_EAI_NONAME ResolveReply_ErrorCode = 8 - ResolveReply_SOCKET_EAI_SERVICE ResolveReply_ErrorCode = 9 - ResolveReply_SOCKET_EAI_SOCKTYPE ResolveReply_ErrorCode = 10 - ResolveReply_SOCKET_EAI_SYSTEM ResolveReply_ErrorCode = 11 - ResolveReply_SOCKET_EAI_BADHINTS ResolveReply_ErrorCode = 12 - ResolveReply_SOCKET_EAI_PROTOCOL ResolveReply_ErrorCode = 13 - ResolveReply_SOCKET_EAI_OVERFLOW ResolveReply_ErrorCode = 14 - ResolveReply_SOCKET_EAI_MAX ResolveReply_ErrorCode = 15 -) - -var ResolveReply_ErrorCode_name = map[int32]string{ - 1: "SOCKET_EAI_ADDRFAMILY", - 2: "SOCKET_EAI_AGAIN", - 3: "SOCKET_EAI_BADFLAGS", - 4: "SOCKET_EAI_FAIL", - 5: "SOCKET_EAI_FAMILY", - 6: "SOCKET_EAI_MEMORY", - 7: "SOCKET_EAI_NODATA", - 8: "SOCKET_EAI_NONAME", - 9: "SOCKET_EAI_SERVICE", - 10: "SOCKET_EAI_SOCKTYPE", - 11: "SOCKET_EAI_SYSTEM", - 12: "SOCKET_EAI_BADHINTS", - 13: "SOCKET_EAI_PROTOCOL", - 14: "SOCKET_EAI_OVERFLOW", - 15: "SOCKET_EAI_MAX", -} -var ResolveReply_ErrorCode_value = map[string]int32{ - "SOCKET_EAI_ADDRFAMILY": 1, - "SOCKET_EAI_AGAIN": 2, - "SOCKET_EAI_BADFLAGS": 3, - "SOCKET_EAI_FAIL": 4, - "SOCKET_EAI_FAMILY": 5, - "SOCKET_EAI_MEMORY": 6, - "SOCKET_EAI_NODATA": 7, - "SOCKET_EAI_NONAME": 8, - "SOCKET_EAI_SERVICE": 9, - "SOCKET_EAI_SOCKTYPE": 10, - "SOCKET_EAI_SYSTEM": 11, - "SOCKET_EAI_BADHINTS": 12, - "SOCKET_EAI_PROTOCOL": 13, - "SOCKET_EAI_OVERFLOW": 14, - "SOCKET_EAI_MAX": 15, -} - -func (x ResolveReply_ErrorCode) Enum() *ResolveReply_ErrorCode { - p := new(ResolveReply_ErrorCode) - *p = x - return p -} -func (x ResolveReply_ErrorCode) String() string { - return proto.EnumName(ResolveReply_ErrorCode_name, int32(x)) -} -func (x *ResolveReply_ErrorCode) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(ResolveReply_ErrorCode_value, data, "ResolveReply_ErrorCode") - if err != nil { - return err - } - *x = ResolveReply_ErrorCode(value) - return nil -} - -type RemoteSocketServiceError struct { - SystemError *int32 `protobuf:"varint,1,opt,name=system_error,def=0" json:"system_error,omitempty"` - ErrorDetail *string `protobuf:"bytes,2,opt,name=error_detail" json:"error_detail,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *RemoteSocketServiceError) Reset() { *m = RemoteSocketServiceError{} } -func (m *RemoteSocketServiceError) String() string { return proto.CompactTextString(m) } -func (*RemoteSocketServiceError) ProtoMessage() {} - -const Default_RemoteSocketServiceError_SystemError int32 = 0 - -func (m *RemoteSocketServiceError) GetSystemError() int32 { - if m != nil && m.SystemError != nil { - return *m.SystemError - } - return Default_RemoteSocketServiceError_SystemError -} - -func (m *RemoteSocketServiceError) GetErrorDetail() string { - if m != nil && m.ErrorDetail != nil { - return *m.ErrorDetail - } - return "" -} - -type AddressPort struct { - Port *int32 `protobuf:"varint,1,req,name=port" json:"port,omitempty"` - PackedAddress []byte `protobuf:"bytes,2,opt,name=packed_address" json:"packed_address,omitempty"` - HostnameHint *string `protobuf:"bytes,3,opt,name=hostname_hint" json:"hostname_hint,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *AddressPort) Reset() { *m = AddressPort{} } -func (m *AddressPort) String() string { return proto.CompactTextString(m) } -func (*AddressPort) ProtoMessage() {} - -func (m *AddressPort) GetPort() int32 { - if m != nil && m.Port != nil { - return *m.Port - } - return 0 -} - -func (m *AddressPort) GetPackedAddress() []byte { - if m != nil { - return m.PackedAddress - } - return nil -} - -func (m *AddressPort) GetHostnameHint() string { - if m != nil && m.HostnameHint != nil { - return *m.HostnameHint - } - return "" -} - -type CreateSocketRequest struct { - Family *CreateSocketRequest_SocketFamily `protobuf:"varint,1,req,name=family,enum=appengine.CreateSocketRequest_SocketFamily" json:"family,omitempty"` - Protocol *CreateSocketRequest_SocketProtocol `protobuf:"varint,2,req,name=protocol,enum=appengine.CreateSocketRequest_SocketProtocol" json:"protocol,omitempty"` - SocketOptions []*SocketOption `protobuf:"bytes,3,rep,name=socket_options" json:"socket_options,omitempty"` - ProxyExternalIp *AddressPort `protobuf:"bytes,4,opt,name=proxy_external_ip" json:"proxy_external_ip,omitempty"` - ListenBacklog *int32 `protobuf:"varint,5,opt,name=listen_backlog,def=0" json:"listen_backlog,omitempty"` - RemoteIp *AddressPort `protobuf:"bytes,6,opt,name=remote_ip" json:"remote_ip,omitempty"` - AppId *string `protobuf:"bytes,9,opt,name=app_id" json:"app_id,omitempty"` - ProjectId *int64 `protobuf:"varint,10,opt,name=project_id" json:"project_id,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CreateSocketRequest) Reset() { *m = CreateSocketRequest{} } -func (m *CreateSocketRequest) String() string { return proto.CompactTextString(m) } -func (*CreateSocketRequest) ProtoMessage() {} - -const Default_CreateSocketRequest_ListenBacklog int32 = 0 - -func (m *CreateSocketRequest) GetFamily() CreateSocketRequest_SocketFamily { - if m != nil && m.Family != nil { - return *m.Family - } - return CreateSocketRequest_IPv4 -} - -func (m *CreateSocketRequest) GetProtocol() CreateSocketRequest_SocketProtocol { - if m != nil && m.Protocol != nil { - return *m.Protocol - } - return CreateSocketRequest_TCP -} - -func (m *CreateSocketRequest) GetSocketOptions() []*SocketOption { - if m != nil { - return m.SocketOptions - } - return nil -} - -func (m *CreateSocketRequest) GetProxyExternalIp() *AddressPort { - if m != nil { - return m.ProxyExternalIp - } - return nil -} - -func (m *CreateSocketRequest) GetListenBacklog() int32 { - if m != nil && m.ListenBacklog != nil { - return *m.ListenBacklog - } - return Default_CreateSocketRequest_ListenBacklog -} - -func (m *CreateSocketRequest) GetRemoteIp() *AddressPort { - if m != nil { - return m.RemoteIp - } - return nil -} - -func (m *CreateSocketRequest) GetAppId() string { - if m != nil && m.AppId != nil { - return *m.AppId - } - return "" -} - -func (m *CreateSocketRequest) GetProjectId() int64 { - if m != nil && m.ProjectId != nil { - return *m.ProjectId - } - return 0 -} - -type CreateSocketReply struct { - SocketDescriptor *string `protobuf:"bytes,1,opt,name=socket_descriptor" json:"socket_descriptor,omitempty"` - ServerAddress *AddressPort `protobuf:"bytes,3,opt,name=server_address" json:"server_address,omitempty"` - ProxyExternalIp *AddressPort `protobuf:"bytes,4,opt,name=proxy_external_ip" json:"proxy_external_ip,omitempty"` - XXX_extensions map[int32]proto.Extension `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CreateSocketReply) Reset() { *m = CreateSocketReply{} } -func (m *CreateSocketReply) String() string { return proto.CompactTextString(m) } -func (*CreateSocketReply) ProtoMessage() {} - -var extRange_CreateSocketReply = []proto.ExtensionRange{ - {1000, 536870911}, -} - -func (*CreateSocketReply) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_CreateSocketReply -} -func (m *CreateSocketReply) ExtensionMap() map[int32]proto.Extension { - if m.XXX_extensions == nil { - m.XXX_extensions = make(map[int32]proto.Extension) - } - return m.XXX_extensions -} - -func (m *CreateSocketReply) GetSocketDescriptor() string { - if m != nil && m.SocketDescriptor != nil { - return *m.SocketDescriptor - } - return "" -} - -func (m *CreateSocketReply) GetServerAddress() *AddressPort { - if m != nil { - return m.ServerAddress - } - return nil -} - -func (m *CreateSocketReply) GetProxyExternalIp() *AddressPort { - if m != nil { - return m.ProxyExternalIp - } - return nil -} - -type BindRequest struct { - SocketDescriptor *string `protobuf:"bytes,1,req,name=socket_descriptor" json:"socket_descriptor,omitempty"` - ProxyExternalIp *AddressPort `protobuf:"bytes,2,req,name=proxy_external_ip" json:"proxy_external_ip,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *BindRequest) Reset() { *m = BindRequest{} } -func (m *BindRequest) String() string { return proto.CompactTextString(m) } -func (*BindRequest) ProtoMessage() {} - -func (m *BindRequest) GetSocketDescriptor() string { - if m != nil && m.SocketDescriptor != nil { - return *m.SocketDescriptor - } - return "" -} - -func (m *BindRequest) GetProxyExternalIp() *AddressPort { - if m != nil { - return m.ProxyExternalIp - } - return nil -} - -type BindReply struct { - ProxyExternalIp *AddressPort `protobuf:"bytes,1,opt,name=proxy_external_ip" json:"proxy_external_ip,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *BindReply) Reset() { *m = BindReply{} } -func (m *BindReply) String() string { return proto.CompactTextString(m) } -func (*BindReply) ProtoMessage() {} - -func (m *BindReply) GetProxyExternalIp() *AddressPort { - if m != nil { - return m.ProxyExternalIp - } - return nil -} - -type GetSocketNameRequest struct { - SocketDescriptor *string `protobuf:"bytes,1,req,name=socket_descriptor" json:"socket_descriptor,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetSocketNameRequest) Reset() { *m = GetSocketNameRequest{} } -func (m *GetSocketNameRequest) String() string { return proto.CompactTextString(m) } -func (*GetSocketNameRequest) ProtoMessage() {} - -func (m *GetSocketNameRequest) GetSocketDescriptor() string { - if m != nil && m.SocketDescriptor != nil { - return *m.SocketDescriptor - } - return "" -} - -type GetSocketNameReply struct { - ProxyExternalIp *AddressPort `protobuf:"bytes,2,opt,name=proxy_external_ip" json:"proxy_external_ip,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetSocketNameReply) Reset() { *m = GetSocketNameReply{} } -func (m *GetSocketNameReply) String() string { return proto.CompactTextString(m) } -func (*GetSocketNameReply) ProtoMessage() {} - -func (m *GetSocketNameReply) GetProxyExternalIp() *AddressPort { - if m != nil { - return m.ProxyExternalIp - } - return nil -} - -type GetPeerNameRequest struct { - SocketDescriptor *string `protobuf:"bytes,1,req,name=socket_descriptor" json:"socket_descriptor,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetPeerNameRequest) Reset() { *m = GetPeerNameRequest{} } -func (m *GetPeerNameRequest) String() string { return proto.CompactTextString(m) } -func (*GetPeerNameRequest) ProtoMessage() {} - -func (m *GetPeerNameRequest) GetSocketDescriptor() string { - if m != nil && m.SocketDescriptor != nil { - return *m.SocketDescriptor - } - return "" -} - -type GetPeerNameReply struct { - PeerIp *AddressPort `protobuf:"bytes,2,opt,name=peer_ip" json:"peer_ip,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetPeerNameReply) Reset() { *m = GetPeerNameReply{} } -func (m *GetPeerNameReply) String() string { return proto.CompactTextString(m) } -func (*GetPeerNameReply) ProtoMessage() {} - -func (m *GetPeerNameReply) GetPeerIp() *AddressPort { - if m != nil { - return m.PeerIp - } - return nil -} - -type SocketOption struct { - Level *SocketOption_SocketOptionLevel `protobuf:"varint,1,req,name=level,enum=appengine.SocketOption_SocketOptionLevel" json:"level,omitempty"` - Option *SocketOption_SocketOptionName `protobuf:"varint,2,req,name=option,enum=appengine.SocketOption_SocketOptionName" json:"option,omitempty"` - Value []byte `protobuf:"bytes,3,req,name=value" json:"value,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SocketOption) Reset() { *m = SocketOption{} } -func (m *SocketOption) String() string { return proto.CompactTextString(m) } -func (*SocketOption) ProtoMessage() {} - -func (m *SocketOption) GetLevel() SocketOption_SocketOptionLevel { - if m != nil && m.Level != nil { - return *m.Level - } - return SocketOption_SOCKET_SOL_IP -} - -func (m *SocketOption) GetOption() SocketOption_SocketOptionName { - if m != nil && m.Option != nil { - return *m.Option - } - return SocketOption_SOCKET_SO_DEBUG -} - -func (m *SocketOption) GetValue() []byte { - if m != nil { - return m.Value - } - return nil -} - -type SetSocketOptionsRequest struct { - SocketDescriptor *string `protobuf:"bytes,1,req,name=socket_descriptor" json:"socket_descriptor,omitempty"` - Options []*SocketOption `protobuf:"bytes,2,rep,name=options" json:"options,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SetSocketOptionsRequest) Reset() { *m = SetSocketOptionsRequest{} } -func (m *SetSocketOptionsRequest) String() string { return proto.CompactTextString(m) } -func (*SetSocketOptionsRequest) ProtoMessage() {} - -func (m *SetSocketOptionsRequest) GetSocketDescriptor() string { - if m != nil && m.SocketDescriptor != nil { - return *m.SocketDescriptor - } - return "" -} - -func (m *SetSocketOptionsRequest) GetOptions() []*SocketOption { - if m != nil { - return m.Options - } - return nil -} - -type SetSocketOptionsReply struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *SetSocketOptionsReply) Reset() { *m = SetSocketOptionsReply{} } -func (m *SetSocketOptionsReply) String() string { return proto.CompactTextString(m) } -func (*SetSocketOptionsReply) ProtoMessage() {} - -type GetSocketOptionsRequest struct { - SocketDescriptor *string `protobuf:"bytes,1,req,name=socket_descriptor" json:"socket_descriptor,omitempty"` - Options []*SocketOption `protobuf:"bytes,2,rep,name=options" json:"options,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetSocketOptionsRequest) Reset() { *m = GetSocketOptionsRequest{} } -func (m *GetSocketOptionsRequest) String() string { return proto.CompactTextString(m) } -func (*GetSocketOptionsRequest) ProtoMessage() {} - -func (m *GetSocketOptionsRequest) GetSocketDescriptor() string { - if m != nil && m.SocketDescriptor != nil { - return *m.SocketDescriptor - } - return "" -} - -func (m *GetSocketOptionsRequest) GetOptions() []*SocketOption { - if m != nil { - return m.Options - } - return nil -} - -type GetSocketOptionsReply struct { - Options []*SocketOption `protobuf:"bytes,2,rep,name=options" json:"options,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetSocketOptionsReply) Reset() { *m = GetSocketOptionsReply{} } -func (m *GetSocketOptionsReply) String() string { return proto.CompactTextString(m) } -func (*GetSocketOptionsReply) ProtoMessage() {} - -func (m *GetSocketOptionsReply) GetOptions() []*SocketOption { - if m != nil { - return m.Options - } - return nil -} - -type ConnectRequest struct { - SocketDescriptor *string `protobuf:"bytes,1,req,name=socket_descriptor" json:"socket_descriptor,omitempty"` - RemoteIp *AddressPort `protobuf:"bytes,2,req,name=remote_ip" json:"remote_ip,omitempty"` - TimeoutSeconds *float64 `protobuf:"fixed64,3,opt,name=timeout_seconds,def=-1" json:"timeout_seconds,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ConnectRequest) Reset() { *m = ConnectRequest{} } -func (m *ConnectRequest) String() string { return proto.CompactTextString(m) } -func (*ConnectRequest) ProtoMessage() {} - -const Default_ConnectRequest_TimeoutSeconds float64 = -1 - -func (m *ConnectRequest) GetSocketDescriptor() string { - if m != nil && m.SocketDescriptor != nil { - return *m.SocketDescriptor - } - return "" -} - -func (m *ConnectRequest) GetRemoteIp() *AddressPort { - if m != nil { - return m.RemoteIp - } - return nil -} - -func (m *ConnectRequest) GetTimeoutSeconds() float64 { - if m != nil && m.TimeoutSeconds != nil { - return *m.TimeoutSeconds - } - return Default_ConnectRequest_TimeoutSeconds -} - -type ConnectReply struct { - ProxyExternalIp *AddressPort `protobuf:"bytes,1,opt,name=proxy_external_ip" json:"proxy_external_ip,omitempty"` - XXX_extensions map[int32]proto.Extension `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ConnectReply) Reset() { *m = ConnectReply{} } -func (m *ConnectReply) String() string { return proto.CompactTextString(m) } -func (*ConnectReply) ProtoMessage() {} - -var extRange_ConnectReply = []proto.ExtensionRange{ - {1000, 536870911}, -} - -func (*ConnectReply) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_ConnectReply -} -func (m *ConnectReply) ExtensionMap() map[int32]proto.Extension { - if m.XXX_extensions == nil { - m.XXX_extensions = make(map[int32]proto.Extension) - } - return m.XXX_extensions -} - -func (m *ConnectReply) GetProxyExternalIp() *AddressPort { - if m != nil { - return m.ProxyExternalIp - } - return nil -} - -type ListenRequest struct { - SocketDescriptor *string `protobuf:"bytes,1,req,name=socket_descriptor" json:"socket_descriptor,omitempty"` - Backlog *int32 `protobuf:"varint,2,req,name=backlog" json:"backlog,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ListenRequest) Reset() { *m = ListenRequest{} } -func (m *ListenRequest) String() string { return proto.CompactTextString(m) } -func (*ListenRequest) ProtoMessage() {} - -func (m *ListenRequest) GetSocketDescriptor() string { - if m != nil && m.SocketDescriptor != nil { - return *m.SocketDescriptor - } - return "" -} - -func (m *ListenRequest) GetBacklog() int32 { - if m != nil && m.Backlog != nil { - return *m.Backlog - } - return 0 -} - -type ListenReply struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *ListenReply) Reset() { *m = ListenReply{} } -func (m *ListenReply) String() string { return proto.CompactTextString(m) } -func (*ListenReply) ProtoMessage() {} - -type AcceptRequest struct { - SocketDescriptor *string `protobuf:"bytes,1,req,name=socket_descriptor" json:"socket_descriptor,omitempty"` - TimeoutSeconds *float64 `protobuf:"fixed64,2,opt,name=timeout_seconds,def=-1" json:"timeout_seconds,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *AcceptRequest) Reset() { *m = AcceptRequest{} } -func (m *AcceptRequest) String() string { return proto.CompactTextString(m) } -func (*AcceptRequest) ProtoMessage() {} - -const Default_AcceptRequest_TimeoutSeconds float64 = -1 - -func (m *AcceptRequest) GetSocketDescriptor() string { - if m != nil && m.SocketDescriptor != nil { - return *m.SocketDescriptor - } - return "" -} - -func (m *AcceptRequest) GetTimeoutSeconds() float64 { - if m != nil && m.TimeoutSeconds != nil { - return *m.TimeoutSeconds - } - return Default_AcceptRequest_TimeoutSeconds -} - -type AcceptReply struct { - NewSocketDescriptor []byte `protobuf:"bytes,2,opt,name=new_socket_descriptor" json:"new_socket_descriptor,omitempty"` - RemoteAddress *AddressPort `protobuf:"bytes,3,opt,name=remote_address" json:"remote_address,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *AcceptReply) Reset() { *m = AcceptReply{} } -func (m *AcceptReply) String() string { return proto.CompactTextString(m) } -func (*AcceptReply) ProtoMessage() {} - -func (m *AcceptReply) GetNewSocketDescriptor() []byte { - if m != nil { - return m.NewSocketDescriptor - } - return nil -} - -func (m *AcceptReply) GetRemoteAddress() *AddressPort { - if m != nil { - return m.RemoteAddress - } - return nil -} - -type ShutDownRequest struct { - SocketDescriptor *string `protobuf:"bytes,1,req,name=socket_descriptor" json:"socket_descriptor,omitempty"` - How *ShutDownRequest_How `protobuf:"varint,2,req,name=how,enum=appengine.ShutDownRequest_How" json:"how,omitempty"` - SendOffset *int64 `protobuf:"varint,3,req,name=send_offset" json:"send_offset,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ShutDownRequest) Reset() { *m = ShutDownRequest{} } -func (m *ShutDownRequest) String() string { return proto.CompactTextString(m) } -func (*ShutDownRequest) ProtoMessage() {} - -func (m *ShutDownRequest) GetSocketDescriptor() string { - if m != nil && m.SocketDescriptor != nil { - return *m.SocketDescriptor - } - return "" -} - -func (m *ShutDownRequest) GetHow() ShutDownRequest_How { - if m != nil && m.How != nil { - return *m.How - } - return ShutDownRequest_SOCKET_SHUT_RD -} - -func (m *ShutDownRequest) GetSendOffset() int64 { - if m != nil && m.SendOffset != nil { - return *m.SendOffset - } - return 0 -} - -type ShutDownReply struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *ShutDownReply) Reset() { *m = ShutDownReply{} } -func (m *ShutDownReply) String() string { return proto.CompactTextString(m) } -func (*ShutDownReply) ProtoMessage() {} - -type CloseRequest struct { - SocketDescriptor *string `protobuf:"bytes,1,req,name=socket_descriptor" json:"socket_descriptor,omitempty"` - SendOffset *int64 `protobuf:"varint,2,opt,name=send_offset,def=-1" json:"send_offset,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CloseRequest) Reset() { *m = CloseRequest{} } -func (m *CloseRequest) String() string { return proto.CompactTextString(m) } -func (*CloseRequest) ProtoMessage() {} - -const Default_CloseRequest_SendOffset int64 = -1 - -func (m *CloseRequest) GetSocketDescriptor() string { - if m != nil && m.SocketDescriptor != nil { - return *m.SocketDescriptor - } - return "" -} - -func (m *CloseRequest) GetSendOffset() int64 { - if m != nil && m.SendOffset != nil { - return *m.SendOffset - } - return Default_CloseRequest_SendOffset -} - -type CloseReply struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *CloseReply) Reset() { *m = CloseReply{} } -func (m *CloseReply) String() string { return proto.CompactTextString(m) } -func (*CloseReply) ProtoMessage() {} - -type SendRequest struct { - SocketDescriptor *string `protobuf:"bytes,1,req,name=socket_descriptor" json:"socket_descriptor,omitempty"` - Data []byte `protobuf:"bytes,2,req,name=data" json:"data,omitempty"` - StreamOffset *int64 `protobuf:"varint,3,req,name=stream_offset" json:"stream_offset,omitempty"` - Flags *int32 `protobuf:"varint,4,opt,name=flags,def=0" json:"flags,omitempty"` - SendTo *AddressPort `protobuf:"bytes,5,opt,name=send_to" json:"send_to,omitempty"` - TimeoutSeconds *float64 `protobuf:"fixed64,6,opt,name=timeout_seconds,def=-1" json:"timeout_seconds,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SendRequest) Reset() { *m = SendRequest{} } -func (m *SendRequest) String() string { return proto.CompactTextString(m) } -func (*SendRequest) ProtoMessage() {} - -const Default_SendRequest_Flags int32 = 0 -const Default_SendRequest_TimeoutSeconds float64 = -1 - -func (m *SendRequest) GetSocketDescriptor() string { - if m != nil && m.SocketDescriptor != nil { - return *m.SocketDescriptor - } - return "" -} - -func (m *SendRequest) GetData() []byte { - if m != nil { - return m.Data - } - return nil -} - -func (m *SendRequest) GetStreamOffset() int64 { - if m != nil && m.StreamOffset != nil { - return *m.StreamOffset - } - return 0 -} - -func (m *SendRequest) GetFlags() int32 { - if m != nil && m.Flags != nil { - return *m.Flags - } - return Default_SendRequest_Flags -} - -func (m *SendRequest) GetSendTo() *AddressPort { - if m != nil { - return m.SendTo - } - return nil -} - -func (m *SendRequest) GetTimeoutSeconds() float64 { - if m != nil && m.TimeoutSeconds != nil { - return *m.TimeoutSeconds - } - return Default_SendRequest_TimeoutSeconds -} - -type SendReply struct { - DataSent *int32 `protobuf:"varint,1,opt,name=data_sent" json:"data_sent,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SendReply) Reset() { *m = SendReply{} } -func (m *SendReply) String() string { return proto.CompactTextString(m) } -func (*SendReply) ProtoMessage() {} - -func (m *SendReply) GetDataSent() int32 { - if m != nil && m.DataSent != nil { - return *m.DataSent - } - return 0 -} - -type ReceiveRequest struct { - SocketDescriptor *string `protobuf:"bytes,1,req,name=socket_descriptor" json:"socket_descriptor,omitempty"` - DataSize *int32 `protobuf:"varint,2,req,name=data_size" json:"data_size,omitempty"` - Flags *int32 `protobuf:"varint,3,opt,name=flags,def=0" json:"flags,omitempty"` - TimeoutSeconds *float64 `protobuf:"fixed64,5,opt,name=timeout_seconds,def=-1" json:"timeout_seconds,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ReceiveRequest) Reset() { *m = ReceiveRequest{} } -func (m *ReceiveRequest) String() string { return proto.CompactTextString(m) } -func (*ReceiveRequest) ProtoMessage() {} - -const Default_ReceiveRequest_Flags int32 = 0 -const Default_ReceiveRequest_TimeoutSeconds float64 = -1 - -func (m *ReceiveRequest) GetSocketDescriptor() string { - if m != nil && m.SocketDescriptor != nil { - return *m.SocketDescriptor - } - return "" -} - -func (m *ReceiveRequest) GetDataSize() int32 { - if m != nil && m.DataSize != nil { - return *m.DataSize - } - return 0 -} - -func (m *ReceiveRequest) GetFlags() int32 { - if m != nil && m.Flags != nil { - return *m.Flags - } - return Default_ReceiveRequest_Flags -} - -func (m *ReceiveRequest) GetTimeoutSeconds() float64 { - if m != nil && m.TimeoutSeconds != nil { - return *m.TimeoutSeconds - } - return Default_ReceiveRequest_TimeoutSeconds -} - -type ReceiveReply struct { - StreamOffset *int64 `protobuf:"varint,2,opt,name=stream_offset" json:"stream_offset,omitempty"` - Data []byte `protobuf:"bytes,3,opt,name=data" json:"data,omitempty"` - ReceivedFrom *AddressPort `protobuf:"bytes,4,opt,name=received_from" json:"received_from,omitempty"` - BufferSize *int32 `protobuf:"varint,5,opt,name=buffer_size" json:"buffer_size,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ReceiveReply) Reset() { *m = ReceiveReply{} } -func (m *ReceiveReply) String() string { return proto.CompactTextString(m) } -func (*ReceiveReply) ProtoMessage() {} - -func (m *ReceiveReply) GetStreamOffset() int64 { - if m != nil && m.StreamOffset != nil { - return *m.StreamOffset - } - return 0 -} - -func (m *ReceiveReply) GetData() []byte { - if m != nil { - return m.Data - } - return nil -} - -func (m *ReceiveReply) GetReceivedFrom() *AddressPort { - if m != nil { - return m.ReceivedFrom - } - return nil -} - -func (m *ReceiveReply) GetBufferSize() int32 { - if m != nil && m.BufferSize != nil { - return *m.BufferSize - } - return 0 -} - -type PollEvent struct { - SocketDescriptor *string `protobuf:"bytes,1,req,name=socket_descriptor" json:"socket_descriptor,omitempty"` - RequestedEvents *int32 `protobuf:"varint,2,req,name=requested_events" json:"requested_events,omitempty"` - ObservedEvents *int32 `protobuf:"varint,3,req,name=observed_events" json:"observed_events,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PollEvent) Reset() { *m = PollEvent{} } -func (m *PollEvent) String() string { return proto.CompactTextString(m) } -func (*PollEvent) ProtoMessage() {} - -func (m *PollEvent) GetSocketDescriptor() string { - if m != nil && m.SocketDescriptor != nil { - return *m.SocketDescriptor - } - return "" -} - -func (m *PollEvent) GetRequestedEvents() int32 { - if m != nil && m.RequestedEvents != nil { - return *m.RequestedEvents - } - return 0 -} - -func (m *PollEvent) GetObservedEvents() int32 { - if m != nil && m.ObservedEvents != nil { - return *m.ObservedEvents - } - return 0 -} - -type PollRequest struct { - Events []*PollEvent `protobuf:"bytes,1,rep,name=events" json:"events,omitempty"` - TimeoutSeconds *float64 `protobuf:"fixed64,2,opt,name=timeout_seconds,def=-1" json:"timeout_seconds,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PollRequest) Reset() { *m = PollRequest{} } -func (m *PollRequest) String() string { return proto.CompactTextString(m) } -func (*PollRequest) ProtoMessage() {} - -const Default_PollRequest_TimeoutSeconds float64 = -1 - -func (m *PollRequest) GetEvents() []*PollEvent { - if m != nil { - return m.Events - } - return nil -} - -func (m *PollRequest) GetTimeoutSeconds() float64 { - if m != nil && m.TimeoutSeconds != nil { - return *m.TimeoutSeconds - } - return Default_PollRequest_TimeoutSeconds -} - -type PollReply struct { - Events []*PollEvent `protobuf:"bytes,2,rep,name=events" json:"events,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PollReply) Reset() { *m = PollReply{} } -func (m *PollReply) String() string { return proto.CompactTextString(m) } -func (*PollReply) ProtoMessage() {} - -func (m *PollReply) GetEvents() []*PollEvent { - if m != nil { - return m.Events - } - return nil -} - -type ResolveRequest struct { - Name *string `protobuf:"bytes,1,req,name=name" json:"name,omitempty"` - AddressFamilies []CreateSocketRequest_SocketFamily `protobuf:"varint,2,rep,name=address_families,enum=appengine.CreateSocketRequest_SocketFamily" json:"address_families,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ResolveRequest) Reset() { *m = ResolveRequest{} } -func (m *ResolveRequest) String() string { return proto.CompactTextString(m) } -func (*ResolveRequest) ProtoMessage() {} - -func (m *ResolveRequest) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *ResolveRequest) GetAddressFamilies() []CreateSocketRequest_SocketFamily { - if m != nil { - return m.AddressFamilies - } - return nil -} - -type ResolveReply struct { - PackedAddress [][]byte `protobuf:"bytes,2,rep,name=packed_address" json:"packed_address,omitempty"` - CanonicalName *string `protobuf:"bytes,3,opt,name=canonical_name" json:"canonical_name,omitempty"` - Aliases []string `protobuf:"bytes,4,rep,name=aliases" json:"aliases,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ResolveReply) Reset() { *m = ResolveReply{} } -func (m *ResolveReply) String() string { return proto.CompactTextString(m) } -func (*ResolveReply) ProtoMessage() {} - -func (m *ResolveReply) GetPackedAddress() [][]byte { - if m != nil { - return m.PackedAddress - } - return nil -} - -func (m *ResolveReply) GetCanonicalName() string { - if m != nil && m.CanonicalName != nil { - return *m.CanonicalName - } - return "" -} - -func (m *ResolveReply) GetAliases() []string { - if m != nil { - return m.Aliases - } - return nil -} - -func init() { -} diff --git a/vendor/google.golang.org/appengine/socket/doc.go b/vendor/google.golang.org/appengine/socket/doc.go deleted file mode 100644 index 3de46df826b..00000000000 --- a/vendor/google.golang.org/appengine/socket/doc.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2012 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// Package socket provides outbound network sockets. -// -// This package is only required in the classic App Engine environment. -// Applications running only in App Engine "flexible environment" should -// use the standard library's net package. -package socket diff --git a/vendor/google.golang.org/appengine/socket/socket_classic.go b/vendor/google.golang.org/appengine/socket/socket_classic.go deleted file mode 100644 index 0ad50e2d36d..00000000000 --- a/vendor/google.golang.org/appengine/socket/socket_classic.go +++ /dev/null @@ -1,290 +0,0 @@ -// Copyright 2012 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// +build appengine - -package socket - -import ( - "fmt" - "io" - "net" - "strconv" - "time" - - "github.com/golang/protobuf/proto" - "golang.org/x/net/context" - "google.golang.org/appengine/internal" - - pb "google.golang.org/appengine/internal/socket" -) - -// Dial connects to the address addr on the network protocol. -// The address format is host:port, where host may be a hostname or an IP address. -// Known protocols are "tcp" and "udp". -// The returned connection satisfies net.Conn, and is valid while ctx is valid; -// if the connection is to be used after ctx becomes invalid, invoke SetContext -// with the new context. -func Dial(ctx context.Context, protocol, addr string) (*Conn, error) { - return DialTimeout(ctx, protocol, addr, 0) -} - -var ipFamilies = []pb.CreateSocketRequest_SocketFamily{ - pb.CreateSocketRequest_IPv4, - pb.CreateSocketRequest_IPv6, -} - -// DialTimeout is like Dial but takes a timeout. -// The timeout includes name resolution, if required. -func DialTimeout(ctx context.Context, protocol, addr string, timeout time.Duration) (*Conn, error) { - dialCtx := ctx // Used for dialing and name resolution, but not stored in the *Conn. - if timeout > 0 { - var cancel context.CancelFunc - dialCtx, cancel = context.WithTimeout(ctx, timeout) - defer cancel() - } - - host, portStr, err := net.SplitHostPort(addr) - if err != nil { - return nil, err - } - port, err := strconv.Atoi(portStr) - if err != nil { - return nil, fmt.Errorf("socket: bad port %q: %v", portStr, err) - } - - var prot pb.CreateSocketRequest_SocketProtocol - switch protocol { - case "tcp": - prot = pb.CreateSocketRequest_TCP - case "udp": - prot = pb.CreateSocketRequest_UDP - default: - return nil, fmt.Errorf("socket: unknown protocol %q", protocol) - } - - packedAddrs, resolved, err := resolve(dialCtx, ipFamilies, host) - if err != nil { - return nil, fmt.Errorf("socket: failed resolving %q: %v", host, err) - } - if len(packedAddrs) == 0 { - return nil, fmt.Errorf("no addresses for %q", host) - } - - packedAddr := packedAddrs[0] // use first address - fam := pb.CreateSocketRequest_IPv4 - if len(packedAddr) == net.IPv6len { - fam = pb.CreateSocketRequest_IPv6 - } - - req := &pb.CreateSocketRequest{ - Family: fam.Enum(), - Protocol: prot.Enum(), - RemoteIp: &pb.AddressPort{ - Port: proto.Int32(int32(port)), - PackedAddress: packedAddr, - }, - } - if resolved { - req.RemoteIp.HostnameHint = &host - } - res := &pb.CreateSocketReply{} - if err := internal.Call(dialCtx, "remote_socket", "CreateSocket", req, res); err != nil { - return nil, err - } - - return &Conn{ - ctx: ctx, - desc: res.GetSocketDescriptor(), - prot: prot, - local: res.ProxyExternalIp, - remote: req.RemoteIp, - }, nil -} - -// LookupIP returns the given host's IP addresses. -func LookupIP(ctx context.Context, host string) (addrs []net.IP, err error) { - packedAddrs, _, err := resolve(ctx, ipFamilies, host) - if err != nil { - return nil, fmt.Errorf("socket: failed resolving %q: %v", host, err) - } - addrs = make([]net.IP, len(packedAddrs)) - for i, pa := range packedAddrs { - addrs[i] = net.IP(pa) - } - return addrs, nil -} - -func resolve(ctx context.Context, fams []pb.CreateSocketRequest_SocketFamily, host string) ([][]byte, bool, error) { - // Check if it's an IP address. - if ip := net.ParseIP(host); ip != nil { - if ip := ip.To4(); ip != nil { - return [][]byte{ip}, false, nil - } - return [][]byte{ip}, false, nil - } - - req := &pb.ResolveRequest{ - Name: &host, - AddressFamilies: fams, - } - res := &pb.ResolveReply{} - if err := internal.Call(ctx, "remote_socket", "Resolve", req, res); err != nil { - // XXX: need to map to pb.ResolveReply_ErrorCode? - return nil, false, err - } - return res.PackedAddress, true, nil -} - -// withDeadline is like context.WithDeadline, except it ignores the zero deadline. -func withDeadline(parent context.Context, deadline time.Time) (context.Context, context.CancelFunc) { - if deadline.IsZero() { - return parent, func() {} - } - return context.WithDeadline(parent, deadline) -} - -// Conn represents a socket connection. -// It implements net.Conn. -type Conn struct { - ctx context.Context - desc string - offset int64 - - prot pb.CreateSocketRequest_SocketProtocol - local, remote *pb.AddressPort - - readDeadline, writeDeadline time.Time // optional -} - -// SetContext sets the context that is used by this Conn. -// It is usually used only when using a Conn that was created in a different context, -// such as when a connection is created during a warmup request but used while -// servicing a user request. -func (cn *Conn) SetContext(ctx context.Context) { - cn.ctx = ctx -} - -func (cn *Conn) Read(b []byte) (n int, err error) { - const maxRead = 1 << 20 - if len(b) > maxRead { - b = b[:maxRead] - } - - req := &pb.ReceiveRequest{ - SocketDescriptor: &cn.desc, - DataSize: proto.Int32(int32(len(b))), - } - res := &pb.ReceiveReply{} - if !cn.readDeadline.IsZero() { - req.TimeoutSeconds = proto.Float64(cn.readDeadline.Sub(time.Now()).Seconds()) - } - ctx, cancel := withDeadline(cn.ctx, cn.readDeadline) - defer cancel() - if err := internal.Call(ctx, "remote_socket", "Receive", req, res); err != nil { - return 0, err - } - if len(res.Data) == 0 { - return 0, io.EOF - } - if len(res.Data) > len(b) { - return 0, fmt.Errorf("socket: internal error: read too much data: %d > %d", len(res.Data), len(b)) - } - return copy(b, res.Data), nil -} - -func (cn *Conn) Write(b []byte) (n int, err error) { - const lim = 1 << 20 // max per chunk - - for n < len(b) { - chunk := b[n:] - if len(chunk) > lim { - chunk = chunk[:lim] - } - - req := &pb.SendRequest{ - SocketDescriptor: &cn.desc, - Data: chunk, - StreamOffset: &cn.offset, - } - res := &pb.SendReply{} - if !cn.writeDeadline.IsZero() { - req.TimeoutSeconds = proto.Float64(cn.writeDeadline.Sub(time.Now()).Seconds()) - } - ctx, cancel := withDeadline(cn.ctx, cn.writeDeadline) - defer cancel() - if err = internal.Call(ctx, "remote_socket", "Send", req, res); err != nil { - // assume zero bytes were sent in this RPC - break - } - n += int(res.GetDataSent()) - cn.offset += int64(res.GetDataSent()) - } - - return -} - -func (cn *Conn) Close() error { - req := &pb.CloseRequest{ - SocketDescriptor: &cn.desc, - } - res := &pb.CloseReply{} - if err := internal.Call(cn.ctx, "remote_socket", "Close", req, res); err != nil { - return err - } - cn.desc = "CLOSED" - return nil -} - -func addr(prot pb.CreateSocketRequest_SocketProtocol, ap *pb.AddressPort) net.Addr { - if ap == nil { - return nil - } - switch prot { - case pb.CreateSocketRequest_TCP: - return &net.TCPAddr{ - IP: net.IP(ap.PackedAddress), - Port: int(*ap.Port), - } - case pb.CreateSocketRequest_UDP: - return &net.UDPAddr{ - IP: net.IP(ap.PackedAddress), - Port: int(*ap.Port), - } - } - panic("unknown protocol " + prot.String()) -} - -func (cn *Conn) LocalAddr() net.Addr { return addr(cn.prot, cn.local) } -func (cn *Conn) RemoteAddr() net.Addr { return addr(cn.prot, cn.remote) } - -func (cn *Conn) SetDeadline(t time.Time) error { - cn.readDeadline = t - cn.writeDeadline = t - return nil -} - -func (cn *Conn) SetReadDeadline(t time.Time) error { - cn.readDeadline = t - return nil -} - -func (cn *Conn) SetWriteDeadline(t time.Time) error { - cn.writeDeadline = t - return nil -} - -// KeepAlive signals that the connection is still in use. -// It may be called to prevent the socket being closed due to inactivity. -func (cn *Conn) KeepAlive() error { - req := &pb.GetSocketNameRequest{ - SocketDescriptor: &cn.desc, - } - res := &pb.GetSocketNameReply{} - return internal.Call(cn.ctx, "remote_socket", "GetSocketName", req, res) -} - -func init() { - internal.RegisterErrorCodeMap("remote_socket", pb.RemoteSocketServiceError_ErrorCode_name) -} diff --git a/vendor/google.golang.org/appengine/socket/socket_vm.go b/vendor/google.golang.org/appengine/socket/socket_vm.go deleted file mode 100644 index c804169a1c0..00000000000 --- a/vendor/google.golang.org/appengine/socket/socket_vm.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// +build !appengine - -package socket - -import ( - "net" - "time" - - "golang.org/x/net/context" -) - -// Dial connects to the address addr on the network protocol. -// The address format is host:port, where host may be a hostname or an IP address. -// Known protocols are "tcp" and "udp". -// The returned connection satisfies net.Conn, and is valid while ctx is valid; -// if the connection is to be used after ctx becomes invalid, invoke SetContext -// with the new context. -func Dial(ctx context.Context, protocol, addr string) (*Conn, error) { - conn, err := net.Dial(protocol, addr) - if err != nil { - return nil, err - } - return &Conn{conn}, nil -} - -// DialTimeout is like Dial but takes a timeout. -// The timeout includes name resolution, if required. -func DialTimeout(ctx context.Context, protocol, addr string, timeout time.Duration) (*Conn, error) { - conn, err := net.DialTimeout(protocol, addr, timeout) - if err != nil { - return nil, err - } - return &Conn{conn}, nil -} - -// LookupIP returns the given host's IP addresses. -func LookupIP(ctx context.Context, host string) (addrs []net.IP, err error) { - return net.LookupIP(host) -} - -// Conn represents a socket connection. -// It implements net.Conn. -type Conn struct { - net.Conn -} - -// SetContext sets the context that is used by this Conn. -// It is usually used only when using a Conn that was created in a different context, -// such as when a connection is created during a warmup request but used while -// servicing a user request. -func (cn *Conn) SetContext(ctx context.Context) { - // This function is not required in App Engine "flexible environment". -} - -// KeepAlive signals that the connection is still in use. -// It may be called to prevent the socket being closed due to inactivity. -func (cn *Conn) KeepAlive() error { - // This function is not required in App Engine "flexible environment". - return nil -} diff --git a/vendor/google.golang.org/genproto/googleapis/api/annotations/annotations.pb.go b/vendor/google.golang.org/genproto/googleapis/api/annotations/annotations.pb.go deleted file mode 100644 index c5a54b3d7ad..00000000000 --- a/vendor/google.golang.org/genproto/googleapis/api/annotations/annotations.pb.go +++ /dev/null @@ -1,54 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/api/annotations.proto - -package annotations // import "google.golang.org/genproto/googleapis/api/annotations" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import descriptor "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 - -var E_Http = &proto.ExtensionDesc{ - ExtendedType: (*descriptor.MethodOptions)(nil), - ExtensionType: (*HttpRule)(nil), - Field: 72295728, - Name: "google.api.http", - Tag: "bytes,72295728,opt,name=http", - Filename: "google/api/annotations.proto", -} - -func init() { - proto.RegisterExtension(E_Http) -} - -func init() { - proto.RegisterFile("google/api/annotations.proto", fileDescriptor_annotations_7782c41cc734273a) -} - -var fileDescriptor_annotations_7782c41cc734273a = []byte{ - // 208 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x49, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x4f, 0x2c, 0xc8, 0xd4, 0x4f, 0xcc, 0xcb, 0xcb, 0x2f, 0x49, 0x2c, 0xc9, 0xcc, - 0xcf, 0x2b, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x82, 0xc8, 0xea, 0x25, 0x16, 0x64, - 0x4a, 0x89, 0x22, 0xa9, 0xcc, 0x28, 0x29, 0x29, 0x80, 0x28, 0x91, 0x52, 0x80, 0x0a, 0x83, 0x79, - 0x49, 0xa5, 0x69, 0xfa, 0x29, 0xa9, 0xc5, 0xc9, 0x45, 0x99, 0x05, 0x25, 0xf9, 0x45, 0x10, 0x15, - 0x56, 0xde, 0x5c, 0x2c, 0x20, 0xf5, 0x42, 0x72, 0x7a, 0x50, 0xd3, 0x60, 0x4a, 0xf5, 0x7c, 0x53, - 0x4b, 0x32, 0xf2, 0x53, 0xfc, 0x0b, 0xc0, 0x56, 0x4a, 0x6c, 0x38, 0xb5, 0x47, 0x49, 0x81, 0x51, - 0x83, 0xdb, 0x48, 0x44, 0x0f, 0x61, 0xad, 0x9e, 0x47, 0x49, 0x49, 0x41, 0x50, 0x69, 0x4e, 0x6a, - 0x10, 0xd8, 0x10, 0xa7, 0x3c, 0x2e, 0xbe, 0xe4, 0xfc, 0x5c, 0x24, 0x05, 0x4e, 0x02, 0x8e, 0x08, - 0x67, 0x07, 0x80, 0x4c, 0x0e, 0x60, 0x8c, 0x72, 0x84, 0xca, 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5, - 0xeb, 0xe5, 0x17, 0xa5, 0xeb, 0xa7, 0xa7, 0xe6, 0x81, 0xed, 0xd5, 0x87, 0x48, 0x25, 0x16, 0x64, - 0x16, 0xa3, 0x7b, 0xda, 0x1a, 0x89, 0xbd, 0x88, 0x89, 0xc5, 0xdd, 0x31, 0xc0, 0x33, 0x89, 0x0d, - 0xac, 0xc9, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0xe3, 0x29, 0x19, 0x62, 0x28, 0x01, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/genproto/googleapis/api/annotations/http.pb.go b/vendor/google.golang.org/genproto/googleapis/api/annotations/http.pb.go deleted file mode 100644 index e32d3b4f30e..00000000000 --- a/vendor/google.golang.org/genproto/googleapis/api/annotations/http.pb.go +++ /dev/null @@ -1,666 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/api/http.proto - -package annotations // import "google.golang.org/genproto/googleapis/api/annotations" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// 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 - -// Defines the HTTP configuration for an API service. It contains a list of -// [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method -// to one or more HTTP REST API methods. -type Http struct { - // A list of HTTP configuration rules that apply to individual API methods. - // - // **NOTE:** All service configuration rules follow "last one wins" order. - Rules []*HttpRule `protobuf:"bytes,1,rep,name=rules" json:"rules,omitempty"` - // When set to true, URL path parmeters will be fully URI-decoded except in - // cases of single segment matches in reserved expansion, where "%2F" will be - // left encoded. - // - // The default behavior is to not decode RFC 6570 reserved characters in multi - // segment matches. - FullyDecodeReservedExpansion bool `protobuf:"varint,2,opt,name=fully_decode_reserved_expansion,json=fullyDecodeReservedExpansion" json:"fully_decode_reserved_expansion,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Http) Reset() { *m = Http{} } -func (m *Http) String() string { return proto.CompactTextString(m) } -func (*Http) ProtoMessage() {} -func (*Http) Descriptor() ([]byte, []int) { - return fileDescriptor_http_9c97bbd8b94894d4, []int{0} -} -func (m *Http) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Http.Unmarshal(m, b) -} -func (m *Http) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Http.Marshal(b, m, deterministic) -} -func (dst *Http) XXX_Merge(src proto.Message) { - xxx_messageInfo_Http.Merge(dst, src) -} -func (m *Http) XXX_Size() int { - return xxx_messageInfo_Http.Size(m) -} -func (m *Http) XXX_DiscardUnknown() { - xxx_messageInfo_Http.DiscardUnknown(m) -} - -var xxx_messageInfo_Http proto.InternalMessageInfo - -func (m *Http) GetRules() []*HttpRule { - if m != nil { - return m.Rules - } - return nil -} - -func (m *Http) GetFullyDecodeReservedExpansion() bool { - if m != nil { - return m.FullyDecodeReservedExpansion - } - return false -} - -// `HttpRule` defines the mapping of an RPC method to one or more HTTP -// REST API methods. The mapping specifies how different portions of the RPC -// request message are mapped to URL path, URL query parameters, and -// HTTP request body. The mapping is typically specified as an -// `google.api.http` annotation on the RPC method, -// see "google/api/annotations.proto" for details. -// -// The mapping consists of a field specifying the path template and -// method kind. The path template can refer to fields in the request -// message, as in the example below which describes a REST GET -// operation on a resource collection of messages: -// -// -// service Messaging { -// rpc GetMessage(GetMessageRequest) returns (Message) { -// option (google.api.http).get = "/v1/messages/{message_id}/{sub.subfield}"; -// } -// } -// message GetMessageRequest { -// message SubMessage { -// string subfield = 1; -// } -// string message_id = 1; // mapped to the URL -// SubMessage sub = 2; // `sub.subfield` is url-mapped -// } -// message Message { -// string text = 1; // content of the resource -// } -// -// The same http annotation can alternatively be expressed inside the -// `GRPC API Configuration` YAML file. -// -// http: -// rules: -// - selector: .Messaging.GetMessage -// get: /v1/messages/{message_id}/{sub.subfield} -// -// This definition enables an automatic, bidrectional mapping of HTTP -// JSON to RPC. Example: -// -// HTTP | RPC -// -----|----- -// `GET /v1/messages/123456/foo` | `GetMessage(message_id: "123456" sub: SubMessage(subfield: "foo"))` -// -// In general, not only fields but also field paths can be referenced -// from a path pattern. Fields mapped to the path pattern cannot be -// repeated and must have a primitive (non-message) type. -// -// Any fields in the request message which are not bound by the path -// pattern automatically become (optional) HTTP query -// parameters. Assume the following definition of the request message: -// -// -// service Messaging { -// rpc GetMessage(GetMessageRequest) returns (Message) { -// option (google.api.http).get = "/v1/messages/{message_id}"; -// } -// } -// message GetMessageRequest { -// message SubMessage { -// string subfield = 1; -// } -// string message_id = 1; // mapped to the URL -// int64 revision = 2; // becomes a parameter -// SubMessage sub = 3; // `sub.subfield` becomes a parameter -// } -// -// -// This enables a HTTP JSON to RPC mapping as below: -// -// HTTP | RPC -// -----|----- -// `GET /v1/messages/123456?revision=2&sub.subfield=foo` | `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield: "foo"))` -// -// Note that fields which are mapped to HTTP parameters must have a -// primitive type or a repeated primitive type. Message types are not -// allowed. In the case of a repeated type, the parameter can be -// repeated in the URL, as in `...?param=A¶m=B`. -// -// For HTTP method kinds which allow a request body, the `body` field -// specifies the mapping. Consider a REST update method on the -// message resource collection: -// -// -// service Messaging { -// rpc UpdateMessage(UpdateMessageRequest) returns (Message) { -// option (google.api.http) = { -// put: "/v1/messages/{message_id}" -// body: "message" -// }; -// } -// } -// message UpdateMessageRequest { -// string message_id = 1; // mapped to the URL -// Message message = 2; // mapped to the body -// } -// -// -// The following HTTP JSON to RPC mapping is enabled, where the -// representation of the JSON in the request body is determined by -// protos JSON encoding: -// -// HTTP | RPC -// -----|----- -// `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" message { text: "Hi!" })` -// -// The special name `*` can be used in the body mapping to define that -// every field not bound by the path template should be mapped to the -// request body. This enables the following alternative definition of -// the update method: -// -// service Messaging { -// rpc UpdateMessage(Message) returns (Message) { -// option (google.api.http) = { -// put: "/v1/messages/{message_id}" -// body: "*" -// }; -// } -// } -// message Message { -// string message_id = 1; -// string text = 2; -// } -// -// -// The following HTTP JSON to RPC mapping is enabled: -// -// HTTP | RPC -// -----|----- -// `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" text: "Hi!")` -// -// Note that when using `*` in the body mapping, it is not possible to -// have HTTP parameters, as all fields not bound by the path end in -// the body. This makes this option more rarely used in practice of -// defining REST APIs. The common usage of `*` is in custom methods -// which don't use the URL at all for transferring data. -// -// It is possible to define multiple HTTP methods for one RPC by using -// the `additional_bindings` option. Example: -// -// service Messaging { -// rpc GetMessage(GetMessageRequest) returns (Message) { -// option (google.api.http) = { -// get: "/v1/messages/{message_id}" -// additional_bindings { -// get: "/v1/users/{user_id}/messages/{message_id}" -// } -// }; -// } -// } -// message GetMessageRequest { -// string message_id = 1; -// string user_id = 2; -// } -// -// -// This enables the following two alternative HTTP JSON to RPC -// mappings: -// -// HTTP | RPC -// -----|----- -// `GET /v1/messages/123456` | `GetMessage(message_id: "123456")` -// `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id: "123456")` -// -// # Rules for HTTP mapping -// -// The rules for mapping HTTP path, query parameters, and body fields -// to the request message are as follows: -// -// 1. The `body` field specifies either `*` or a field path, or is -// omitted. If omitted, it indicates there is no HTTP request body. -// 2. Leaf fields (recursive expansion of nested messages in the -// request) can be classified into three types: -// (a) Matched in the URL template. -// (b) Covered by body (if body is `*`, everything except (a) fields; -// else everything under the body field) -// (c) All other fields. -// 3. URL query parameters found in the HTTP request are mapped to (c) fields. -// 4. Any body sent with an HTTP request can contain only (b) fields. -// -// The syntax of the path template is as follows: -// -// Template = "/" Segments [ Verb ] ; -// Segments = Segment { "/" Segment } ; -// Segment = "*" | "**" | LITERAL | Variable ; -// Variable = "{" FieldPath [ "=" Segments ] "}" ; -// FieldPath = IDENT { "." IDENT } ; -// Verb = ":" LITERAL ; -// -// The syntax `*` matches a single path segment. The syntax `**` matches zero -// or more path segments, which must be the last part of the path except the -// `Verb`. The syntax `LITERAL` matches literal text in the path. -// -// The syntax `Variable` matches part of the URL path as specified by its -// template. A variable template must not contain other variables. If a variable -// matches a single path segment, its template may be omitted, e.g. `{var}` -// is equivalent to `{var=*}`. -// -// If a variable contains exactly one path segment, such as `"{var}"` or -// `"{var=*}"`, when such a variable is expanded into a URL path, all characters -// except `[-_.~0-9a-zA-Z]` are percent-encoded. Such variables show up in the -// Discovery Document as `{var}`. -// -// If a variable contains one or more path segments, such as `"{var=foo/*}"` -// or `"{var=**}"`, when such a variable is expanded into a URL path, all -// characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. Such variables -// show up in the Discovery Document as `{+var}`. -// -// NOTE: While the single segment variable matches the semantics of -// [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 -// Simple String Expansion, the multi segment variable **does not** match -// RFC 6570 Reserved Expansion. The reason is that the Reserved Expansion -// does not expand special characters like `?` and `#`, which would lead -// to invalid URLs. -// -// NOTE: the field paths in variables and in the `body` must not refer to -// repeated fields or map fields. -type HttpRule struct { - // Selects methods to which this rule applies. - // - // Refer to [selector][google.api.DocumentationRule.selector] for syntax details. - Selector string `protobuf:"bytes,1,opt,name=selector" json:"selector,omitempty"` - // Determines the URL pattern is matched by this rules. This pattern can be - // used with any of the {get|put|post|delete|patch} methods. A custom method - // can be defined using the 'custom' field. - // - // Types that are valid to be assigned to Pattern: - // *HttpRule_Get - // *HttpRule_Put - // *HttpRule_Post - // *HttpRule_Delete - // *HttpRule_Patch - // *HttpRule_Custom - Pattern isHttpRule_Pattern `protobuf_oneof:"pattern"` - // The name of the request field whose value is mapped to the HTTP body, or - // `*` for mapping all fields not captured by the path pattern to the HTTP - // body. NOTE: the referred field must not be a repeated field and must be - // present at the top-level of request message type. - Body string `protobuf:"bytes,7,opt,name=body" json:"body,omitempty"` - // Additional HTTP bindings for the selector. Nested bindings must - // not contain an `additional_bindings` field themselves (that is, - // the nesting may only be one level deep). - AdditionalBindings []*HttpRule `protobuf:"bytes,11,rep,name=additional_bindings,json=additionalBindings" json:"additional_bindings,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HttpRule) Reset() { *m = HttpRule{} } -func (m *HttpRule) String() string { return proto.CompactTextString(m) } -func (*HttpRule) ProtoMessage() {} -func (*HttpRule) Descriptor() ([]byte, []int) { - return fileDescriptor_http_9c97bbd8b94894d4, []int{1} -} -func (m *HttpRule) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HttpRule.Unmarshal(m, b) -} -func (m *HttpRule) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HttpRule.Marshal(b, m, deterministic) -} -func (dst *HttpRule) XXX_Merge(src proto.Message) { - xxx_messageInfo_HttpRule.Merge(dst, src) -} -func (m *HttpRule) XXX_Size() int { - return xxx_messageInfo_HttpRule.Size(m) -} -func (m *HttpRule) XXX_DiscardUnknown() { - xxx_messageInfo_HttpRule.DiscardUnknown(m) -} - -var xxx_messageInfo_HttpRule proto.InternalMessageInfo - -type isHttpRule_Pattern interface { - isHttpRule_Pattern() -} - -type HttpRule_Get struct { - Get string `protobuf:"bytes,2,opt,name=get,oneof"` -} -type HttpRule_Put struct { - Put string `protobuf:"bytes,3,opt,name=put,oneof"` -} -type HttpRule_Post struct { - Post string `protobuf:"bytes,4,opt,name=post,oneof"` -} -type HttpRule_Delete struct { - Delete string `protobuf:"bytes,5,opt,name=delete,oneof"` -} -type HttpRule_Patch struct { - Patch string `protobuf:"bytes,6,opt,name=patch,oneof"` -} -type HttpRule_Custom struct { - Custom *CustomHttpPattern `protobuf:"bytes,8,opt,name=custom,oneof"` -} - -func (*HttpRule_Get) isHttpRule_Pattern() {} -func (*HttpRule_Put) isHttpRule_Pattern() {} -func (*HttpRule_Post) isHttpRule_Pattern() {} -func (*HttpRule_Delete) isHttpRule_Pattern() {} -func (*HttpRule_Patch) isHttpRule_Pattern() {} -func (*HttpRule_Custom) isHttpRule_Pattern() {} - -func (m *HttpRule) GetPattern() isHttpRule_Pattern { - if m != nil { - return m.Pattern - } - return nil -} - -func (m *HttpRule) GetSelector() string { - if m != nil { - return m.Selector - } - return "" -} - -func (m *HttpRule) GetGet() string { - if x, ok := m.GetPattern().(*HttpRule_Get); ok { - return x.Get - } - return "" -} - -func (m *HttpRule) GetPut() string { - if x, ok := m.GetPattern().(*HttpRule_Put); ok { - return x.Put - } - return "" -} - -func (m *HttpRule) GetPost() string { - if x, ok := m.GetPattern().(*HttpRule_Post); ok { - return x.Post - } - return "" -} - -func (m *HttpRule) GetDelete() string { - if x, ok := m.GetPattern().(*HttpRule_Delete); ok { - return x.Delete - } - return "" -} - -func (m *HttpRule) GetPatch() string { - if x, ok := m.GetPattern().(*HttpRule_Patch); ok { - return x.Patch - } - return "" -} - -func (m *HttpRule) GetCustom() *CustomHttpPattern { - if x, ok := m.GetPattern().(*HttpRule_Custom); ok { - return x.Custom - } - return nil -} - -func (m *HttpRule) GetBody() string { - if m != nil { - return m.Body - } - return "" -} - -func (m *HttpRule) GetAdditionalBindings() []*HttpRule { - if m != nil { - return m.AdditionalBindings - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*HttpRule) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _HttpRule_OneofMarshaler, _HttpRule_OneofUnmarshaler, _HttpRule_OneofSizer, []interface{}{ - (*HttpRule_Get)(nil), - (*HttpRule_Put)(nil), - (*HttpRule_Post)(nil), - (*HttpRule_Delete)(nil), - (*HttpRule_Patch)(nil), - (*HttpRule_Custom)(nil), - } -} - -func _HttpRule_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*HttpRule) - // pattern - switch x := m.Pattern.(type) { - case *HttpRule_Get: - b.EncodeVarint(2<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Get) - case *HttpRule_Put: - b.EncodeVarint(3<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Put) - case *HttpRule_Post: - b.EncodeVarint(4<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Post) - case *HttpRule_Delete: - b.EncodeVarint(5<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Delete) - case *HttpRule_Patch: - b.EncodeVarint(6<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Patch) - case *HttpRule_Custom: - b.EncodeVarint(8<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Custom); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("HttpRule.Pattern has unexpected type %T", x) - } - return nil -} - -func _HttpRule_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*HttpRule) - switch tag { - case 2: // pattern.get - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Pattern = &HttpRule_Get{x} - return true, err - case 3: // pattern.put - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Pattern = &HttpRule_Put{x} - return true, err - case 4: // pattern.post - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Pattern = &HttpRule_Post{x} - return true, err - case 5: // pattern.delete - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Pattern = &HttpRule_Delete{x} - return true, err - case 6: // pattern.patch - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Pattern = &HttpRule_Patch{x} - return true, err - case 8: // pattern.custom - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(CustomHttpPattern) - err := b.DecodeMessage(msg) - m.Pattern = &HttpRule_Custom{msg} - return true, err - default: - return false, nil - } -} - -func _HttpRule_OneofSizer(msg proto.Message) (n int) { - m := msg.(*HttpRule) - // pattern - switch x := m.Pattern.(type) { - case *HttpRule_Get: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Get))) - n += len(x.Get) - case *HttpRule_Put: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Put))) - n += len(x.Put) - case *HttpRule_Post: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Post))) - n += len(x.Post) - case *HttpRule_Delete: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Delete))) - n += len(x.Delete) - case *HttpRule_Patch: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Patch))) - n += len(x.Patch) - case *HttpRule_Custom: - s := proto.Size(x.Custom) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -// A custom pattern is used for defining custom HTTP verb. -type CustomHttpPattern struct { - // The name of this custom HTTP verb. - Kind string `protobuf:"bytes,1,opt,name=kind" json:"kind,omitempty"` - // The path matched by this custom verb. - Path string `protobuf:"bytes,2,opt,name=path" json:"path,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CustomHttpPattern) Reset() { *m = CustomHttpPattern{} } -func (m *CustomHttpPattern) String() string { return proto.CompactTextString(m) } -func (*CustomHttpPattern) ProtoMessage() {} -func (*CustomHttpPattern) Descriptor() ([]byte, []int) { - return fileDescriptor_http_9c97bbd8b94894d4, []int{2} -} -func (m *CustomHttpPattern) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CustomHttpPattern.Unmarshal(m, b) -} -func (m *CustomHttpPattern) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CustomHttpPattern.Marshal(b, m, deterministic) -} -func (dst *CustomHttpPattern) XXX_Merge(src proto.Message) { - xxx_messageInfo_CustomHttpPattern.Merge(dst, src) -} -func (m *CustomHttpPattern) XXX_Size() int { - return xxx_messageInfo_CustomHttpPattern.Size(m) -} -func (m *CustomHttpPattern) XXX_DiscardUnknown() { - xxx_messageInfo_CustomHttpPattern.DiscardUnknown(m) -} - -var xxx_messageInfo_CustomHttpPattern proto.InternalMessageInfo - -func (m *CustomHttpPattern) GetKind() string { - if m != nil { - return m.Kind - } - return "" -} - -func (m *CustomHttpPattern) GetPath() string { - if m != nil { - return m.Path - } - return "" -} - -func init() { - proto.RegisterType((*Http)(nil), "google.api.Http") - proto.RegisterType((*HttpRule)(nil), "google.api.HttpRule") - proto.RegisterType((*CustomHttpPattern)(nil), "google.api.CustomHttpPattern") -} - -func init() { proto.RegisterFile("google/api/http.proto", fileDescriptor_http_9c97bbd8b94894d4) } - -var fileDescriptor_http_9c97bbd8b94894d4 = []byte{ - // 401 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0x41, 0xab, 0x13, 0x31, - 0x10, 0xc7, 0xdd, 0x76, 0xdb, 0xd7, 0x4e, 0x41, 0x30, 0x3e, 0x25, 0x88, 0x62, 0xe9, 0xa9, 0x78, - 0xd8, 0xc2, 0xf3, 0xe0, 0xe1, 0x9d, 0x5e, 0xb5, 0xf8, 0xbc, 0x95, 0x3d, 0x7a, 0x29, 0xe9, 0x66, - 0x4c, 0xa3, 0x79, 0x49, 0xd8, 0xcc, 0x8a, 0xfd, 0x3a, 0x7e, 0x07, 0xbf, 0x9b, 0x47, 0x49, 0x36, - 0xb5, 0x05, 0xc1, 0xdb, 0xfc, 0xff, 0xf3, 0xcb, 0xcc, 0x64, 0x18, 0x78, 0xa6, 0x9c, 0x53, 0x06, - 0x57, 0xc2, 0xeb, 0xd5, 0x81, 0xc8, 0x57, 0xbe, 0x75, 0xe4, 0x18, 0xf4, 0x76, 0x25, 0xbc, 0x5e, - 0x1c, 0xa1, 0xbc, 0x27, 0xf2, 0xec, 0x0d, 0x8c, 0xda, 0xce, 0x60, 0xe0, 0xc5, 0x7c, 0xb8, 0x9c, - 0xdd, 0x5c, 0x57, 0x67, 0xa6, 0x8a, 0x40, 0xdd, 0x19, 0xac, 0x7b, 0x84, 0x6d, 0xe0, 0xf5, 0x97, - 0xce, 0x98, 0xe3, 0x4e, 0x62, 0xe3, 0x24, 0xee, 0x5a, 0x0c, 0xd8, 0x7e, 0x47, 0xb9, 0xc3, 0x1f, - 0x5e, 0xd8, 0xa0, 0x9d, 0xe5, 0x83, 0x79, 0xb1, 0x9c, 0xd4, 0x2f, 0x13, 0xf6, 0x21, 0x51, 0x75, - 0x86, 0x36, 0x27, 0x66, 0xf1, 0x6b, 0x00, 0x93, 0x53, 0x69, 0xf6, 0x02, 0x26, 0x01, 0x0d, 0x36, - 0xe4, 0x5a, 0x5e, 0xcc, 0x8b, 0xe5, 0xb4, 0xfe, 0xab, 0x19, 0x83, 0xa1, 0x42, 0x4a, 0x35, 0xa7, - 0xf7, 0x8f, 0xea, 0x28, 0xa2, 0xe7, 0x3b, 0xe2, 0xc3, 0x93, 0xe7, 0x3b, 0x62, 0xd7, 0x50, 0x7a, - 0x17, 0x88, 0x97, 0xd9, 0x4c, 0x8a, 0x71, 0x18, 0x4b, 0x34, 0x48, 0xc8, 0x47, 0xd9, 0xcf, 0x9a, - 0x3d, 0x87, 0x91, 0x17, 0xd4, 0x1c, 0xf8, 0x38, 0x27, 0x7a, 0xc9, 0xde, 0xc1, 0xb8, 0xe9, 0x02, - 0xb9, 0x07, 0x3e, 0x99, 0x17, 0xcb, 0xd9, 0xcd, 0xab, 0xcb, 0x65, 0xbc, 0x4f, 0x99, 0x38, 0xf7, - 0x56, 0x10, 0x61, 0x6b, 0x63, 0xc1, 0x1e, 0x67, 0x0c, 0xca, 0xbd, 0x93, 0x47, 0x7e, 0x95, 0x3e, - 0x90, 0x62, 0xb6, 0x81, 0xa7, 0x42, 0x4a, 0x4d, 0xda, 0x59, 0x61, 0x76, 0x7b, 0x6d, 0xa5, 0xb6, - 0x2a, 0xf0, 0xd9, 0x7f, 0xd6, 0xcc, 0xce, 0x0f, 0xd6, 0x99, 0x5f, 0x4f, 0xe1, 0xca, 0xf7, 0xfd, - 0x16, 0xb7, 0xf0, 0xe4, 0x9f, 0x21, 0x62, 0xeb, 0x6f, 0xda, 0xca, 0xbc, 0xbb, 0x14, 0x47, 0xcf, - 0x0b, 0x3a, 0xf4, 0x8b, 0xab, 0x53, 0xbc, 0xfe, 0x0a, 0x8f, 0x1b, 0xf7, 0x70, 0xd1, 0x76, 0x3d, - 0x4d, 0x65, 0xe2, 0x61, 0x6c, 0x8b, 0xcf, 0x77, 0x39, 0xa1, 0x9c, 0x11, 0x56, 0x55, 0xae, 0x55, - 0x2b, 0x85, 0x36, 0x9d, 0xcd, 0xaa, 0x4f, 0x09, 0xaf, 0x43, 0x3a, 0x28, 0x61, 0xad, 0x23, 0x11, - 0xc7, 0x0c, 0xb7, 0x17, 0xf1, 0xef, 0xa2, 0xf8, 0x39, 0x28, 0x3f, 0xde, 0x6d, 0x3f, 0xed, 0xc7, - 0xe9, 0xdd, 0xdb, 0x3f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x73, 0x2c, 0xed, 0xfb, 0x87, 0x02, 0x00, - 0x00, -} diff --git a/vendor/google.golang.org/genproto/googleapis/iam/v1/iam_policy.pb.go b/vendor/google.golang.org/genproto/googleapis/iam/v1/iam_policy.pb.go deleted file mode 100644 index 0450c83f77f..00000000000 --- a/vendor/google.golang.org/genproto/googleapis/iam/v1/iam_policy.pb.go +++ /dev/null @@ -1,412 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/iam/v1/iam_policy.proto - -package iam // import "google.golang.org/genproto/googleapis/iam/v1" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import _ "google.golang.org/genproto/googleapis/api/annotations" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// 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 - -// Request message for `SetIamPolicy` method. -type SetIamPolicyRequest struct { - // REQUIRED: The resource for which the policy is being specified. - // `resource` is usually specified as a path. For example, a Project - // resource is specified as `projects/{project}`. - Resource string `protobuf:"bytes,1,opt,name=resource" json:"resource,omitempty"` - // REQUIRED: The complete policy to be applied to the `resource`. The size of - // the policy is limited to a few 10s of KB. An empty policy is a - // valid policy but certain Cloud Platform services (such as Projects) - // might reject them. - Policy *Policy `protobuf:"bytes,2,opt,name=policy" json:"policy,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SetIamPolicyRequest) Reset() { *m = SetIamPolicyRequest{} } -func (m *SetIamPolicyRequest) String() string { return proto.CompactTextString(m) } -func (*SetIamPolicyRequest) ProtoMessage() {} -func (*SetIamPolicyRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_iam_policy_511a6b0802f7199d, []int{0} -} -func (m *SetIamPolicyRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SetIamPolicyRequest.Unmarshal(m, b) -} -func (m *SetIamPolicyRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SetIamPolicyRequest.Marshal(b, m, deterministic) -} -func (dst *SetIamPolicyRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_SetIamPolicyRequest.Merge(dst, src) -} -func (m *SetIamPolicyRequest) XXX_Size() int { - return xxx_messageInfo_SetIamPolicyRequest.Size(m) -} -func (m *SetIamPolicyRequest) XXX_DiscardUnknown() { - xxx_messageInfo_SetIamPolicyRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_SetIamPolicyRequest proto.InternalMessageInfo - -func (m *SetIamPolicyRequest) GetResource() string { - if m != nil { - return m.Resource - } - return "" -} - -func (m *SetIamPolicyRequest) GetPolicy() *Policy { - if m != nil { - return m.Policy - } - return nil -} - -// Request message for `GetIamPolicy` method. -type GetIamPolicyRequest struct { - // REQUIRED: The resource for which the policy is being requested. - // `resource` is usually specified as a path. For example, a Project - // resource is specified as `projects/{project}`. - Resource string `protobuf:"bytes,1,opt,name=resource" json:"resource,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetIamPolicyRequest) Reset() { *m = GetIamPolicyRequest{} } -func (m *GetIamPolicyRequest) String() string { return proto.CompactTextString(m) } -func (*GetIamPolicyRequest) ProtoMessage() {} -func (*GetIamPolicyRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_iam_policy_511a6b0802f7199d, []int{1} -} -func (m *GetIamPolicyRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetIamPolicyRequest.Unmarshal(m, b) -} -func (m *GetIamPolicyRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetIamPolicyRequest.Marshal(b, m, deterministic) -} -func (dst *GetIamPolicyRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetIamPolicyRequest.Merge(dst, src) -} -func (m *GetIamPolicyRequest) XXX_Size() int { - return xxx_messageInfo_GetIamPolicyRequest.Size(m) -} -func (m *GetIamPolicyRequest) XXX_DiscardUnknown() { - xxx_messageInfo_GetIamPolicyRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_GetIamPolicyRequest proto.InternalMessageInfo - -func (m *GetIamPolicyRequest) GetResource() string { - if m != nil { - return m.Resource - } - return "" -} - -// Request message for `TestIamPermissions` method. -type TestIamPermissionsRequest struct { - // REQUIRED: The resource for which the policy detail is being requested. - // `resource` is usually specified as a path. For example, a Project - // resource is specified as `projects/{project}`. - Resource string `protobuf:"bytes,1,opt,name=resource" json:"resource,omitempty"` - // The set of permissions to check for the `resource`. Permissions with - // wildcards (such as '*' or 'storage.*') are not allowed. For more - // information see - // [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). - Permissions []string `protobuf:"bytes,2,rep,name=permissions" json:"permissions,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *TestIamPermissionsRequest) Reset() { *m = TestIamPermissionsRequest{} } -func (m *TestIamPermissionsRequest) String() string { return proto.CompactTextString(m) } -func (*TestIamPermissionsRequest) ProtoMessage() {} -func (*TestIamPermissionsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_iam_policy_511a6b0802f7199d, []int{2} -} -func (m *TestIamPermissionsRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TestIamPermissionsRequest.Unmarshal(m, b) -} -func (m *TestIamPermissionsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TestIamPermissionsRequest.Marshal(b, m, deterministic) -} -func (dst *TestIamPermissionsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_TestIamPermissionsRequest.Merge(dst, src) -} -func (m *TestIamPermissionsRequest) XXX_Size() int { - return xxx_messageInfo_TestIamPermissionsRequest.Size(m) -} -func (m *TestIamPermissionsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_TestIamPermissionsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_TestIamPermissionsRequest proto.InternalMessageInfo - -func (m *TestIamPermissionsRequest) GetResource() string { - if m != nil { - return m.Resource - } - return "" -} - -func (m *TestIamPermissionsRequest) GetPermissions() []string { - if m != nil { - return m.Permissions - } - return nil -} - -// Response message for `TestIamPermissions` method. -type TestIamPermissionsResponse struct { - // A subset of `TestPermissionsRequest.permissions` that the caller is - // allowed. - Permissions []string `protobuf:"bytes,1,rep,name=permissions" json:"permissions,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *TestIamPermissionsResponse) Reset() { *m = TestIamPermissionsResponse{} } -func (m *TestIamPermissionsResponse) String() string { return proto.CompactTextString(m) } -func (*TestIamPermissionsResponse) ProtoMessage() {} -func (*TestIamPermissionsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_iam_policy_511a6b0802f7199d, []int{3} -} -func (m *TestIamPermissionsResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TestIamPermissionsResponse.Unmarshal(m, b) -} -func (m *TestIamPermissionsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TestIamPermissionsResponse.Marshal(b, m, deterministic) -} -func (dst *TestIamPermissionsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TestIamPermissionsResponse.Merge(dst, src) -} -func (m *TestIamPermissionsResponse) XXX_Size() int { - return xxx_messageInfo_TestIamPermissionsResponse.Size(m) -} -func (m *TestIamPermissionsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TestIamPermissionsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TestIamPermissionsResponse proto.InternalMessageInfo - -func (m *TestIamPermissionsResponse) GetPermissions() []string { - if m != nil { - return m.Permissions - } - return nil -} - -func init() { - proto.RegisterType((*SetIamPolicyRequest)(nil), "google.iam.v1.SetIamPolicyRequest") - proto.RegisterType((*GetIamPolicyRequest)(nil), "google.iam.v1.GetIamPolicyRequest") - proto.RegisterType((*TestIamPermissionsRequest)(nil), "google.iam.v1.TestIamPermissionsRequest") - proto.RegisterType((*TestIamPermissionsResponse)(nil), "google.iam.v1.TestIamPermissionsResponse") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// IAMPolicyClient is the client API for IAMPolicy service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type IAMPolicyClient interface { - // Sets the access control policy on the specified resource. Replaces any - // existing policy. - SetIamPolicy(ctx context.Context, in *SetIamPolicyRequest, opts ...grpc.CallOption) (*Policy, error) - // Gets the access control policy for a resource. - // Returns an empty policy if the resource exists and does not have a policy - // set. - GetIamPolicy(ctx context.Context, in *GetIamPolicyRequest, opts ...grpc.CallOption) (*Policy, error) - // Returns permissions that a caller has on the specified resource. - // If the resource does not exist, this will return an empty set of - // permissions, not a NOT_FOUND error. - TestIamPermissions(ctx context.Context, in *TestIamPermissionsRequest, opts ...grpc.CallOption) (*TestIamPermissionsResponse, error) -} - -type iAMPolicyClient struct { - cc *grpc.ClientConn -} - -func NewIAMPolicyClient(cc *grpc.ClientConn) IAMPolicyClient { - return &iAMPolicyClient{cc} -} - -func (c *iAMPolicyClient) SetIamPolicy(ctx context.Context, in *SetIamPolicyRequest, opts ...grpc.CallOption) (*Policy, error) { - out := new(Policy) - err := c.cc.Invoke(ctx, "/google.iam.v1.IAMPolicy/SetIamPolicy", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *iAMPolicyClient) GetIamPolicy(ctx context.Context, in *GetIamPolicyRequest, opts ...grpc.CallOption) (*Policy, error) { - out := new(Policy) - err := c.cc.Invoke(ctx, "/google.iam.v1.IAMPolicy/GetIamPolicy", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *iAMPolicyClient) TestIamPermissions(ctx context.Context, in *TestIamPermissionsRequest, opts ...grpc.CallOption) (*TestIamPermissionsResponse, error) { - out := new(TestIamPermissionsResponse) - err := c.cc.Invoke(ctx, "/google.iam.v1.IAMPolicy/TestIamPermissions", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for IAMPolicy service - -type IAMPolicyServer interface { - // Sets the access control policy on the specified resource. Replaces any - // existing policy. - SetIamPolicy(context.Context, *SetIamPolicyRequest) (*Policy, error) - // Gets the access control policy for a resource. - // Returns an empty policy if the resource exists and does not have a policy - // set. - GetIamPolicy(context.Context, *GetIamPolicyRequest) (*Policy, error) - // Returns permissions that a caller has on the specified resource. - // If the resource does not exist, this will return an empty set of - // permissions, not a NOT_FOUND error. - TestIamPermissions(context.Context, *TestIamPermissionsRequest) (*TestIamPermissionsResponse, error) -} - -func RegisterIAMPolicyServer(s *grpc.Server, srv IAMPolicyServer) { - s.RegisterService(&_IAMPolicy_serviceDesc, srv) -} - -func _IAMPolicy_SetIamPolicy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SetIamPolicyRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IAMPolicyServer).SetIamPolicy(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.iam.v1.IAMPolicy/SetIamPolicy", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IAMPolicyServer).SetIamPolicy(ctx, req.(*SetIamPolicyRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _IAMPolicy_GetIamPolicy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetIamPolicyRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IAMPolicyServer).GetIamPolicy(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.iam.v1.IAMPolicy/GetIamPolicy", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IAMPolicyServer).GetIamPolicy(ctx, req.(*GetIamPolicyRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _IAMPolicy_TestIamPermissions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(TestIamPermissionsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IAMPolicyServer).TestIamPermissions(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.iam.v1.IAMPolicy/TestIamPermissions", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IAMPolicyServer).TestIamPermissions(ctx, req.(*TestIamPermissionsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _IAMPolicy_serviceDesc = grpc.ServiceDesc{ - ServiceName: "google.iam.v1.IAMPolicy", - HandlerType: (*IAMPolicyServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "SetIamPolicy", - Handler: _IAMPolicy_SetIamPolicy_Handler, - }, - { - MethodName: "GetIamPolicy", - Handler: _IAMPolicy_GetIamPolicy_Handler, - }, - { - MethodName: "TestIamPermissions", - Handler: _IAMPolicy_TestIamPermissions_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "google/iam/v1/iam_policy.proto", -} - -func init() { - proto.RegisterFile("google/iam/v1/iam_policy.proto", fileDescriptor_iam_policy_511a6b0802f7199d) -} - -var fileDescriptor_iam_policy_511a6b0802f7199d = []byte{ - // 411 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0xcf, 0x4c, 0xcc, 0xd5, 0x2f, 0x33, 0x04, 0x51, 0xf1, 0x05, 0xf9, 0x39, 0x99, - 0xc9, 0x95, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0xbc, 0x10, 0x79, 0xbd, 0xcc, 0xc4, 0x5c, - 0xbd, 0x32, 0x43, 0x29, 0x19, 0xa8, 0xf2, 0xc4, 0x82, 0x4c, 0xfd, 0xc4, 0xbc, 0xbc, 0xfc, 0x92, - 0xc4, 0x92, 0xcc, 0xfc, 0xbc, 0x62, 0x88, 0x62, 0x29, 0x29, 0x54, 0xc3, 0x90, 0x0d, 0x52, 0x4a, - 0xe0, 0x12, 0x0e, 0x4e, 0x2d, 0xf1, 0x4c, 0xcc, 0x0d, 0x00, 0x8b, 0x06, 0xa5, 0x16, 0x96, 0xa6, - 0x16, 0x97, 0x08, 0x49, 0x71, 0x71, 0x14, 0xa5, 0x16, 0xe7, 0x97, 0x16, 0x25, 0xa7, 0x4a, 0x30, - 0x2a, 0x30, 0x6a, 0x70, 0x06, 0xc1, 0xf9, 0x42, 0xba, 0x5c, 0x6c, 0x10, 0x23, 0x24, 0x98, 0x14, - 0x18, 0x35, 0xb8, 0x8d, 0x44, 0xf5, 0x50, 0x1c, 0xa3, 0x07, 0x35, 0x09, 0xaa, 0x48, 0xc9, 0x90, - 0x4b, 0xd8, 0x9d, 0x34, 0x1b, 0x94, 0x22, 0xb9, 0x24, 0x43, 0x52, 0x8b, 0xc1, 0x7a, 0x52, 0x8b, - 0x72, 0x33, 0x8b, 0x8b, 0x41, 0x9e, 0x21, 0xc6, 0x69, 0x0a, 0x5c, 0xdc, 0x05, 0x08, 0x1d, 0x12, - 0x4c, 0x0a, 0xcc, 0x1a, 0x9c, 0x41, 0xc8, 0x42, 0x4a, 0x76, 0x5c, 0x52, 0xd8, 0x8c, 0x2e, 0x2e, - 0xc8, 0xcf, 0x2b, 0xc6, 0xd0, 0xcf, 0x88, 0xa1, 0xdf, 0x68, 0x0a, 0x33, 0x17, 0xa7, 0xa7, 0xa3, - 0x2f, 0xc4, 0x2f, 0x42, 0x25, 0x5c, 0x3c, 0xc8, 0xa1, 0x27, 0xa4, 0x84, 0x16, 0x14, 0x58, 0x82, - 0x56, 0x0a, 0x7b, 0x70, 0x29, 0x69, 0x36, 0x5d, 0x7e, 0x32, 0x99, 0x49, 0x59, 0x49, 0x0e, 0x14, - 0x45, 0xd5, 0x30, 0x1f, 0xd9, 0x6a, 0x69, 0xd5, 0x5a, 0x15, 0x23, 0x99, 0x62, 0xc5, 0xa8, 0x05, - 0xb2, 0xd5, 0x1d, 0x9f, 0xad, 0xee, 0x54, 0xb1, 0x35, 0x1d, 0xcd, 0xd6, 0x59, 0x8c, 0x5c, 0x42, - 0x98, 0x41, 0x27, 0xa4, 0x81, 0x66, 0x30, 0xce, 0x88, 0x93, 0xd2, 0x24, 0x42, 0x25, 0x24, 0x1e, - 0x94, 0xf4, 0xc1, 0xce, 0xd2, 0x54, 0x52, 0xc1, 0x74, 0x56, 0x09, 0x86, 0x2e, 0x2b, 0x46, 0x2d, - 0xa7, 0x36, 0x46, 0x2e, 0xc1, 0xe4, 0xfc, 0x5c, 0x54, 0x1b, 0x9c, 0xf8, 0xe0, 0x1e, 0x08, 0x00, - 0x25, 0xf6, 0x00, 0xc6, 0x28, 0x03, 0xa8, 0x82, 0xf4, 0xfc, 0x9c, 0xc4, 0xbc, 0x74, 0xbd, 0xfc, - 0xa2, 0x74, 0xfd, 0xf4, 0xd4, 0x3c, 0x70, 0x56, 0xd0, 0x87, 0x48, 0x25, 0x16, 0x64, 0x16, 0x43, - 0x73, 0x8a, 0x75, 0x66, 0x62, 0xee, 0x0f, 0x46, 0xc6, 0x55, 0x4c, 0xc2, 0xee, 0x10, 0x5d, 0xce, - 0x39, 0xf9, 0xa5, 0x29, 0x7a, 0x9e, 0x89, 0xb9, 0x7a, 0x61, 0x86, 0xa7, 0x60, 0xa2, 0x31, 0x60, - 0xd1, 0x18, 0xcf, 0xc4, 0xdc, 0x98, 0x30, 0xc3, 0x24, 0x36, 0xb0, 0x59, 0xc6, 0x80, 0x00, 0x00, - 0x00, 0xff, 0xff, 0xea, 0x62, 0x8f, 0x22, 0xc1, 0x03, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/genproto/googleapis/iam/v1/policy.pb.go b/vendor/google.golang.org/genproto/googleapis/iam/v1/policy.pb.go deleted file mode 100644 index dd132dfc83a..00000000000 --- a/vendor/google.golang.org/genproto/googleapis/iam/v1/policy.pb.go +++ /dev/null @@ -1,366 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/iam/v1/policy.proto - -package iam // import "google.golang.org/genproto/googleapis/iam/v1" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import _ "google.golang.org/genproto/googleapis/api/annotations" - -// 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 type of action performed on a Binding in a policy. -type BindingDelta_Action int32 - -const ( - // Unspecified. - BindingDelta_ACTION_UNSPECIFIED BindingDelta_Action = 0 - // Addition of a Binding. - BindingDelta_ADD BindingDelta_Action = 1 - // Removal of a Binding. - BindingDelta_REMOVE BindingDelta_Action = 2 -) - -var BindingDelta_Action_name = map[int32]string{ - 0: "ACTION_UNSPECIFIED", - 1: "ADD", - 2: "REMOVE", -} -var BindingDelta_Action_value = map[string]int32{ - "ACTION_UNSPECIFIED": 0, - "ADD": 1, - "REMOVE": 2, -} - -func (x BindingDelta_Action) String() string { - return proto.EnumName(BindingDelta_Action_name, int32(x)) -} -func (BindingDelta_Action) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_policy_d61b385c3386eaea, []int{3, 0} -} - -// Defines an Identity and Access Management (IAM) policy. It is used to -// specify access control policies for Cloud Platform resources. -// -// -// A `Policy` consists of a list of `bindings`. A `Binding` binds a list of -// `members` to a `role`, where the members can be user accounts, Google groups, -// Google domains, and service accounts. A `role` is a named list of permissions -// defined by IAM. -// -// **Example** -// -// { -// "bindings": [ -// { -// "role": "roles/owner", -// "members": [ -// "user:mike@example.com", -// "group:admins@example.com", -// "domain:google.com", -// "serviceAccount:my-other-app@appspot.gserviceaccount.com", -// ] -// }, -// { -// "role": "roles/viewer", -// "members": ["user:sean@example.com"] -// } -// ] -// } -// -// For a description of IAM and its features, see the -// [IAM developer's guide](https://cloud.google.com/iam). -type Policy struct { - // Version of the `Policy`. The default version is 0. - Version int32 `protobuf:"varint,1,opt,name=version" json:"version,omitempty"` - // Associates a list of `members` to a `role`. - // Multiple `bindings` must not be specified for the same `role`. - // `bindings` with no members will result in an error. - Bindings []*Binding `protobuf:"bytes,4,rep,name=bindings" json:"bindings,omitempty"` - // `etag` is used for optimistic concurrency control as a way to help - // prevent simultaneous updates of a policy from overwriting each other. - // It is strongly suggested that systems make use of the `etag` in the - // read-modify-write cycle to perform policy updates in order to avoid race - // conditions: An `etag` is returned in the response to `getIamPolicy`, and - // systems are expected to put that etag in the request to `setIamPolicy` to - // ensure that their change will be applied to the same version of the policy. - // - // If no `etag` is provided in the call to `setIamPolicy`, then the existing - // policy is overwritten blindly. - Etag []byte `protobuf:"bytes,3,opt,name=etag,proto3" json:"etag,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Policy) Reset() { *m = Policy{} } -func (m *Policy) String() string { return proto.CompactTextString(m) } -func (*Policy) ProtoMessage() {} -func (*Policy) Descriptor() ([]byte, []int) { - return fileDescriptor_policy_d61b385c3386eaea, []int{0} -} -func (m *Policy) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Policy.Unmarshal(m, b) -} -func (m *Policy) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Policy.Marshal(b, m, deterministic) -} -func (dst *Policy) XXX_Merge(src proto.Message) { - xxx_messageInfo_Policy.Merge(dst, src) -} -func (m *Policy) XXX_Size() int { - return xxx_messageInfo_Policy.Size(m) -} -func (m *Policy) XXX_DiscardUnknown() { - xxx_messageInfo_Policy.DiscardUnknown(m) -} - -var xxx_messageInfo_Policy proto.InternalMessageInfo - -func (m *Policy) GetVersion() int32 { - if m != nil { - return m.Version - } - return 0 -} - -func (m *Policy) GetBindings() []*Binding { - if m != nil { - return m.Bindings - } - return nil -} - -func (m *Policy) GetEtag() []byte { - if m != nil { - return m.Etag - } - return nil -} - -// Associates `members` with a `role`. -type Binding struct { - // Role that is assigned to `members`. - // For example, `roles/viewer`, `roles/editor`, or `roles/owner`. - // Required - Role string `protobuf:"bytes,1,opt,name=role" json:"role,omitempty"` - // Specifies the identities requesting access for a Cloud Platform resource. - // `members` can have the following values: - // - // * `allUsers`: A special identifier that represents anyone who is - // on the internet; with or without a Google account. - // - // * `allAuthenticatedUsers`: A special identifier that represents anyone - // who is authenticated with a Google account or a service account. - // - // * `user:{emailid}`: An email address that represents a specific Google - // account. For example, `alice@gmail.com` or `joe@example.com`. - // - // - // * `serviceAccount:{emailid}`: An email address that represents a service - // account. For example, `my-other-app@appspot.gserviceaccount.com`. - // - // * `group:{emailid}`: An email address that represents a Google group. - // For example, `admins@example.com`. - // - // * `domain:{domain}`: A Google Apps domain name that represents all the - // users of that domain. For example, `google.com` or `example.com`. - // - // - Members []string `protobuf:"bytes,2,rep,name=members" json:"members,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Binding) Reset() { *m = Binding{} } -func (m *Binding) String() string { return proto.CompactTextString(m) } -func (*Binding) ProtoMessage() {} -func (*Binding) Descriptor() ([]byte, []int) { - return fileDescriptor_policy_d61b385c3386eaea, []int{1} -} -func (m *Binding) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Binding.Unmarshal(m, b) -} -func (m *Binding) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Binding.Marshal(b, m, deterministic) -} -func (dst *Binding) XXX_Merge(src proto.Message) { - xxx_messageInfo_Binding.Merge(dst, src) -} -func (m *Binding) XXX_Size() int { - return xxx_messageInfo_Binding.Size(m) -} -func (m *Binding) XXX_DiscardUnknown() { - xxx_messageInfo_Binding.DiscardUnknown(m) -} - -var xxx_messageInfo_Binding proto.InternalMessageInfo - -func (m *Binding) GetRole() string { - if m != nil { - return m.Role - } - return "" -} - -func (m *Binding) GetMembers() []string { - if m != nil { - return m.Members - } - return nil -} - -// The difference delta between two policies. -type PolicyDelta struct { - // The delta for Bindings between two policies. - BindingDeltas []*BindingDelta `protobuf:"bytes,1,rep,name=binding_deltas,json=bindingDeltas" json:"binding_deltas,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PolicyDelta) Reset() { *m = PolicyDelta{} } -func (m *PolicyDelta) String() string { return proto.CompactTextString(m) } -func (*PolicyDelta) ProtoMessage() {} -func (*PolicyDelta) Descriptor() ([]byte, []int) { - return fileDescriptor_policy_d61b385c3386eaea, []int{2} -} -func (m *PolicyDelta) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PolicyDelta.Unmarshal(m, b) -} -func (m *PolicyDelta) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PolicyDelta.Marshal(b, m, deterministic) -} -func (dst *PolicyDelta) XXX_Merge(src proto.Message) { - xxx_messageInfo_PolicyDelta.Merge(dst, src) -} -func (m *PolicyDelta) XXX_Size() int { - return xxx_messageInfo_PolicyDelta.Size(m) -} -func (m *PolicyDelta) XXX_DiscardUnknown() { - xxx_messageInfo_PolicyDelta.DiscardUnknown(m) -} - -var xxx_messageInfo_PolicyDelta proto.InternalMessageInfo - -func (m *PolicyDelta) GetBindingDeltas() []*BindingDelta { - if m != nil { - return m.BindingDeltas - } - return nil -} - -// One delta entry for Binding. Each individual change (only one member in each -// entry) to a binding will be a separate entry. -type BindingDelta struct { - // The action that was performed on a Binding. - // Required - Action BindingDelta_Action `protobuf:"varint,1,opt,name=action,enum=google.iam.v1.BindingDelta_Action" json:"action,omitempty"` - // Role that is assigned to `members`. - // For example, `roles/viewer`, `roles/editor`, or `roles/owner`. - // Required - Role string `protobuf:"bytes,2,opt,name=role" json:"role,omitempty"` - // A single identity requesting access for a Cloud Platform resource. - // Follows the same format of Binding.members. - // Required - Member string `protobuf:"bytes,3,opt,name=member" json:"member,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *BindingDelta) Reset() { *m = BindingDelta{} } -func (m *BindingDelta) String() string { return proto.CompactTextString(m) } -func (*BindingDelta) ProtoMessage() {} -func (*BindingDelta) Descriptor() ([]byte, []int) { - return fileDescriptor_policy_d61b385c3386eaea, []int{3} -} -func (m *BindingDelta) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_BindingDelta.Unmarshal(m, b) -} -func (m *BindingDelta) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_BindingDelta.Marshal(b, m, deterministic) -} -func (dst *BindingDelta) XXX_Merge(src proto.Message) { - xxx_messageInfo_BindingDelta.Merge(dst, src) -} -func (m *BindingDelta) XXX_Size() int { - return xxx_messageInfo_BindingDelta.Size(m) -} -func (m *BindingDelta) XXX_DiscardUnknown() { - xxx_messageInfo_BindingDelta.DiscardUnknown(m) -} - -var xxx_messageInfo_BindingDelta proto.InternalMessageInfo - -func (m *BindingDelta) GetAction() BindingDelta_Action { - if m != nil { - return m.Action - } - return BindingDelta_ACTION_UNSPECIFIED -} - -func (m *BindingDelta) GetRole() string { - if m != nil { - return m.Role - } - return "" -} - -func (m *BindingDelta) GetMember() string { - if m != nil { - return m.Member - } - return "" -} - -func init() { - proto.RegisterType((*Policy)(nil), "google.iam.v1.Policy") - proto.RegisterType((*Binding)(nil), "google.iam.v1.Binding") - proto.RegisterType((*PolicyDelta)(nil), "google.iam.v1.PolicyDelta") - proto.RegisterType((*BindingDelta)(nil), "google.iam.v1.BindingDelta") - proto.RegisterEnum("google.iam.v1.BindingDelta_Action", BindingDelta_Action_name, BindingDelta_Action_value) -} - -func init() { proto.RegisterFile("google/iam/v1/policy.proto", fileDescriptor_policy_d61b385c3386eaea) } - -var fileDescriptor_policy_d61b385c3386eaea = []byte{ - // 403 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x52, 0x4d, 0xab, 0x13, 0x31, - 0x14, 0x35, 0xed, 0x73, 0x6a, 0xef, 0xfb, 0xa0, 0x46, 0x28, 0xc3, 0xd3, 0x45, 0x99, 0x55, 0x57, - 0x19, 0x5b, 0x11, 0x41, 0x57, 0xfd, 0x18, 0x65, 0x16, 0xbe, 0x37, 0x46, 0xed, 0x42, 0x0a, 0x8f, - 0x4c, 0x1b, 0x42, 0x64, 0x92, 0x0c, 0x33, 0x63, 0xc1, 0xb5, 0xff, 0x46, 0xf0, 0x8f, 0xf8, 0x8b, - 0x5c, 0xca, 0x24, 0x99, 0x47, 0x0b, 0xe2, 0x2e, 0xe7, 0x9e, 0x73, 0x72, 0xcf, 0xcd, 0x0d, 0x5c, - 0x0b, 0x63, 0x44, 0xc1, 0x63, 0xc9, 0x54, 0x7c, 0x98, 0xc5, 0xa5, 0x29, 0xe4, 0xee, 0x3b, 0x29, - 0x2b, 0xd3, 0x18, 0x7c, 0xe9, 0x38, 0x22, 0x99, 0x22, 0x87, 0xd9, 0xf5, 0x33, 0x2f, 0x65, 0xa5, - 0x8c, 0x99, 0xd6, 0xa6, 0x61, 0x8d, 0x34, 0xba, 0x76, 0xe2, 0xe8, 0x2b, 0x04, 0x99, 0x35, 0xe3, - 0x10, 0x06, 0x07, 0x5e, 0xd5, 0xd2, 0xe8, 0x10, 0x4d, 0xd0, 0xf4, 0x21, 0xed, 0x20, 0x9e, 0xc3, - 0xa3, 0x5c, 0xea, 0xbd, 0xd4, 0xa2, 0x0e, 0xcf, 0x26, 0xfd, 0xe9, 0xf9, 0x7c, 0x4c, 0x4e, 0x7a, - 0x90, 0xa5, 0xa3, 0xe9, 0xbd, 0x0e, 0x63, 0x38, 0xe3, 0x0d, 0x13, 0x61, 0x7f, 0x82, 0xa6, 0x17, - 0xd4, 0x9e, 0xa3, 0x57, 0x30, 0xf0, 0xc2, 0x96, 0xae, 0x4c, 0xc1, 0x6d, 0xa7, 0x21, 0xb5, 0xe7, - 0x36, 0x80, 0xe2, 0x2a, 0xe7, 0x55, 0x1d, 0xf6, 0x26, 0xfd, 0xe9, 0x90, 0x76, 0x30, 0xfa, 0x00, - 0xe7, 0x2e, 0xe4, 0x9a, 0x17, 0x0d, 0xc3, 0x4b, 0xb8, 0xf2, 0x7d, 0xee, 0xf6, 0x6d, 0xa1, 0x0e, - 0x91, 0x4d, 0xf5, 0xf4, 0xdf, 0xa9, 0xac, 0x89, 0x5e, 0xe6, 0x47, 0xa8, 0x8e, 0x7e, 0x21, 0xb8, - 0x38, 0xe6, 0xf1, 0x6b, 0x08, 0xd8, 0xae, 0xe9, 0xa6, 0xbf, 0x9a, 0x47, 0xff, 0xb9, 0x8c, 0x2c, - 0xac, 0x92, 0x7a, 0xc7, 0xfd, 0x34, 0xbd, 0xa3, 0x69, 0xc6, 0x10, 0xb8, 0xf8, 0xf6, 0x09, 0x86, - 0xd4, 0xa3, 0xe8, 0x25, 0x04, 0xce, 0x8d, 0xc7, 0x80, 0x17, 0xab, 0x4f, 0xe9, 0xed, 0xcd, 0xdd, - 0xe7, 0x9b, 0x8f, 0x59, 0xb2, 0x4a, 0xdf, 0xa6, 0xc9, 0x7a, 0xf4, 0x00, 0x0f, 0xa0, 0xbf, 0x58, - 0xaf, 0x47, 0x08, 0x03, 0x04, 0x34, 0x79, 0x7f, 0xbb, 0x49, 0x46, 0xbd, 0xe5, 0x0f, 0x04, 0x8f, - 0x77, 0x46, 0x9d, 0x86, 0x5a, 0xfa, 0x67, 0xc9, 0xda, 0x55, 0x66, 0xe8, 0xcb, 0x73, 0xcf, 0x0a, - 0x53, 0x30, 0x2d, 0x88, 0xa9, 0x44, 0x2c, 0xb8, 0xb6, 0x8b, 0x8e, 0x1d, 0xc5, 0x4a, 0x59, 0xfb, - 0x4f, 0xf3, 0x46, 0x32, 0xf5, 0x07, 0xa1, 0x9f, 0xbd, 0x27, 0xef, 0x9c, 0x6b, 0x55, 0x98, 0x6f, - 0x7b, 0x92, 0x32, 0x45, 0x36, 0xb3, 0xdf, 0x5d, 0x75, 0x6b, 0xab, 0xdb, 0x94, 0xa9, 0xed, 0x66, - 0x96, 0x07, 0xf6, 0xae, 0x17, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0xfc, 0x18, 0xca, 0xaa, 0x7f, - 0x02, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/genproto/googleapis/pubsub/v1/pubsub.pb.go b/vendor/google.golang.org/genproto/googleapis/pubsub/v1/pubsub.pb.go deleted file mode 100644 index 96690c7f417..00000000000 --- a/vendor/google.golang.org/genproto/googleapis/pubsub/v1/pubsub.pb.go +++ /dev/null @@ -1,3239 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/pubsub/v1/pubsub.proto - -package pubsub // import "google.golang.org/genproto/googleapis/pubsub/v1" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import duration "github.com/golang/protobuf/ptypes/duration" -import empty "github.com/golang/protobuf/ptypes/empty" -import timestamp "github.com/golang/protobuf/ptypes/timestamp" -import _ "google.golang.org/genproto/googleapis/api/annotations" -import field_mask "google.golang.org/genproto/protobuf/field_mask" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// 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 - -// A topic resource. -type Topic struct { - // The name of the topic. It must have the format - // `"projects/{project}/topics/{topic}"`. `{topic}` must start with a letter, - // and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), - // underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent - // signs (`%`). It must be between 3 and 255 characters in length, and it - // must not start with `"goog"`. - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - // User labels. - Labels map[string]string `protobuf:"bytes,2,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Topic) Reset() { *m = Topic{} } -func (m *Topic) String() string { return proto.CompactTextString(m) } -func (*Topic) ProtoMessage() {} -func (*Topic) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{0} -} -func (m *Topic) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Topic.Unmarshal(m, b) -} -func (m *Topic) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Topic.Marshal(b, m, deterministic) -} -func (dst *Topic) XXX_Merge(src proto.Message) { - xxx_messageInfo_Topic.Merge(dst, src) -} -func (m *Topic) XXX_Size() int { - return xxx_messageInfo_Topic.Size(m) -} -func (m *Topic) XXX_DiscardUnknown() { - xxx_messageInfo_Topic.DiscardUnknown(m) -} - -var xxx_messageInfo_Topic proto.InternalMessageInfo - -func (m *Topic) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Topic) GetLabels() map[string]string { - if m != nil { - return m.Labels - } - return nil -} - -// A message data and its attributes. The message payload must not be empty; -// it must contain either a non-empty data field, or at least one attribute. -type PubsubMessage struct { - // The message payload. - Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` - // Optional attributes for this message. - Attributes map[string]string `protobuf:"bytes,2,rep,name=attributes" json:"attributes,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - // ID of this message, assigned by the server when the message is published. - // Guaranteed to be unique within the topic. This value may be read by a - // subscriber that receives a `PubsubMessage` via a `Pull` call or a push - // delivery. It must not be populated by the publisher in a `Publish` call. - MessageId string `protobuf:"bytes,3,opt,name=message_id,json=messageId" json:"message_id,omitempty"` - // The time at which the message was published, populated by the server when - // it receives the `Publish` call. It must not be populated by the - // publisher in a `Publish` call. - PublishTime *timestamp.Timestamp `protobuf:"bytes,4,opt,name=publish_time,json=publishTime" json:"publish_time,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PubsubMessage) Reset() { *m = PubsubMessage{} } -func (m *PubsubMessage) String() string { return proto.CompactTextString(m) } -func (*PubsubMessage) ProtoMessage() {} -func (*PubsubMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{1} -} -func (m *PubsubMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PubsubMessage.Unmarshal(m, b) -} -func (m *PubsubMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PubsubMessage.Marshal(b, m, deterministic) -} -func (dst *PubsubMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_PubsubMessage.Merge(dst, src) -} -func (m *PubsubMessage) XXX_Size() int { - return xxx_messageInfo_PubsubMessage.Size(m) -} -func (m *PubsubMessage) XXX_DiscardUnknown() { - xxx_messageInfo_PubsubMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_PubsubMessage proto.InternalMessageInfo - -func (m *PubsubMessage) GetData() []byte { - if m != nil { - return m.Data - } - return nil -} - -func (m *PubsubMessage) GetAttributes() map[string]string { - if m != nil { - return m.Attributes - } - return nil -} - -func (m *PubsubMessage) GetMessageId() string { - if m != nil { - return m.MessageId - } - return "" -} - -func (m *PubsubMessage) GetPublishTime() *timestamp.Timestamp { - if m != nil { - return m.PublishTime - } - return nil -} - -// Request for the GetTopic method. -type GetTopicRequest struct { - // The name of the topic to get. - // Format is `projects/{project}/topics/{topic}`. - Topic string `protobuf:"bytes,1,opt,name=topic" json:"topic,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetTopicRequest) Reset() { *m = GetTopicRequest{} } -func (m *GetTopicRequest) String() string { return proto.CompactTextString(m) } -func (*GetTopicRequest) ProtoMessage() {} -func (*GetTopicRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{2} -} -func (m *GetTopicRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetTopicRequest.Unmarshal(m, b) -} -func (m *GetTopicRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetTopicRequest.Marshal(b, m, deterministic) -} -func (dst *GetTopicRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetTopicRequest.Merge(dst, src) -} -func (m *GetTopicRequest) XXX_Size() int { - return xxx_messageInfo_GetTopicRequest.Size(m) -} -func (m *GetTopicRequest) XXX_DiscardUnknown() { - xxx_messageInfo_GetTopicRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_GetTopicRequest proto.InternalMessageInfo - -func (m *GetTopicRequest) GetTopic() string { - if m != nil { - return m.Topic - } - return "" -} - -// Request for the UpdateTopic method. -type UpdateTopicRequest struct { - // The topic to update. - Topic *Topic `protobuf:"bytes,1,opt,name=topic" json:"topic,omitempty"` - // Indicates which fields in the provided topic to update. - // Must be specified and non-empty. - UpdateMask *field_mask.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask" json:"update_mask,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UpdateTopicRequest) Reset() { *m = UpdateTopicRequest{} } -func (m *UpdateTopicRequest) String() string { return proto.CompactTextString(m) } -func (*UpdateTopicRequest) ProtoMessage() {} -func (*UpdateTopicRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{3} -} -func (m *UpdateTopicRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UpdateTopicRequest.Unmarshal(m, b) -} -func (m *UpdateTopicRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UpdateTopicRequest.Marshal(b, m, deterministic) -} -func (dst *UpdateTopicRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_UpdateTopicRequest.Merge(dst, src) -} -func (m *UpdateTopicRequest) XXX_Size() int { - return xxx_messageInfo_UpdateTopicRequest.Size(m) -} -func (m *UpdateTopicRequest) XXX_DiscardUnknown() { - xxx_messageInfo_UpdateTopicRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_UpdateTopicRequest proto.InternalMessageInfo - -func (m *UpdateTopicRequest) GetTopic() *Topic { - if m != nil { - return m.Topic - } - return nil -} - -func (m *UpdateTopicRequest) GetUpdateMask() *field_mask.FieldMask { - if m != nil { - return m.UpdateMask - } - return nil -} - -// Request for the Publish method. -type PublishRequest struct { - // The messages in the request will be published on this topic. - // Format is `projects/{project}/topics/{topic}`. - Topic string `protobuf:"bytes,1,opt,name=topic" json:"topic,omitempty"` - // The messages to publish. - Messages []*PubsubMessage `protobuf:"bytes,2,rep,name=messages" json:"messages,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PublishRequest) Reset() { *m = PublishRequest{} } -func (m *PublishRequest) String() string { return proto.CompactTextString(m) } -func (*PublishRequest) ProtoMessage() {} -func (*PublishRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{4} -} -func (m *PublishRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PublishRequest.Unmarshal(m, b) -} -func (m *PublishRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PublishRequest.Marshal(b, m, deterministic) -} -func (dst *PublishRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_PublishRequest.Merge(dst, src) -} -func (m *PublishRequest) XXX_Size() int { - return xxx_messageInfo_PublishRequest.Size(m) -} -func (m *PublishRequest) XXX_DiscardUnknown() { - xxx_messageInfo_PublishRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_PublishRequest proto.InternalMessageInfo - -func (m *PublishRequest) GetTopic() string { - if m != nil { - return m.Topic - } - return "" -} - -func (m *PublishRequest) GetMessages() []*PubsubMessage { - if m != nil { - return m.Messages - } - return nil -} - -// Response for the `Publish` method. -type PublishResponse struct { - // The server-assigned ID of each published message, in the same order as - // the messages in the request. IDs are guaranteed to be unique within - // the topic. - MessageIds []string `protobuf:"bytes,1,rep,name=message_ids,json=messageIds" json:"message_ids,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PublishResponse) Reset() { *m = PublishResponse{} } -func (m *PublishResponse) String() string { return proto.CompactTextString(m) } -func (*PublishResponse) ProtoMessage() {} -func (*PublishResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{5} -} -func (m *PublishResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PublishResponse.Unmarshal(m, b) -} -func (m *PublishResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PublishResponse.Marshal(b, m, deterministic) -} -func (dst *PublishResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_PublishResponse.Merge(dst, src) -} -func (m *PublishResponse) XXX_Size() int { - return xxx_messageInfo_PublishResponse.Size(m) -} -func (m *PublishResponse) XXX_DiscardUnknown() { - xxx_messageInfo_PublishResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_PublishResponse proto.InternalMessageInfo - -func (m *PublishResponse) GetMessageIds() []string { - if m != nil { - return m.MessageIds - } - return nil -} - -// Request for the `ListTopics` method. -type ListTopicsRequest struct { - // The name of the cloud project that topics belong to. - // Format is `projects/{project}`. - Project string `protobuf:"bytes,1,opt,name=project" json:"project,omitempty"` - // Maximum number of topics to return. - PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize" json:"page_size,omitempty"` - // The value returned by the last `ListTopicsResponse`; indicates that this is - // a continuation of a prior `ListTopics` call, and that the system should - // return the next page of data. - PageToken string `protobuf:"bytes,3,opt,name=page_token,json=pageToken" json:"page_token,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListTopicsRequest) Reset() { *m = ListTopicsRequest{} } -func (m *ListTopicsRequest) String() string { return proto.CompactTextString(m) } -func (*ListTopicsRequest) ProtoMessage() {} -func (*ListTopicsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{6} -} -func (m *ListTopicsRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListTopicsRequest.Unmarshal(m, b) -} -func (m *ListTopicsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListTopicsRequest.Marshal(b, m, deterministic) -} -func (dst *ListTopicsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListTopicsRequest.Merge(dst, src) -} -func (m *ListTopicsRequest) XXX_Size() int { - return xxx_messageInfo_ListTopicsRequest.Size(m) -} -func (m *ListTopicsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ListTopicsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ListTopicsRequest proto.InternalMessageInfo - -func (m *ListTopicsRequest) GetProject() string { - if m != nil { - return m.Project - } - return "" -} - -func (m *ListTopicsRequest) GetPageSize() int32 { - if m != nil { - return m.PageSize - } - return 0 -} - -func (m *ListTopicsRequest) GetPageToken() string { - if m != nil { - return m.PageToken - } - return "" -} - -// Response for the `ListTopics` method. -type ListTopicsResponse struct { - // The resulting topics. - Topics []*Topic `protobuf:"bytes,1,rep,name=topics" json:"topics,omitempty"` - // If not empty, indicates that there may be more topics that match the - // request; this value should be passed in a new `ListTopicsRequest`. - NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken" json:"next_page_token,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListTopicsResponse) Reset() { *m = ListTopicsResponse{} } -func (m *ListTopicsResponse) String() string { return proto.CompactTextString(m) } -func (*ListTopicsResponse) ProtoMessage() {} -func (*ListTopicsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{7} -} -func (m *ListTopicsResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListTopicsResponse.Unmarshal(m, b) -} -func (m *ListTopicsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListTopicsResponse.Marshal(b, m, deterministic) -} -func (dst *ListTopicsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListTopicsResponse.Merge(dst, src) -} -func (m *ListTopicsResponse) XXX_Size() int { - return xxx_messageInfo_ListTopicsResponse.Size(m) -} -func (m *ListTopicsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ListTopicsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ListTopicsResponse proto.InternalMessageInfo - -func (m *ListTopicsResponse) GetTopics() []*Topic { - if m != nil { - return m.Topics - } - return nil -} - -func (m *ListTopicsResponse) GetNextPageToken() string { - if m != nil { - return m.NextPageToken - } - return "" -} - -// Request for the `ListTopicSubscriptions` method. -type ListTopicSubscriptionsRequest struct { - // The name of the topic that subscriptions are attached to. - // Format is `projects/{project}/topics/{topic}`. - Topic string `protobuf:"bytes,1,opt,name=topic" json:"topic,omitempty"` - // Maximum number of subscription names to return. - PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize" json:"page_size,omitempty"` - // The value returned by the last `ListTopicSubscriptionsResponse`; indicates - // that this is a continuation of a prior `ListTopicSubscriptions` call, and - // that the system should return the next page of data. - PageToken string `protobuf:"bytes,3,opt,name=page_token,json=pageToken" json:"page_token,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListTopicSubscriptionsRequest) Reset() { *m = ListTopicSubscriptionsRequest{} } -func (m *ListTopicSubscriptionsRequest) String() string { return proto.CompactTextString(m) } -func (*ListTopicSubscriptionsRequest) ProtoMessage() {} -func (*ListTopicSubscriptionsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{8} -} -func (m *ListTopicSubscriptionsRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListTopicSubscriptionsRequest.Unmarshal(m, b) -} -func (m *ListTopicSubscriptionsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListTopicSubscriptionsRequest.Marshal(b, m, deterministic) -} -func (dst *ListTopicSubscriptionsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListTopicSubscriptionsRequest.Merge(dst, src) -} -func (m *ListTopicSubscriptionsRequest) XXX_Size() int { - return xxx_messageInfo_ListTopicSubscriptionsRequest.Size(m) -} -func (m *ListTopicSubscriptionsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ListTopicSubscriptionsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ListTopicSubscriptionsRequest proto.InternalMessageInfo - -func (m *ListTopicSubscriptionsRequest) GetTopic() string { - if m != nil { - return m.Topic - } - return "" -} - -func (m *ListTopicSubscriptionsRequest) GetPageSize() int32 { - if m != nil { - return m.PageSize - } - return 0 -} - -func (m *ListTopicSubscriptionsRequest) GetPageToken() string { - if m != nil { - return m.PageToken - } - return "" -} - -// Response for the `ListTopicSubscriptions` method. -type ListTopicSubscriptionsResponse struct { - // The names of the subscriptions that match the request. - Subscriptions []string `protobuf:"bytes,1,rep,name=subscriptions" json:"subscriptions,omitempty"` - // If not empty, indicates that there may be more subscriptions that match - // the request; this value should be passed in a new - // `ListTopicSubscriptionsRequest` to get more subscriptions. - NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken" json:"next_page_token,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListTopicSubscriptionsResponse) Reset() { *m = ListTopicSubscriptionsResponse{} } -func (m *ListTopicSubscriptionsResponse) String() string { return proto.CompactTextString(m) } -func (*ListTopicSubscriptionsResponse) ProtoMessage() {} -func (*ListTopicSubscriptionsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{9} -} -func (m *ListTopicSubscriptionsResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListTopicSubscriptionsResponse.Unmarshal(m, b) -} -func (m *ListTopicSubscriptionsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListTopicSubscriptionsResponse.Marshal(b, m, deterministic) -} -func (dst *ListTopicSubscriptionsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListTopicSubscriptionsResponse.Merge(dst, src) -} -func (m *ListTopicSubscriptionsResponse) XXX_Size() int { - return xxx_messageInfo_ListTopicSubscriptionsResponse.Size(m) -} -func (m *ListTopicSubscriptionsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ListTopicSubscriptionsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ListTopicSubscriptionsResponse proto.InternalMessageInfo - -func (m *ListTopicSubscriptionsResponse) GetSubscriptions() []string { - if m != nil { - return m.Subscriptions - } - return nil -} - -func (m *ListTopicSubscriptionsResponse) GetNextPageToken() string { - if m != nil { - return m.NextPageToken - } - return "" -} - -// Request for the `DeleteTopic` method. -type DeleteTopicRequest struct { - // Name of the topic to delete. - // Format is `projects/{project}/topics/{topic}`. - Topic string `protobuf:"bytes,1,opt,name=topic" json:"topic,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DeleteTopicRequest) Reset() { *m = DeleteTopicRequest{} } -func (m *DeleteTopicRequest) String() string { return proto.CompactTextString(m) } -func (*DeleteTopicRequest) ProtoMessage() {} -func (*DeleteTopicRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{10} -} -func (m *DeleteTopicRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DeleteTopicRequest.Unmarshal(m, b) -} -func (m *DeleteTopicRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DeleteTopicRequest.Marshal(b, m, deterministic) -} -func (dst *DeleteTopicRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_DeleteTopicRequest.Merge(dst, src) -} -func (m *DeleteTopicRequest) XXX_Size() int { - return xxx_messageInfo_DeleteTopicRequest.Size(m) -} -func (m *DeleteTopicRequest) XXX_DiscardUnknown() { - xxx_messageInfo_DeleteTopicRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_DeleteTopicRequest proto.InternalMessageInfo - -func (m *DeleteTopicRequest) GetTopic() string { - if m != nil { - return m.Topic - } - return "" -} - -// A subscription resource. -type Subscription struct { - // The name of the subscription. It must have the format - // `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must - // start with a letter, and contain only letters (`[A-Za-z]`), numbers - // (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), - // plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters - // in length, and it must not start with `"goog"`. - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - // The name of the topic from which this subscription is receiving messages. - // Format is `projects/{project}/topics/{topic}`. - // The value of this field will be `_deleted-topic_` if the topic has been - // deleted. - Topic string `protobuf:"bytes,2,opt,name=topic" json:"topic,omitempty"` - // If push delivery is used with this subscription, this field is - // used to configure it. An empty `pushConfig` signifies that the subscriber - // will pull and ack messages using API methods. - PushConfig *PushConfig `protobuf:"bytes,4,opt,name=push_config,json=pushConfig" json:"push_config,omitempty"` - // This value is the maximum time after a subscriber receives a message - // before the subscriber should acknowledge the message. After message - // delivery but before the ack deadline expires and before the message is - // acknowledged, it is an outstanding message and will not be delivered - // again during that time (on a best-effort basis). - // - // For pull subscriptions, this value is used as the initial value for the ack - // deadline. To override this value for a given message, call - // `ModifyAckDeadline` with the corresponding `ack_id` if using - // pull. - // The minimum custom deadline you can specify is 10 seconds. - // The maximum custom deadline you can specify is 600 seconds (10 minutes). - // If this parameter is 0, a default value of 10 seconds is used. - // - // For push delivery, this value is also used to set the request timeout for - // the call to the push endpoint. - // - // If the subscriber never acknowledges the message, the Pub/Sub - // system will eventually redeliver the message. - AckDeadlineSeconds int32 `protobuf:"varint,5,opt,name=ack_deadline_seconds,json=ackDeadlineSeconds" json:"ack_deadline_seconds,omitempty"` - // Indicates whether to retain acknowledged messages. If true, then - // messages are not expunged from the subscription's backlog, even if they are - // acknowledged, until they fall out of the `message_retention_duration` - // window. - RetainAckedMessages bool `protobuf:"varint,7,opt,name=retain_acked_messages,json=retainAckedMessages" json:"retain_acked_messages,omitempty"` - // How long to retain unacknowledged messages in the subscription's backlog, - // from the moment a message is published. - // If `retain_acked_messages` is true, then this also configures the retention - // of acknowledged messages, and thus configures how far back in time a `Seek` - // can be done. Defaults to 7 days. Cannot be more than 7 days or less than 10 - // minutes. - MessageRetentionDuration *duration.Duration `protobuf:"bytes,8,opt,name=message_retention_duration,json=messageRetentionDuration" json:"message_retention_duration,omitempty"` - // User labels. - Labels map[string]string `protobuf:"bytes,9,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Subscription) Reset() { *m = Subscription{} } -func (m *Subscription) String() string { return proto.CompactTextString(m) } -func (*Subscription) ProtoMessage() {} -func (*Subscription) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{11} -} -func (m *Subscription) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Subscription.Unmarshal(m, b) -} -func (m *Subscription) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Subscription.Marshal(b, m, deterministic) -} -func (dst *Subscription) XXX_Merge(src proto.Message) { - xxx_messageInfo_Subscription.Merge(dst, src) -} -func (m *Subscription) XXX_Size() int { - return xxx_messageInfo_Subscription.Size(m) -} -func (m *Subscription) XXX_DiscardUnknown() { - xxx_messageInfo_Subscription.DiscardUnknown(m) -} - -var xxx_messageInfo_Subscription proto.InternalMessageInfo - -func (m *Subscription) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Subscription) GetTopic() string { - if m != nil { - return m.Topic - } - return "" -} - -func (m *Subscription) GetPushConfig() *PushConfig { - if m != nil { - return m.PushConfig - } - return nil -} - -func (m *Subscription) GetAckDeadlineSeconds() int32 { - if m != nil { - return m.AckDeadlineSeconds - } - return 0 -} - -func (m *Subscription) GetRetainAckedMessages() bool { - if m != nil { - return m.RetainAckedMessages - } - return false -} - -func (m *Subscription) GetMessageRetentionDuration() *duration.Duration { - if m != nil { - return m.MessageRetentionDuration - } - return nil -} - -func (m *Subscription) GetLabels() map[string]string { - if m != nil { - return m.Labels - } - return nil -} - -// Configuration for a push delivery endpoint. -type PushConfig struct { - // A URL locating the endpoint to which messages should be pushed. - // For example, a Webhook endpoint might use "https://example.com/push". - PushEndpoint string `protobuf:"bytes,1,opt,name=push_endpoint,json=pushEndpoint" json:"push_endpoint,omitempty"` - // Endpoint configuration attributes. - // - // Every endpoint has a set of API supported attributes that can be used to - // control different aspects of the message delivery. - // - // The currently supported attribute is `x-goog-version`, which you can - // use to change the format of the pushed message. This attribute - // indicates the version of the data expected by the endpoint. This - // controls the shape of the pushed message (i.e., its fields and metadata). - // The endpoint version is based on the version of the Pub/Sub API. - // - // If not present during the `CreateSubscription` call, it will default to - // the version of the API used to make such call. If not present during a - // `ModifyPushConfig` call, its value will not be changed. `GetSubscription` - // calls will always return a valid version, even if the subscription was - // created without this attribute. - // - // The possible values for this attribute are: - // - // * `v1beta1`: uses the push format defined in the v1beta1 Pub/Sub API. - // * `v1` or `v1beta2`: uses the push format defined in the v1 Pub/Sub API. - Attributes map[string]string `protobuf:"bytes,2,rep,name=attributes" json:"attributes,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PushConfig) Reset() { *m = PushConfig{} } -func (m *PushConfig) String() string { return proto.CompactTextString(m) } -func (*PushConfig) ProtoMessage() {} -func (*PushConfig) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{12} -} -func (m *PushConfig) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PushConfig.Unmarshal(m, b) -} -func (m *PushConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PushConfig.Marshal(b, m, deterministic) -} -func (dst *PushConfig) XXX_Merge(src proto.Message) { - xxx_messageInfo_PushConfig.Merge(dst, src) -} -func (m *PushConfig) XXX_Size() int { - return xxx_messageInfo_PushConfig.Size(m) -} -func (m *PushConfig) XXX_DiscardUnknown() { - xxx_messageInfo_PushConfig.DiscardUnknown(m) -} - -var xxx_messageInfo_PushConfig proto.InternalMessageInfo - -func (m *PushConfig) GetPushEndpoint() string { - if m != nil { - return m.PushEndpoint - } - return "" -} - -func (m *PushConfig) GetAttributes() map[string]string { - if m != nil { - return m.Attributes - } - return nil -} - -// A message and its corresponding acknowledgment ID. -type ReceivedMessage struct { - // This ID can be used to acknowledge the received message. - AckId string `protobuf:"bytes,1,opt,name=ack_id,json=ackId" json:"ack_id,omitempty"` - // The message. - Message *PubsubMessage `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ReceivedMessage) Reset() { *m = ReceivedMessage{} } -func (m *ReceivedMessage) String() string { return proto.CompactTextString(m) } -func (*ReceivedMessage) ProtoMessage() {} -func (*ReceivedMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{13} -} -func (m *ReceivedMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ReceivedMessage.Unmarshal(m, b) -} -func (m *ReceivedMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ReceivedMessage.Marshal(b, m, deterministic) -} -func (dst *ReceivedMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReceivedMessage.Merge(dst, src) -} -func (m *ReceivedMessage) XXX_Size() int { - return xxx_messageInfo_ReceivedMessage.Size(m) -} -func (m *ReceivedMessage) XXX_DiscardUnknown() { - xxx_messageInfo_ReceivedMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_ReceivedMessage proto.InternalMessageInfo - -func (m *ReceivedMessage) GetAckId() string { - if m != nil { - return m.AckId - } - return "" -} - -func (m *ReceivedMessage) GetMessage() *PubsubMessage { - if m != nil { - return m.Message - } - return nil -} - -// Request for the GetSubscription method. -type GetSubscriptionRequest struct { - // The name of the subscription to get. - // Format is `projects/{project}/subscriptions/{sub}`. - Subscription string `protobuf:"bytes,1,opt,name=subscription" json:"subscription,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetSubscriptionRequest) Reset() { *m = GetSubscriptionRequest{} } -func (m *GetSubscriptionRequest) String() string { return proto.CompactTextString(m) } -func (*GetSubscriptionRequest) ProtoMessage() {} -func (*GetSubscriptionRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{14} -} -func (m *GetSubscriptionRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetSubscriptionRequest.Unmarshal(m, b) -} -func (m *GetSubscriptionRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetSubscriptionRequest.Marshal(b, m, deterministic) -} -func (dst *GetSubscriptionRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetSubscriptionRequest.Merge(dst, src) -} -func (m *GetSubscriptionRequest) XXX_Size() int { - return xxx_messageInfo_GetSubscriptionRequest.Size(m) -} -func (m *GetSubscriptionRequest) XXX_DiscardUnknown() { - xxx_messageInfo_GetSubscriptionRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_GetSubscriptionRequest proto.InternalMessageInfo - -func (m *GetSubscriptionRequest) GetSubscription() string { - if m != nil { - return m.Subscription - } - return "" -} - -// Request for the UpdateSubscription method. -type UpdateSubscriptionRequest struct { - // The updated subscription object. - Subscription *Subscription `protobuf:"bytes,1,opt,name=subscription" json:"subscription,omitempty"` - // Indicates which fields in the provided subscription to update. - // Must be specified and non-empty. - UpdateMask *field_mask.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask" json:"update_mask,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UpdateSubscriptionRequest) Reset() { *m = UpdateSubscriptionRequest{} } -func (m *UpdateSubscriptionRequest) String() string { return proto.CompactTextString(m) } -func (*UpdateSubscriptionRequest) ProtoMessage() {} -func (*UpdateSubscriptionRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{15} -} -func (m *UpdateSubscriptionRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UpdateSubscriptionRequest.Unmarshal(m, b) -} -func (m *UpdateSubscriptionRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UpdateSubscriptionRequest.Marshal(b, m, deterministic) -} -func (dst *UpdateSubscriptionRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_UpdateSubscriptionRequest.Merge(dst, src) -} -func (m *UpdateSubscriptionRequest) XXX_Size() int { - return xxx_messageInfo_UpdateSubscriptionRequest.Size(m) -} -func (m *UpdateSubscriptionRequest) XXX_DiscardUnknown() { - xxx_messageInfo_UpdateSubscriptionRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_UpdateSubscriptionRequest proto.InternalMessageInfo - -func (m *UpdateSubscriptionRequest) GetSubscription() *Subscription { - if m != nil { - return m.Subscription - } - return nil -} - -func (m *UpdateSubscriptionRequest) GetUpdateMask() *field_mask.FieldMask { - if m != nil { - return m.UpdateMask - } - return nil -} - -// Request for the `ListSubscriptions` method. -type ListSubscriptionsRequest struct { - // The name of the cloud project that subscriptions belong to. - // Format is `projects/{project}`. - Project string `protobuf:"bytes,1,opt,name=project" json:"project,omitempty"` - // Maximum number of subscriptions to return. - PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize" json:"page_size,omitempty"` - // The value returned by the last `ListSubscriptionsResponse`; indicates that - // this is a continuation of a prior `ListSubscriptions` call, and that the - // system should return the next page of data. - PageToken string `protobuf:"bytes,3,opt,name=page_token,json=pageToken" json:"page_token,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListSubscriptionsRequest) Reset() { *m = ListSubscriptionsRequest{} } -func (m *ListSubscriptionsRequest) String() string { return proto.CompactTextString(m) } -func (*ListSubscriptionsRequest) ProtoMessage() {} -func (*ListSubscriptionsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{16} -} -func (m *ListSubscriptionsRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListSubscriptionsRequest.Unmarshal(m, b) -} -func (m *ListSubscriptionsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListSubscriptionsRequest.Marshal(b, m, deterministic) -} -func (dst *ListSubscriptionsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListSubscriptionsRequest.Merge(dst, src) -} -func (m *ListSubscriptionsRequest) XXX_Size() int { - return xxx_messageInfo_ListSubscriptionsRequest.Size(m) -} -func (m *ListSubscriptionsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ListSubscriptionsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ListSubscriptionsRequest proto.InternalMessageInfo - -func (m *ListSubscriptionsRequest) GetProject() string { - if m != nil { - return m.Project - } - return "" -} - -func (m *ListSubscriptionsRequest) GetPageSize() int32 { - if m != nil { - return m.PageSize - } - return 0 -} - -func (m *ListSubscriptionsRequest) GetPageToken() string { - if m != nil { - return m.PageToken - } - return "" -} - -// Response for the `ListSubscriptions` method. -type ListSubscriptionsResponse struct { - // The subscriptions that match the request. - Subscriptions []*Subscription `protobuf:"bytes,1,rep,name=subscriptions" json:"subscriptions,omitempty"` - // If not empty, indicates that there may be more subscriptions that match - // the request; this value should be passed in a new - // `ListSubscriptionsRequest` to get more subscriptions. - NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken" json:"next_page_token,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListSubscriptionsResponse) Reset() { *m = ListSubscriptionsResponse{} } -func (m *ListSubscriptionsResponse) String() string { return proto.CompactTextString(m) } -func (*ListSubscriptionsResponse) ProtoMessage() {} -func (*ListSubscriptionsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{17} -} -func (m *ListSubscriptionsResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListSubscriptionsResponse.Unmarshal(m, b) -} -func (m *ListSubscriptionsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListSubscriptionsResponse.Marshal(b, m, deterministic) -} -func (dst *ListSubscriptionsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListSubscriptionsResponse.Merge(dst, src) -} -func (m *ListSubscriptionsResponse) XXX_Size() int { - return xxx_messageInfo_ListSubscriptionsResponse.Size(m) -} -func (m *ListSubscriptionsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ListSubscriptionsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ListSubscriptionsResponse proto.InternalMessageInfo - -func (m *ListSubscriptionsResponse) GetSubscriptions() []*Subscription { - if m != nil { - return m.Subscriptions - } - return nil -} - -func (m *ListSubscriptionsResponse) GetNextPageToken() string { - if m != nil { - return m.NextPageToken - } - return "" -} - -// Request for the DeleteSubscription method. -type DeleteSubscriptionRequest struct { - // The subscription to delete. - // Format is `projects/{project}/subscriptions/{sub}`. - Subscription string `protobuf:"bytes,1,opt,name=subscription" json:"subscription,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DeleteSubscriptionRequest) Reset() { *m = DeleteSubscriptionRequest{} } -func (m *DeleteSubscriptionRequest) String() string { return proto.CompactTextString(m) } -func (*DeleteSubscriptionRequest) ProtoMessage() {} -func (*DeleteSubscriptionRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{18} -} -func (m *DeleteSubscriptionRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DeleteSubscriptionRequest.Unmarshal(m, b) -} -func (m *DeleteSubscriptionRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DeleteSubscriptionRequest.Marshal(b, m, deterministic) -} -func (dst *DeleteSubscriptionRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_DeleteSubscriptionRequest.Merge(dst, src) -} -func (m *DeleteSubscriptionRequest) XXX_Size() int { - return xxx_messageInfo_DeleteSubscriptionRequest.Size(m) -} -func (m *DeleteSubscriptionRequest) XXX_DiscardUnknown() { - xxx_messageInfo_DeleteSubscriptionRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_DeleteSubscriptionRequest proto.InternalMessageInfo - -func (m *DeleteSubscriptionRequest) GetSubscription() string { - if m != nil { - return m.Subscription - } - return "" -} - -// Request for the ModifyPushConfig method. -type ModifyPushConfigRequest struct { - // The name of the subscription. - // Format is `projects/{project}/subscriptions/{sub}`. - Subscription string `protobuf:"bytes,1,opt,name=subscription" json:"subscription,omitempty"` - // The push configuration for future deliveries. - // - // An empty `pushConfig` indicates that the Pub/Sub system should - // stop pushing messages from the given subscription and allow - // messages to be pulled and acknowledged - effectively pausing - // the subscription if `Pull` is not called. - PushConfig *PushConfig `protobuf:"bytes,2,opt,name=push_config,json=pushConfig" json:"push_config,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ModifyPushConfigRequest) Reset() { *m = ModifyPushConfigRequest{} } -func (m *ModifyPushConfigRequest) String() string { return proto.CompactTextString(m) } -func (*ModifyPushConfigRequest) ProtoMessage() {} -func (*ModifyPushConfigRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{19} -} -func (m *ModifyPushConfigRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ModifyPushConfigRequest.Unmarshal(m, b) -} -func (m *ModifyPushConfigRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ModifyPushConfigRequest.Marshal(b, m, deterministic) -} -func (dst *ModifyPushConfigRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ModifyPushConfigRequest.Merge(dst, src) -} -func (m *ModifyPushConfigRequest) XXX_Size() int { - return xxx_messageInfo_ModifyPushConfigRequest.Size(m) -} -func (m *ModifyPushConfigRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ModifyPushConfigRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ModifyPushConfigRequest proto.InternalMessageInfo - -func (m *ModifyPushConfigRequest) GetSubscription() string { - if m != nil { - return m.Subscription - } - return "" -} - -func (m *ModifyPushConfigRequest) GetPushConfig() *PushConfig { - if m != nil { - return m.PushConfig - } - return nil -} - -// Request for the `Pull` method. -type PullRequest struct { - // The subscription from which messages should be pulled. - // Format is `projects/{project}/subscriptions/{sub}`. - Subscription string `protobuf:"bytes,1,opt,name=subscription" json:"subscription,omitempty"` - // If this field set to true, the system will respond immediately even if - // it there are no messages available to return in the `Pull` response. - // Otherwise, the system may wait (for a bounded amount of time) until at - // least one message is available, rather than returning no messages. The - // client may cancel the request if it does not wish to wait any longer for - // the response. - ReturnImmediately bool `protobuf:"varint,2,opt,name=return_immediately,json=returnImmediately" json:"return_immediately,omitempty"` - // The maximum number of messages returned for this request. The Pub/Sub - // system may return fewer than the number specified. - MaxMessages int32 `protobuf:"varint,3,opt,name=max_messages,json=maxMessages" json:"max_messages,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PullRequest) Reset() { *m = PullRequest{} } -func (m *PullRequest) String() string { return proto.CompactTextString(m) } -func (*PullRequest) ProtoMessage() {} -func (*PullRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{20} -} -func (m *PullRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PullRequest.Unmarshal(m, b) -} -func (m *PullRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PullRequest.Marshal(b, m, deterministic) -} -func (dst *PullRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_PullRequest.Merge(dst, src) -} -func (m *PullRequest) XXX_Size() int { - return xxx_messageInfo_PullRequest.Size(m) -} -func (m *PullRequest) XXX_DiscardUnknown() { - xxx_messageInfo_PullRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_PullRequest proto.InternalMessageInfo - -func (m *PullRequest) GetSubscription() string { - if m != nil { - return m.Subscription - } - return "" -} - -func (m *PullRequest) GetReturnImmediately() bool { - if m != nil { - return m.ReturnImmediately - } - return false -} - -func (m *PullRequest) GetMaxMessages() int32 { - if m != nil { - return m.MaxMessages - } - return 0 -} - -// Response for the `Pull` method. -type PullResponse struct { - // Received Pub/Sub messages. The Pub/Sub system will return zero messages if - // there are no more available in the backlog. The Pub/Sub system may return - // fewer than the `maxMessages` requested even if there are more messages - // available in the backlog. - ReceivedMessages []*ReceivedMessage `protobuf:"bytes,1,rep,name=received_messages,json=receivedMessages" json:"received_messages,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PullResponse) Reset() { *m = PullResponse{} } -func (m *PullResponse) String() string { return proto.CompactTextString(m) } -func (*PullResponse) ProtoMessage() {} -func (*PullResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{21} -} -func (m *PullResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PullResponse.Unmarshal(m, b) -} -func (m *PullResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PullResponse.Marshal(b, m, deterministic) -} -func (dst *PullResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_PullResponse.Merge(dst, src) -} -func (m *PullResponse) XXX_Size() int { - return xxx_messageInfo_PullResponse.Size(m) -} -func (m *PullResponse) XXX_DiscardUnknown() { - xxx_messageInfo_PullResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_PullResponse proto.InternalMessageInfo - -func (m *PullResponse) GetReceivedMessages() []*ReceivedMessage { - if m != nil { - return m.ReceivedMessages - } - return nil -} - -// Request for the ModifyAckDeadline method. -type ModifyAckDeadlineRequest struct { - // The name of the subscription. - // Format is `projects/{project}/subscriptions/{sub}`. - Subscription string `protobuf:"bytes,1,opt,name=subscription" json:"subscription,omitempty"` - // List of acknowledgment IDs. - AckIds []string `protobuf:"bytes,4,rep,name=ack_ids,json=ackIds" json:"ack_ids,omitempty"` - // The new ack deadline with respect to the time this request was sent to - // the Pub/Sub system. For example, if the value is 10, the new - // ack deadline will expire 10 seconds after the `ModifyAckDeadline` call - // was made. Specifying zero may immediately make the message available for - // another pull request. - // The minimum deadline you can specify is 0 seconds. - // The maximum deadline you can specify is 600 seconds (10 minutes). - AckDeadlineSeconds int32 `protobuf:"varint,3,opt,name=ack_deadline_seconds,json=ackDeadlineSeconds" json:"ack_deadline_seconds,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ModifyAckDeadlineRequest) Reset() { *m = ModifyAckDeadlineRequest{} } -func (m *ModifyAckDeadlineRequest) String() string { return proto.CompactTextString(m) } -func (*ModifyAckDeadlineRequest) ProtoMessage() {} -func (*ModifyAckDeadlineRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{22} -} -func (m *ModifyAckDeadlineRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ModifyAckDeadlineRequest.Unmarshal(m, b) -} -func (m *ModifyAckDeadlineRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ModifyAckDeadlineRequest.Marshal(b, m, deterministic) -} -func (dst *ModifyAckDeadlineRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ModifyAckDeadlineRequest.Merge(dst, src) -} -func (m *ModifyAckDeadlineRequest) XXX_Size() int { - return xxx_messageInfo_ModifyAckDeadlineRequest.Size(m) -} -func (m *ModifyAckDeadlineRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ModifyAckDeadlineRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ModifyAckDeadlineRequest proto.InternalMessageInfo - -func (m *ModifyAckDeadlineRequest) GetSubscription() string { - if m != nil { - return m.Subscription - } - return "" -} - -func (m *ModifyAckDeadlineRequest) GetAckIds() []string { - if m != nil { - return m.AckIds - } - return nil -} - -func (m *ModifyAckDeadlineRequest) GetAckDeadlineSeconds() int32 { - if m != nil { - return m.AckDeadlineSeconds - } - return 0 -} - -// Request for the Acknowledge method. -type AcknowledgeRequest struct { - // The subscription whose message is being acknowledged. - // Format is `projects/{project}/subscriptions/{sub}`. - Subscription string `protobuf:"bytes,1,opt,name=subscription" json:"subscription,omitempty"` - // The acknowledgment ID for the messages being acknowledged that was returned - // by the Pub/Sub system in the `Pull` response. Must not be empty. - AckIds []string `protobuf:"bytes,2,rep,name=ack_ids,json=ackIds" json:"ack_ids,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *AcknowledgeRequest) Reset() { *m = AcknowledgeRequest{} } -func (m *AcknowledgeRequest) String() string { return proto.CompactTextString(m) } -func (*AcknowledgeRequest) ProtoMessage() {} -func (*AcknowledgeRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{23} -} -func (m *AcknowledgeRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_AcknowledgeRequest.Unmarshal(m, b) -} -func (m *AcknowledgeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_AcknowledgeRequest.Marshal(b, m, deterministic) -} -func (dst *AcknowledgeRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_AcknowledgeRequest.Merge(dst, src) -} -func (m *AcknowledgeRequest) XXX_Size() int { - return xxx_messageInfo_AcknowledgeRequest.Size(m) -} -func (m *AcknowledgeRequest) XXX_DiscardUnknown() { - xxx_messageInfo_AcknowledgeRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_AcknowledgeRequest proto.InternalMessageInfo - -func (m *AcknowledgeRequest) GetSubscription() string { - if m != nil { - return m.Subscription - } - return "" -} - -func (m *AcknowledgeRequest) GetAckIds() []string { - if m != nil { - return m.AckIds - } - return nil -} - -// Request for the `StreamingPull` streaming RPC method. This request is used to -// establish the initial stream as well as to stream acknowledgements and ack -// deadline modifications from the client to the server. -type StreamingPullRequest struct { - // The subscription for which to initialize the new stream. This must be - // provided in the first request on the stream, and must not be set in - // subsequent requests from client to server. - // Format is `projects/{project}/subscriptions/{sub}`. - Subscription string `protobuf:"bytes,1,opt,name=subscription" json:"subscription,omitempty"` - // List of acknowledgement IDs for acknowledging previously received messages - // (received on this stream or a different stream). If an ack ID has expired, - // the corresponding message may be redelivered later. Acknowledging a message - // more than once will not result in an error. If the acknowledgement ID is - // malformed, the stream will be aborted with status `INVALID_ARGUMENT`. - AckIds []string `protobuf:"bytes,2,rep,name=ack_ids,json=ackIds" json:"ack_ids,omitempty"` - // The list of new ack deadlines for the IDs listed in - // `modify_deadline_ack_ids`. The size of this list must be the same as the - // size of `modify_deadline_ack_ids`. If it differs the stream will be aborted - // with `INVALID_ARGUMENT`. Each element in this list is applied to the - // element in the same position in `modify_deadline_ack_ids`. The new ack - // deadline is with respect to the time this request was sent to the Pub/Sub - // system. Must be >= 0. For example, if the value is 10, the new ack deadline - // will expire 10 seconds after this request is received. If the value is 0, - // the message is immediately made available for another streaming or - // non-streaming pull request. If the value is < 0 (an error), the stream will - // be aborted with status `INVALID_ARGUMENT`. - ModifyDeadlineSeconds []int32 `protobuf:"varint,3,rep,packed,name=modify_deadline_seconds,json=modifyDeadlineSeconds" json:"modify_deadline_seconds,omitempty"` - // List of acknowledgement IDs whose deadline will be modified based on the - // corresponding element in `modify_deadline_seconds`. This field can be used - // to indicate that more time is needed to process a message by the - // subscriber, or to make the message available for redelivery if the - // processing was interrupted. - ModifyDeadlineAckIds []string `protobuf:"bytes,4,rep,name=modify_deadline_ack_ids,json=modifyDeadlineAckIds" json:"modify_deadline_ack_ids,omitempty"` - // The ack deadline to use for the stream. This must be provided in the - // first request on the stream, but it can also be updated on subsequent - // requests from client to server. The minimum deadline you can specify is 10 - // seconds. The maximum deadline you can specify is 600 seconds (10 minutes). - StreamAckDeadlineSeconds int32 `protobuf:"varint,5,opt,name=stream_ack_deadline_seconds,json=streamAckDeadlineSeconds" json:"stream_ack_deadline_seconds,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StreamingPullRequest) Reset() { *m = StreamingPullRequest{} } -func (m *StreamingPullRequest) String() string { return proto.CompactTextString(m) } -func (*StreamingPullRequest) ProtoMessage() {} -func (*StreamingPullRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{24} -} -func (m *StreamingPullRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StreamingPullRequest.Unmarshal(m, b) -} -func (m *StreamingPullRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StreamingPullRequest.Marshal(b, m, deterministic) -} -func (dst *StreamingPullRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_StreamingPullRequest.Merge(dst, src) -} -func (m *StreamingPullRequest) XXX_Size() int { - return xxx_messageInfo_StreamingPullRequest.Size(m) -} -func (m *StreamingPullRequest) XXX_DiscardUnknown() { - xxx_messageInfo_StreamingPullRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_StreamingPullRequest proto.InternalMessageInfo - -func (m *StreamingPullRequest) GetSubscription() string { - if m != nil { - return m.Subscription - } - return "" -} - -func (m *StreamingPullRequest) GetAckIds() []string { - if m != nil { - return m.AckIds - } - return nil -} - -func (m *StreamingPullRequest) GetModifyDeadlineSeconds() []int32 { - if m != nil { - return m.ModifyDeadlineSeconds - } - return nil -} - -func (m *StreamingPullRequest) GetModifyDeadlineAckIds() []string { - if m != nil { - return m.ModifyDeadlineAckIds - } - return nil -} - -func (m *StreamingPullRequest) GetStreamAckDeadlineSeconds() int32 { - if m != nil { - return m.StreamAckDeadlineSeconds - } - return 0 -} - -// Response for the `StreamingPull` method. This response is used to stream -// messages from the server to the client. -type StreamingPullResponse struct { - // Received Pub/Sub messages. This will not be empty. - ReceivedMessages []*ReceivedMessage `protobuf:"bytes,1,rep,name=received_messages,json=receivedMessages" json:"received_messages,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StreamingPullResponse) Reset() { *m = StreamingPullResponse{} } -func (m *StreamingPullResponse) String() string { return proto.CompactTextString(m) } -func (*StreamingPullResponse) ProtoMessage() {} -func (*StreamingPullResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{25} -} -func (m *StreamingPullResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StreamingPullResponse.Unmarshal(m, b) -} -func (m *StreamingPullResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StreamingPullResponse.Marshal(b, m, deterministic) -} -func (dst *StreamingPullResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_StreamingPullResponse.Merge(dst, src) -} -func (m *StreamingPullResponse) XXX_Size() int { - return xxx_messageInfo_StreamingPullResponse.Size(m) -} -func (m *StreamingPullResponse) XXX_DiscardUnknown() { - xxx_messageInfo_StreamingPullResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_StreamingPullResponse proto.InternalMessageInfo - -func (m *StreamingPullResponse) GetReceivedMessages() []*ReceivedMessage { - if m != nil { - return m.ReceivedMessages - } - return nil -} - -// Request for the `CreateSnapshot` method. -type CreateSnapshotRequest struct { - // Optional user-provided name for this snapshot. - // If the name is not provided in the request, the server will assign a random - // name for this snapshot on the same project as the subscription. - // Note that for REST API requests, you must specify a name. - // Format is `projects/{project}/snapshots/{snap}`. - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - // The subscription whose backlog the snapshot retains. - // Specifically, the created snapshot is guaranteed to retain: - // (a) The existing backlog on the subscription. More precisely, this is - // defined as the messages in the subscription's backlog that are - // unacknowledged upon the successful completion of the - // `CreateSnapshot` request; as well as: - // (b) Any messages published to the subscription's topic following the - // successful completion of the CreateSnapshot request. - // Format is `projects/{project}/subscriptions/{sub}`. - Subscription string `protobuf:"bytes,2,opt,name=subscription" json:"subscription,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CreateSnapshotRequest) Reset() { *m = CreateSnapshotRequest{} } -func (m *CreateSnapshotRequest) String() string { return proto.CompactTextString(m) } -func (*CreateSnapshotRequest) ProtoMessage() {} -func (*CreateSnapshotRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{26} -} -func (m *CreateSnapshotRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CreateSnapshotRequest.Unmarshal(m, b) -} -func (m *CreateSnapshotRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CreateSnapshotRequest.Marshal(b, m, deterministic) -} -func (dst *CreateSnapshotRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_CreateSnapshotRequest.Merge(dst, src) -} -func (m *CreateSnapshotRequest) XXX_Size() int { - return xxx_messageInfo_CreateSnapshotRequest.Size(m) -} -func (m *CreateSnapshotRequest) XXX_DiscardUnknown() { - xxx_messageInfo_CreateSnapshotRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_CreateSnapshotRequest proto.InternalMessageInfo - -func (m *CreateSnapshotRequest) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *CreateSnapshotRequest) GetSubscription() string { - if m != nil { - return m.Subscription - } - return "" -} - -// Request for the UpdateSnapshot method. -type UpdateSnapshotRequest struct { - // The updated snpashot object. - Snapshot *Snapshot `protobuf:"bytes,1,opt,name=snapshot" json:"snapshot,omitempty"` - // Indicates which fields in the provided snapshot to update. - // Must be specified and non-empty. - UpdateMask *field_mask.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask" json:"update_mask,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UpdateSnapshotRequest) Reset() { *m = UpdateSnapshotRequest{} } -func (m *UpdateSnapshotRequest) String() string { return proto.CompactTextString(m) } -func (*UpdateSnapshotRequest) ProtoMessage() {} -func (*UpdateSnapshotRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{27} -} -func (m *UpdateSnapshotRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UpdateSnapshotRequest.Unmarshal(m, b) -} -func (m *UpdateSnapshotRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UpdateSnapshotRequest.Marshal(b, m, deterministic) -} -func (dst *UpdateSnapshotRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_UpdateSnapshotRequest.Merge(dst, src) -} -func (m *UpdateSnapshotRequest) XXX_Size() int { - return xxx_messageInfo_UpdateSnapshotRequest.Size(m) -} -func (m *UpdateSnapshotRequest) XXX_DiscardUnknown() { - xxx_messageInfo_UpdateSnapshotRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_UpdateSnapshotRequest proto.InternalMessageInfo - -func (m *UpdateSnapshotRequest) GetSnapshot() *Snapshot { - if m != nil { - return m.Snapshot - } - return nil -} - -func (m *UpdateSnapshotRequest) GetUpdateMask() *field_mask.FieldMask { - if m != nil { - return m.UpdateMask - } - return nil -} - -// A snapshot resource. -type Snapshot struct { - // The name of the snapshot. - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - // The name of the topic from which this snapshot is retaining messages. - Topic string `protobuf:"bytes,2,opt,name=topic" json:"topic,omitempty"` - // The snapshot is guaranteed to exist up until this time. - // A newly-created snapshot expires no later than 7 days from the time of its - // creation. Its exact lifetime is determined at creation by the existing - // backlog in the source subscription. Specifically, the lifetime of the - // snapshot is `7 days - (age of oldest unacked message in the subscription)`. - // For example, consider a subscription whose oldest unacked message is 3 days - // old. If a snapshot is created from this subscription, the snapshot -- which - // will always capture this 3-day-old backlog as long as the snapshot - // exists -- will expire in 4 days. - ExpireTime *timestamp.Timestamp `protobuf:"bytes,3,opt,name=expire_time,json=expireTime" json:"expire_time,omitempty"` - // User labels. - Labels map[string]string `protobuf:"bytes,4,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Snapshot) Reset() { *m = Snapshot{} } -func (m *Snapshot) String() string { return proto.CompactTextString(m) } -func (*Snapshot) ProtoMessage() {} -func (*Snapshot) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{28} -} -func (m *Snapshot) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Snapshot.Unmarshal(m, b) -} -func (m *Snapshot) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Snapshot.Marshal(b, m, deterministic) -} -func (dst *Snapshot) XXX_Merge(src proto.Message) { - xxx_messageInfo_Snapshot.Merge(dst, src) -} -func (m *Snapshot) XXX_Size() int { - return xxx_messageInfo_Snapshot.Size(m) -} -func (m *Snapshot) XXX_DiscardUnknown() { - xxx_messageInfo_Snapshot.DiscardUnknown(m) -} - -var xxx_messageInfo_Snapshot proto.InternalMessageInfo - -func (m *Snapshot) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Snapshot) GetTopic() string { - if m != nil { - return m.Topic - } - return "" -} - -func (m *Snapshot) GetExpireTime() *timestamp.Timestamp { - if m != nil { - return m.ExpireTime - } - return nil -} - -func (m *Snapshot) GetLabels() map[string]string { - if m != nil { - return m.Labels - } - return nil -} - -// Request for the `ListSnapshots` method. -type ListSnapshotsRequest struct { - // The name of the cloud project that snapshots belong to. - // Format is `projects/{project}`. - Project string `protobuf:"bytes,1,opt,name=project" json:"project,omitempty"` - // Maximum number of snapshots to return. - PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize" json:"page_size,omitempty"` - // The value returned by the last `ListSnapshotsResponse`; indicates that this - // is a continuation of a prior `ListSnapshots` call, and that the system - // should return the next page of data. - PageToken string `protobuf:"bytes,3,opt,name=page_token,json=pageToken" json:"page_token,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListSnapshotsRequest) Reset() { *m = ListSnapshotsRequest{} } -func (m *ListSnapshotsRequest) String() string { return proto.CompactTextString(m) } -func (*ListSnapshotsRequest) ProtoMessage() {} -func (*ListSnapshotsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{29} -} -func (m *ListSnapshotsRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListSnapshotsRequest.Unmarshal(m, b) -} -func (m *ListSnapshotsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListSnapshotsRequest.Marshal(b, m, deterministic) -} -func (dst *ListSnapshotsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListSnapshotsRequest.Merge(dst, src) -} -func (m *ListSnapshotsRequest) XXX_Size() int { - return xxx_messageInfo_ListSnapshotsRequest.Size(m) -} -func (m *ListSnapshotsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ListSnapshotsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ListSnapshotsRequest proto.InternalMessageInfo - -func (m *ListSnapshotsRequest) GetProject() string { - if m != nil { - return m.Project - } - return "" -} - -func (m *ListSnapshotsRequest) GetPageSize() int32 { - if m != nil { - return m.PageSize - } - return 0 -} - -func (m *ListSnapshotsRequest) GetPageToken() string { - if m != nil { - return m.PageToken - } - return "" -} - -// Response for the `ListSnapshots` method. -type ListSnapshotsResponse struct { - // The resulting snapshots. - Snapshots []*Snapshot `protobuf:"bytes,1,rep,name=snapshots" json:"snapshots,omitempty"` - // If not empty, indicates that there may be more snapshot that match the - // request; this value should be passed in a new `ListSnapshotsRequest`. - NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken" json:"next_page_token,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListSnapshotsResponse) Reset() { *m = ListSnapshotsResponse{} } -func (m *ListSnapshotsResponse) String() string { return proto.CompactTextString(m) } -func (*ListSnapshotsResponse) ProtoMessage() {} -func (*ListSnapshotsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{30} -} -func (m *ListSnapshotsResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListSnapshotsResponse.Unmarshal(m, b) -} -func (m *ListSnapshotsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListSnapshotsResponse.Marshal(b, m, deterministic) -} -func (dst *ListSnapshotsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListSnapshotsResponse.Merge(dst, src) -} -func (m *ListSnapshotsResponse) XXX_Size() int { - return xxx_messageInfo_ListSnapshotsResponse.Size(m) -} -func (m *ListSnapshotsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ListSnapshotsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ListSnapshotsResponse proto.InternalMessageInfo - -func (m *ListSnapshotsResponse) GetSnapshots() []*Snapshot { - if m != nil { - return m.Snapshots - } - return nil -} - -func (m *ListSnapshotsResponse) GetNextPageToken() string { - if m != nil { - return m.NextPageToken - } - return "" -} - -// Request for the `DeleteSnapshot` method. -type DeleteSnapshotRequest struct { - // The name of the snapshot to delete. - // Format is `projects/{project}/snapshots/{snap}`. - Snapshot string `protobuf:"bytes,1,opt,name=snapshot" json:"snapshot,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DeleteSnapshotRequest) Reset() { *m = DeleteSnapshotRequest{} } -func (m *DeleteSnapshotRequest) String() string { return proto.CompactTextString(m) } -func (*DeleteSnapshotRequest) ProtoMessage() {} -func (*DeleteSnapshotRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{31} -} -func (m *DeleteSnapshotRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DeleteSnapshotRequest.Unmarshal(m, b) -} -func (m *DeleteSnapshotRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DeleteSnapshotRequest.Marshal(b, m, deterministic) -} -func (dst *DeleteSnapshotRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_DeleteSnapshotRequest.Merge(dst, src) -} -func (m *DeleteSnapshotRequest) XXX_Size() int { - return xxx_messageInfo_DeleteSnapshotRequest.Size(m) -} -func (m *DeleteSnapshotRequest) XXX_DiscardUnknown() { - xxx_messageInfo_DeleteSnapshotRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_DeleteSnapshotRequest proto.InternalMessageInfo - -func (m *DeleteSnapshotRequest) GetSnapshot() string { - if m != nil { - return m.Snapshot - } - return "" -} - -// Request for the `Seek` method. -type SeekRequest struct { - // The subscription to affect. - Subscription string `protobuf:"bytes,1,opt,name=subscription" json:"subscription,omitempty"` - // Types that are valid to be assigned to Target: - // *SeekRequest_Time - // *SeekRequest_Snapshot - Target isSeekRequest_Target `protobuf_oneof:"target"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SeekRequest) Reset() { *m = SeekRequest{} } -func (m *SeekRequest) String() string { return proto.CompactTextString(m) } -func (*SeekRequest) ProtoMessage() {} -func (*SeekRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{32} -} -func (m *SeekRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SeekRequest.Unmarshal(m, b) -} -func (m *SeekRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SeekRequest.Marshal(b, m, deterministic) -} -func (dst *SeekRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_SeekRequest.Merge(dst, src) -} -func (m *SeekRequest) XXX_Size() int { - return xxx_messageInfo_SeekRequest.Size(m) -} -func (m *SeekRequest) XXX_DiscardUnknown() { - xxx_messageInfo_SeekRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_SeekRequest proto.InternalMessageInfo - -type isSeekRequest_Target interface { - isSeekRequest_Target() -} - -type SeekRequest_Time struct { - Time *timestamp.Timestamp `protobuf:"bytes,2,opt,name=time,oneof"` -} -type SeekRequest_Snapshot struct { - Snapshot string `protobuf:"bytes,3,opt,name=snapshot,oneof"` -} - -func (*SeekRequest_Time) isSeekRequest_Target() {} -func (*SeekRequest_Snapshot) isSeekRequest_Target() {} - -func (m *SeekRequest) GetTarget() isSeekRequest_Target { - if m != nil { - return m.Target - } - return nil -} - -func (m *SeekRequest) GetSubscription() string { - if m != nil { - return m.Subscription - } - return "" -} - -func (m *SeekRequest) GetTime() *timestamp.Timestamp { - if x, ok := m.GetTarget().(*SeekRequest_Time); ok { - return x.Time - } - return nil -} - -func (m *SeekRequest) GetSnapshot() string { - if x, ok := m.GetTarget().(*SeekRequest_Snapshot); ok { - return x.Snapshot - } - return "" -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*SeekRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _SeekRequest_OneofMarshaler, _SeekRequest_OneofUnmarshaler, _SeekRequest_OneofSizer, []interface{}{ - (*SeekRequest_Time)(nil), - (*SeekRequest_Snapshot)(nil), - } -} - -func _SeekRequest_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*SeekRequest) - // target - switch x := m.Target.(type) { - case *SeekRequest_Time: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Time); err != nil { - return err - } - case *SeekRequest_Snapshot: - b.EncodeVarint(3<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Snapshot) - case nil: - default: - return fmt.Errorf("SeekRequest.Target has unexpected type %T", x) - } - return nil -} - -func _SeekRequest_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*SeekRequest) - switch tag { - case 2: // target.time - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(timestamp.Timestamp) - err := b.DecodeMessage(msg) - m.Target = &SeekRequest_Time{msg} - return true, err - case 3: // target.snapshot - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Target = &SeekRequest_Snapshot{x} - return true, err - default: - return false, nil - } -} - -func _SeekRequest_OneofSizer(msg proto.Message) (n int) { - m := msg.(*SeekRequest) - // target - switch x := m.Target.(type) { - case *SeekRequest_Time: - s := proto.Size(x.Time) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *SeekRequest_Snapshot: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Snapshot))) - n += len(x.Snapshot) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type SeekResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SeekResponse) Reset() { *m = SeekResponse{} } -func (m *SeekResponse) String() string { return proto.CompactTextString(m) } -func (*SeekResponse) ProtoMessage() {} -func (*SeekResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_pubsub_2c3603090b805ba2, []int{33} -} -func (m *SeekResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SeekResponse.Unmarshal(m, b) -} -func (m *SeekResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SeekResponse.Marshal(b, m, deterministic) -} -func (dst *SeekResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_SeekResponse.Merge(dst, src) -} -func (m *SeekResponse) XXX_Size() int { - return xxx_messageInfo_SeekResponse.Size(m) -} -func (m *SeekResponse) XXX_DiscardUnknown() { - xxx_messageInfo_SeekResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_SeekResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Topic)(nil), "google.pubsub.v1.Topic") - proto.RegisterMapType((map[string]string)(nil), "google.pubsub.v1.Topic.LabelsEntry") - proto.RegisterType((*PubsubMessage)(nil), "google.pubsub.v1.PubsubMessage") - proto.RegisterMapType((map[string]string)(nil), "google.pubsub.v1.PubsubMessage.AttributesEntry") - proto.RegisterType((*GetTopicRequest)(nil), "google.pubsub.v1.GetTopicRequest") - proto.RegisterType((*UpdateTopicRequest)(nil), "google.pubsub.v1.UpdateTopicRequest") - proto.RegisterType((*PublishRequest)(nil), "google.pubsub.v1.PublishRequest") - proto.RegisterType((*PublishResponse)(nil), "google.pubsub.v1.PublishResponse") - proto.RegisterType((*ListTopicsRequest)(nil), "google.pubsub.v1.ListTopicsRequest") - proto.RegisterType((*ListTopicsResponse)(nil), "google.pubsub.v1.ListTopicsResponse") - proto.RegisterType((*ListTopicSubscriptionsRequest)(nil), "google.pubsub.v1.ListTopicSubscriptionsRequest") - proto.RegisterType((*ListTopicSubscriptionsResponse)(nil), "google.pubsub.v1.ListTopicSubscriptionsResponse") - proto.RegisterType((*DeleteTopicRequest)(nil), "google.pubsub.v1.DeleteTopicRequest") - proto.RegisterType((*Subscription)(nil), "google.pubsub.v1.Subscription") - proto.RegisterMapType((map[string]string)(nil), "google.pubsub.v1.Subscription.LabelsEntry") - proto.RegisterType((*PushConfig)(nil), "google.pubsub.v1.PushConfig") - proto.RegisterMapType((map[string]string)(nil), "google.pubsub.v1.PushConfig.AttributesEntry") - proto.RegisterType((*ReceivedMessage)(nil), "google.pubsub.v1.ReceivedMessage") - proto.RegisterType((*GetSubscriptionRequest)(nil), "google.pubsub.v1.GetSubscriptionRequest") - proto.RegisterType((*UpdateSubscriptionRequest)(nil), "google.pubsub.v1.UpdateSubscriptionRequest") - proto.RegisterType((*ListSubscriptionsRequest)(nil), "google.pubsub.v1.ListSubscriptionsRequest") - proto.RegisterType((*ListSubscriptionsResponse)(nil), "google.pubsub.v1.ListSubscriptionsResponse") - proto.RegisterType((*DeleteSubscriptionRequest)(nil), "google.pubsub.v1.DeleteSubscriptionRequest") - proto.RegisterType((*ModifyPushConfigRequest)(nil), "google.pubsub.v1.ModifyPushConfigRequest") - proto.RegisterType((*PullRequest)(nil), "google.pubsub.v1.PullRequest") - proto.RegisterType((*PullResponse)(nil), "google.pubsub.v1.PullResponse") - proto.RegisterType((*ModifyAckDeadlineRequest)(nil), "google.pubsub.v1.ModifyAckDeadlineRequest") - proto.RegisterType((*AcknowledgeRequest)(nil), "google.pubsub.v1.AcknowledgeRequest") - proto.RegisterType((*StreamingPullRequest)(nil), "google.pubsub.v1.StreamingPullRequest") - proto.RegisterType((*StreamingPullResponse)(nil), "google.pubsub.v1.StreamingPullResponse") - proto.RegisterType((*CreateSnapshotRequest)(nil), "google.pubsub.v1.CreateSnapshotRequest") - proto.RegisterType((*UpdateSnapshotRequest)(nil), "google.pubsub.v1.UpdateSnapshotRequest") - proto.RegisterType((*Snapshot)(nil), "google.pubsub.v1.Snapshot") - proto.RegisterMapType((map[string]string)(nil), "google.pubsub.v1.Snapshot.LabelsEntry") - proto.RegisterType((*ListSnapshotsRequest)(nil), "google.pubsub.v1.ListSnapshotsRequest") - proto.RegisterType((*ListSnapshotsResponse)(nil), "google.pubsub.v1.ListSnapshotsResponse") - proto.RegisterType((*DeleteSnapshotRequest)(nil), "google.pubsub.v1.DeleteSnapshotRequest") - proto.RegisterType((*SeekRequest)(nil), "google.pubsub.v1.SeekRequest") - proto.RegisterType((*SeekResponse)(nil), "google.pubsub.v1.SeekResponse") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// SubscriberClient is the client API for Subscriber service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type SubscriberClient interface { - // Creates a subscription to a given topic. - // If the subscription already exists, returns `ALREADY_EXISTS`. - // If the corresponding topic doesn't exist, returns `NOT_FOUND`. - // - // If the name is not provided in the request, the server will assign a random - // name for this subscription on the same project as the topic, conforming - // to the - // [resource name format](https://cloud.google.com/pubsub/docs/overview#names). - // The generated name is populated in the returned Subscription object. - // Note that for REST API requests, you must specify a name in the request. - CreateSubscription(ctx context.Context, in *Subscription, opts ...grpc.CallOption) (*Subscription, error) - // Gets the configuration details of a subscription. - GetSubscription(ctx context.Context, in *GetSubscriptionRequest, opts ...grpc.CallOption) (*Subscription, error) - // Updates an existing subscription. Note that certain properties of a - // subscription, such as its topic, are not modifiable. - // NOTE: The style guide requires body: "subscription" instead of body: "*". - // Keeping the latter for internal consistency in V1, however it should be - // corrected in V2. See - // https://cloud.google.com/apis/design/standard_methods#update for details. - UpdateSubscription(ctx context.Context, in *UpdateSubscriptionRequest, opts ...grpc.CallOption) (*Subscription, error) - // Lists matching subscriptions. - ListSubscriptions(ctx context.Context, in *ListSubscriptionsRequest, opts ...grpc.CallOption) (*ListSubscriptionsResponse, error) - // Deletes an existing subscription. All messages retained in the subscription - // are immediately dropped. Calls to `Pull` after deletion will return - // `NOT_FOUND`. After a subscription is deleted, a new one may be created with - // the same name, but the new one has no association with the old - // subscription or its topic unless the same topic is specified. - DeleteSubscription(ctx context.Context, in *DeleteSubscriptionRequest, opts ...grpc.CallOption) (*empty.Empty, error) - // Modifies the ack deadline for a specific message. This method is useful - // to indicate that more time is needed to process a message by the - // subscriber, or to make the message available for redelivery if the - // processing was interrupted. Note that this does not modify the - // subscription-level `ackDeadlineSeconds` used for subsequent messages. - ModifyAckDeadline(ctx context.Context, in *ModifyAckDeadlineRequest, opts ...grpc.CallOption) (*empty.Empty, error) - // Acknowledges the messages associated with the `ack_ids` in the - // `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages - // from the subscription. - // - // Acknowledging a message whose ack deadline has expired may succeed, - // but such a message may be redelivered later. Acknowledging a message more - // than once will not result in an error. - Acknowledge(ctx context.Context, in *AcknowledgeRequest, opts ...grpc.CallOption) (*empty.Empty, error) - // Pulls messages from the server. Returns an empty list if there are no - // messages available in the backlog. The server may return `UNAVAILABLE` if - // there are too many concurrent pull requests pending for the given - // subscription. - Pull(ctx context.Context, in *PullRequest, opts ...grpc.CallOption) (*PullResponse, error) - // (EXPERIMENTAL) StreamingPull is an experimental feature. This RPC will - // respond with UNIMPLEMENTED errors unless you have been invited to test - // this feature. Contact cloud-pubsub@google.com with any questions. - // - // Establishes a stream with the server, which sends messages down to the - // client. The client streams acknowledgements and ack deadline modifications - // back to the server. The server will close the stream and return the status - // on any error. The server may close the stream with status `OK` to reassign - // server-side resources, in which case, the client should re-establish the - // stream. `UNAVAILABLE` may also be returned in the case of a transient error - // (e.g., a server restart). These should also be retried by the client. Flow - // control can be achieved by configuring the underlying RPC channel. - StreamingPull(ctx context.Context, opts ...grpc.CallOption) (Subscriber_StreamingPullClient, error) - // Modifies the `PushConfig` for a specified subscription. - // - // This may be used to change a push subscription to a pull one (signified by - // an empty `PushConfig`) or vice versa, or change the endpoint URL and other - // attributes of a push subscription. Messages will accumulate for delivery - // continuously through the call regardless of changes to the `PushConfig`. - ModifyPushConfig(ctx context.Context, in *ModifyPushConfigRequest, opts ...grpc.CallOption) (*empty.Empty, error) - // Lists the existing snapshots. - ListSnapshots(ctx context.Context, in *ListSnapshotsRequest, opts ...grpc.CallOption) (*ListSnapshotsResponse, error) - // Creates a snapshot from the requested subscription. - // If the snapshot already exists, returns `ALREADY_EXISTS`. - // If the requested subscription doesn't exist, returns `NOT_FOUND`. - // - // If the name is not provided in the request, the server will assign a random - // name for this snapshot on the same project as the subscription, conforming - // to the - // [resource name format](https://cloud.google.com/pubsub/docs/overview#names). - // The generated name is populated in the returned Snapshot object. - // Note that for REST API requests, you must specify a name in the request. - CreateSnapshot(ctx context.Context, in *CreateSnapshotRequest, opts ...grpc.CallOption) (*Snapshot, error) - // Updates an existing snapshot. Note that certain properties of a snapshot - // are not modifiable. - // NOTE: The style guide requires body: "snapshot" instead of body: "*". - // Keeping the latter for internal consistency in V1, however it should be - // corrected in V2. See - // https://cloud.google.com/apis/design/standard_methods#update for details. - UpdateSnapshot(ctx context.Context, in *UpdateSnapshotRequest, opts ...grpc.CallOption) (*Snapshot, error) - // Removes an existing snapshot. All messages retained in the snapshot - // are immediately dropped. After a snapshot is deleted, a new one may be - // created with the same name, but the new one has no association with the old - // snapshot or its subscription, unless the same subscription is specified. - DeleteSnapshot(ctx context.Context, in *DeleteSnapshotRequest, opts ...grpc.CallOption) (*empty.Empty, error) - // Seeks an existing subscription to a point in time or to a given snapshot, - // whichever is provided in the request. - Seek(ctx context.Context, in *SeekRequest, opts ...grpc.CallOption) (*SeekResponse, error) -} - -type subscriberClient struct { - cc *grpc.ClientConn -} - -func NewSubscriberClient(cc *grpc.ClientConn) SubscriberClient { - return &subscriberClient{cc} -} - -func (c *subscriberClient) CreateSubscription(ctx context.Context, in *Subscription, opts ...grpc.CallOption) (*Subscription, error) { - out := new(Subscription) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Subscriber/CreateSubscription", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *subscriberClient) GetSubscription(ctx context.Context, in *GetSubscriptionRequest, opts ...grpc.CallOption) (*Subscription, error) { - out := new(Subscription) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Subscriber/GetSubscription", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *subscriberClient) UpdateSubscription(ctx context.Context, in *UpdateSubscriptionRequest, opts ...grpc.CallOption) (*Subscription, error) { - out := new(Subscription) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Subscriber/UpdateSubscription", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *subscriberClient) ListSubscriptions(ctx context.Context, in *ListSubscriptionsRequest, opts ...grpc.CallOption) (*ListSubscriptionsResponse, error) { - out := new(ListSubscriptionsResponse) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Subscriber/ListSubscriptions", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *subscriberClient) DeleteSubscription(ctx context.Context, in *DeleteSubscriptionRequest, opts ...grpc.CallOption) (*empty.Empty, error) { - out := new(empty.Empty) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Subscriber/DeleteSubscription", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *subscriberClient) ModifyAckDeadline(ctx context.Context, in *ModifyAckDeadlineRequest, opts ...grpc.CallOption) (*empty.Empty, error) { - out := new(empty.Empty) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Subscriber/ModifyAckDeadline", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *subscriberClient) Acknowledge(ctx context.Context, in *AcknowledgeRequest, opts ...grpc.CallOption) (*empty.Empty, error) { - out := new(empty.Empty) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Subscriber/Acknowledge", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *subscriberClient) Pull(ctx context.Context, in *PullRequest, opts ...grpc.CallOption) (*PullResponse, error) { - out := new(PullResponse) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Subscriber/Pull", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *subscriberClient) StreamingPull(ctx context.Context, opts ...grpc.CallOption) (Subscriber_StreamingPullClient, error) { - stream, err := c.cc.NewStream(ctx, &_Subscriber_serviceDesc.Streams[0], "/google.pubsub.v1.Subscriber/StreamingPull", opts...) - if err != nil { - return nil, err - } - x := &subscriberStreamingPullClient{stream} - return x, nil -} - -type Subscriber_StreamingPullClient interface { - Send(*StreamingPullRequest) error - Recv() (*StreamingPullResponse, error) - grpc.ClientStream -} - -type subscriberStreamingPullClient struct { - grpc.ClientStream -} - -func (x *subscriberStreamingPullClient) Send(m *StreamingPullRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *subscriberStreamingPullClient) Recv() (*StreamingPullResponse, error) { - m := new(StreamingPullResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *subscriberClient) ModifyPushConfig(ctx context.Context, in *ModifyPushConfigRequest, opts ...grpc.CallOption) (*empty.Empty, error) { - out := new(empty.Empty) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Subscriber/ModifyPushConfig", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *subscriberClient) ListSnapshots(ctx context.Context, in *ListSnapshotsRequest, opts ...grpc.CallOption) (*ListSnapshotsResponse, error) { - out := new(ListSnapshotsResponse) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Subscriber/ListSnapshots", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *subscriberClient) CreateSnapshot(ctx context.Context, in *CreateSnapshotRequest, opts ...grpc.CallOption) (*Snapshot, error) { - out := new(Snapshot) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Subscriber/CreateSnapshot", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *subscriberClient) UpdateSnapshot(ctx context.Context, in *UpdateSnapshotRequest, opts ...grpc.CallOption) (*Snapshot, error) { - out := new(Snapshot) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Subscriber/UpdateSnapshot", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *subscriberClient) DeleteSnapshot(ctx context.Context, in *DeleteSnapshotRequest, opts ...grpc.CallOption) (*empty.Empty, error) { - out := new(empty.Empty) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Subscriber/DeleteSnapshot", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *subscriberClient) Seek(ctx context.Context, in *SeekRequest, opts ...grpc.CallOption) (*SeekResponse, error) { - out := new(SeekResponse) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Subscriber/Seek", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for Subscriber service - -type SubscriberServer interface { - // Creates a subscription to a given topic. - // If the subscription already exists, returns `ALREADY_EXISTS`. - // If the corresponding topic doesn't exist, returns `NOT_FOUND`. - // - // If the name is not provided in the request, the server will assign a random - // name for this subscription on the same project as the topic, conforming - // to the - // [resource name format](https://cloud.google.com/pubsub/docs/overview#names). - // The generated name is populated in the returned Subscription object. - // Note that for REST API requests, you must specify a name in the request. - CreateSubscription(context.Context, *Subscription) (*Subscription, error) - // Gets the configuration details of a subscription. - GetSubscription(context.Context, *GetSubscriptionRequest) (*Subscription, error) - // Updates an existing subscription. Note that certain properties of a - // subscription, such as its topic, are not modifiable. - // NOTE: The style guide requires body: "subscription" instead of body: "*". - // Keeping the latter for internal consistency in V1, however it should be - // corrected in V2. See - // https://cloud.google.com/apis/design/standard_methods#update for details. - UpdateSubscription(context.Context, *UpdateSubscriptionRequest) (*Subscription, error) - // Lists matching subscriptions. - ListSubscriptions(context.Context, *ListSubscriptionsRequest) (*ListSubscriptionsResponse, error) - // Deletes an existing subscription. All messages retained in the subscription - // are immediately dropped. Calls to `Pull` after deletion will return - // `NOT_FOUND`. After a subscription is deleted, a new one may be created with - // the same name, but the new one has no association with the old - // subscription or its topic unless the same topic is specified. - DeleteSubscription(context.Context, *DeleteSubscriptionRequest) (*empty.Empty, error) - // Modifies the ack deadline for a specific message. This method is useful - // to indicate that more time is needed to process a message by the - // subscriber, or to make the message available for redelivery if the - // processing was interrupted. Note that this does not modify the - // subscription-level `ackDeadlineSeconds` used for subsequent messages. - ModifyAckDeadline(context.Context, *ModifyAckDeadlineRequest) (*empty.Empty, error) - // Acknowledges the messages associated with the `ack_ids` in the - // `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages - // from the subscription. - // - // Acknowledging a message whose ack deadline has expired may succeed, - // but such a message may be redelivered later. Acknowledging a message more - // than once will not result in an error. - Acknowledge(context.Context, *AcknowledgeRequest) (*empty.Empty, error) - // Pulls messages from the server. Returns an empty list if there are no - // messages available in the backlog. The server may return `UNAVAILABLE` if - // there are too many concurrent pull requests pending for the given - // subscription. - Pull(context.Context, *PullRequest) (*PullResponse, error) - // (EXPERIMENTAL) StreamingPull is an experimental feature. This RPC will - // respond with UNIMPLEMENTED errors unless you have been invited to test - // this feature. Contact cloud-pubsub@google.com with any questions. - // - // Establishes a stream with the server, which sends messages down to the - // client. The client streams acknowledgements and ack deadline modifications - // back to the server. The server will close the stream and return the status - // on any error. The server may close the stream with status `OK` to reassign - // server-side resources, in which case, the client should re-establish the - // stream. `UNAVAILABLE` may also be returned in the case of a transient error - // (e.g., a server restart). These should also be retried by the client. Flow - // control can be achieved by configuring the underlying RPC channel. - StreamingPull(Subscriber_StreamingPullServer) error - // Modifies the `PushConfig` for a specified subscription. - // - // This may be used to change a push subscription to a pull one (signified by - // an empty `PushConfig`) or vice versa, or change the endpoint URL and other - // attributes of a push subscription. Messages will accumulate for delivery - // continuously through the call regardless of changes to the `PushConfig`. - ModifyPushConfig(context.Context, *ModifyPushConfigRequest) (*empty.Empty, error) - // Lists the existing snapshots. - ListSnapshots(context.Context, *ListSnapshotsRequest) (*ListSnapshotsResponse, error) - // Creates a snapshot from the requested subscription. - // If the snapshot already exists, returns `ALREADY_EXISTS`. - // If the requested subscription doesn't exist, returns `NOT_FOUND`. - // - // If the name is not provided in the request, the server will assign a random - // name for this snapshot on the same project as the subscription, conforming - // to the - // [resource name format](https://cloud.google.com/pubsub/docs/overview#names). - // The generated name is populated in the returned Snapshot object. - // Note that for REST API requests, you must specify a name in the request. - CreateSnapshot(context.Context, *CreateSnapshotRequest) (*Snapshot, error) - // Updates an existing snapshot. Note that certain properties of a snapshot - // are not modifiable. - // NOTE: The style guide requires body: "snapshot" instead of body: "*". - // Keeping the latter for internal consistency in V1, however it should be - // corrected in V2. See - // https://cloud.google.com/apis/design/standard_methods#update for details. - UpdateSnapshot(context.Context, *UpdateSnapshotRequest) (*Snapshot, error) - // Removes an existing snapshot. All messages retained in the snapshot - // are immediately dropped. After a snapshot is deleted, a new one may be - // created with the same name, but the new one has no association with the old - // snapshot or its subscription, unless the same subscription is specified. - DeleteSnapshot(context.Context, *DeleteSnapshotRequest) (*empty.Empty, error) - // Seeks an existing subscription to a point in time or to a given snapshot, - // whichever is provided in the request. - Seek(context.Context, *SeekRequest) (*SeekResponse, error) -} - -func RegisterSubscriberServer(s *grpc.Server, srv SubscriberServer) { - s.RegisterService(&_Subscriber_serviceDesc, srv) -} - -func _Subscriber_CreateSubscription_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Subscription) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SubscriberServer).CreateSubscription(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Subscriber/CreateSubscription", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SubscriberServer).CreateSubscription(ctx, req.(*Subscription)) - } - return interceptor(ctx, in, info, handler) -} - -func _Subscriber_GetSubscription_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetSubscriptionRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SubscriberServer).GetSubscription(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Subscriber/GetSubscription", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SubscriberServer).GetSubscription(ctx, req.(*GetSubscriptionRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Subscriber_UpdateSubscription_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(UpdateSubscriptionRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SubscriberServer).UpdateSubscription(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Subscriber/UpdateSubscription", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SubscriberServer).UpdateSubscription(ctx, req.(*UpdateSubscriptionRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Subscriber_ListSubscriptions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ListSubscriptionsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SubscriberServer).ListSubscriptions(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Subscriber/ListSubscriptions", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SubscriberServer).ListSubscriptions(ctx, req.(*ListSubscriptionsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Subscriber_DeleteSubscription_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(DeleteSubscriptionRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SubscriberServer).DeleteSubscription(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Subscriber/DeleteSubscription", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SubscriberServer).DeleteSubscription(ctx, req.(*DeleteSubscriptionRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Subscriber_ModifyAckDeadline_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ModifyAckDeadlineRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SubscriberServer).ModifyAckDeadline(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Subscriber/ModifyAckDeadline", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SubscriberServer).ModifyAckDeadline(ctx, req.(*ModifyAckDeadlineRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Subscriber_Acknowledge_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(AcknowledgeRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SubscriberServer).Acknowledge(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Subscriber/Acknowledge", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SubscriberServer).Acknowledge(ctx, req.(*AcknowledgeRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Subscriber_Pull_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(PullRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SubscriberServer).Pull(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Subscriber/Pull", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SubscriberServer).Pull(ctx, req.(*PullRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Subscriber_StreamingPull_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(SubscriberServer).StreamingPull(&subscriberStreamingPullServer{stream}) -} - -type Subscriber_StreamingPullServer interface { - Send(*StreamingPullResponse) error - Recv() (*StreamingPullRequest, error) - grpc.ServerStream -} - -type subscriberStreamingPullServer struct { - grpc.ServerStream -} - -func (x *subscriberStreamingPullServer) Send(m *StreamingPullResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *subscriberStreamingPullServer) Recv() (*StreamingPullRequest, error) { - m := new(StreamingPullRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _Subscriber_ModifyPushConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ModifyPushConfigRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SubscriberServer).ModifyPushConfig(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Subscriber/ModifyPushConfig", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SubscriberServer).ModifyPushConfig(ctx, req.(*ModifyPushConfigRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Subscriber_ListSnapshots_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ListSnapshotsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SubscriberServer).ListSnapshots(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Subscriber/ListSnapshots", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SubscriberServer).ListSnapshots(ctx, req.(*ListSnapshotsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Subscriber_CreateSnapshot_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(CreateSnapshotRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SubscriberServer).CreateSnapshot(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Subscriber/CreateSnapshot", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SubscriberServer).CreateSnapshot(ctx, req.(*CreateSnapshotRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Subscriber_UpdateSnapshot_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(UpdateSnapshotRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SubscriberServer).UpdateSnapshot(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Subscriber/UpdateSnapshot", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SubscriberServer).UpdateSnapshot(ctx, req.(*UpdateSnapshotRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Subscriber_DeleteSnapshot_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(DeleteSnapshotRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SubscriberServer).DeleteSnapshot(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Subscriber/DeleteSnapshot", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SubscriberServer).DeleteSnapshot(ctx, req.(*DeleteSnapshotRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Subscriber_Seek_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SeekRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SubscriberServer).Seek(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Subscriber/Seek", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SubscriberServer).Seek(ctx, req.(*SeekRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Subscriber_serviceDesc = grpc.ServiceDesc{ - ServiceName: "google.pubsub.v1.Subscriber", - HandlerType: (*SubscriberServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "CreateSubscription", - Handler: _Subscriber_CreateSubscription_Handler, - }, - { - MethodName: "GetSubscription", - Handler: _Subscriber_GetSubscription_Handler, - }, - { - MethodName: "UpdateSubscription", - Handler: _Subscriber_UpdateSubscription_Handler, - }, - { - MethodName: "ListSubscriptions", - Handler: _Subscriber_ListSubscriptions_Handler, - }, - { - MethodName: "DeleteSubscription", - Handler: _Subscriber_DeleteSubscription_Handler, - }, - { - MethodName: "ModifyAckDeadline", - Handler: _Subscriber_ModifyAckDeadline_Handler, - }, - { - MethodName: "Acknowledge", - Handler: _Subscriber_Acknowledge_Handler, - }, - { - MethodName: "Pull", - Handler: _Subscriber_Pull_Handler, - }, - { - MethodName: "ModifyPushConfig", - Handler: _Subscriber_ModifyPushConfig_Handler, - }, - { - MethodName: "ListSnapshots", - Handler: _Subscriber_ListSnapshots_Handler, - }, - { - MethodName: "CreateSnapshot", - Handler: _Subscriber_CreateSnapshot_Handler, - }, - { - MethodName: "UpdateSnapshot", - Handler: _Subscriber_UpdateSnapshot_Handler, - }, - { - MethodName: "DeleteSnapshot", - Handler: _Subscriber_DeleteSnapshot_Handler, - }, - { - MethodName: "Seek", - Handler: _Subscriber_Seek_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "StreamingPull", - Handler: _Subscriber_StreamingPull_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "google/pubsub/v1/pubsub.proto", -} - -// PublisherClient is the client API for Publisher service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type PublisherClient interface { - // Creates the given topic with the given name. - CreateTopic(ctx context.Context, in *Topic, opts ...grpc.CallOption) (*Topic, error) - // Updates an existing topic. Note that certain properties of a topic are not - // modifiable. Options settings follow the style guide: - // NOTE: The style guide requires body: "topic" instead of body: "*". - // Keeping the latter for internal consistency in V1, however it should be - // corrected in V2. See - // https://cloud.google.com/apis/design/standard_methods#update for details. - UpdateTopic(ctx context.Context, in *UpdateTopicRequest, opts ...grpc.CallOption) (*Topic, error) - // Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic - // does not exist. The message payload must not be empty; it must contain - // either a non-empty data field, or at least one attribute. - Publish(ctx context.Context, in *PublishRequest, opts ...grpc.CallOption) (*PublishResponse, error) - // Gets the configuration of a topic. - GetTopic(ctx context.Context, in *GetTopicRequest, opts ...grpc.CallOption) (*Topic, error) - // Lists matching topics. - ListTopics(ctx context.Context, in *ListTopicsRequest, opts ...grpc.CallOption) (*ListTopicsResponse, error) - // Lists the name of the subscriptions for this topic. - ListTopicSubscriptions(ctx context.Context, in *ListTopicSubscriptionsRequest, opts ...grpc.CallOption) (*ListTopicSubscriptionsResponse, error) - // Deletes the topic with the given name. Returns `NOT_FOUND` if the topic - // does not exist. After a topic is deleted, a new topic may be created with - // the same name; this is an entirely new topic with none of the old - // configuration or subscriptions. Existing subscriptions to this topic are - // not deleted, but their `topic` field is set to `_deleted-topic_`. - DeleteTopic(ctx context.Context, in *DeleteTopicRequest, opts ...grpc.CallOption) (*empty.Empty, error) -} - -type publisherClient struct { - cc *grpc.ClientConn -} - -func NewPublisherClient(cc *grpc.ClientConn) PublisherClient { - return &publisherClient{cc} -} - -func (c *publisherClient) CreateTopic(ctx context.Context, in *Topic, opts ...grpc.CallOption) (*Topic, error) { - out := new(Topic) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Publisher/CreateTopic", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *publisherClient) UpdateTopic(ctx context.Context, in *UpdateTopicRequest, opts ...grpc.CallOption) (*Topic, error) { - out := new(Topic) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Publisher/UpdateTopic", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *publisherClient) Publish(ctx context.Context, in *PublishRequest, opts ...grpc.CallOption) (*PublishResponse, error) { - out := new(PublishResponse) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Publisher/Publish", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *publisherClient) GetTopic(ctx context.Context, in *GetTopicRequest, opts ...grpc.CallOption) (*Topic, error) { - out := new(Topic) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Publisher/GetTopic", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *publisherClient) ListTopics(ctx context.Context, in *ListTopicsRequest, opts ...grpc.CallOption) (*ListTopicsResponse, error) { - out := new(ListTopicsResponse) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Publisher/ListTopics", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *publisherClient) ListTopicSubscriptions(ctx context.Context, in *ListTopicSubscriptionsRequest, opts ...grpc.CallOption) (*ListTopicSubscriptionsResponse, error) { - out := new(ListTopicSubscriptionsResponse) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Publisher/ListTopicSubscriptions", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *publisherClient) DeleteTopic(ctx context.Context, in *DeleteTopicRequest, opts ...grpc.CallOption) (*empty.Empty, error) { - out := new(empty.Empty) - err := c.cc.Invoke(ctx, "/google.pubsub.v1.Publisher/DeleteTopic", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for Publisher service - -type PublisherServer interface { - // Creates the given topic with the given name. - CreateTopic(context.Context, *Topic) (*Topic, error) - // Updates an existing topic. Note that certain properties of a topic are not - // modifiable. Options settings follow the style guide: - // NOTE: The style guide requires body: "topic" instead of body: "*". - // Keeping the latter for internal consistency in V1, however it should be - // corrected in V2. See - // https://cloud.google.com/apis/design/standard_methods#update for details. - UpdateTopic(context.Context, *UpdateTopicRequest) (*Topic, error) - // Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic - // does not exist. The message payload must not be empty; it must contain - // either a non-empty data field, or at least one attribute. - Publish(context.Context, *PublishRequest) (*PublishResponse, error) - // Gets the configuration of a topic. - GetTopic(context.Context, *GetTopicRequest) (*Topic, error) - // Lists matching topics. - ListTopics(context.Context, *ListTopicsRequest) (*ListTopicsResponse, error) - // Lists the name of the subscriptions for this topic. - ListTopicSubscriptions(context.Context, *ListTopicSubscriptionsRequest) (*ListTopicSubscriptionsResponse, error) - // Deletes the topic with the given name. Returns `NOT_FOUND` if the topic - // does not exist. After a topic is deleted, a new topic may be created with - // the same name; this is an entirely new topic with none of the old - // configuration or subscriptions. Existing subscriptions to this topic are - // not deleted, but their `topic` field is set to `_deleted-topic_`. - DeleteTopic(context.Context, *DeleteTopicRequest) (*empty.Empty, error) -} - -func RegisterPublisherServer(s *grpc.Server, srv PublisherServer) { - s.RegisterService(&_Publisher_serviceDesc, srv) -} - -func _Publisher_CreateTopic_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Topic) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(PublisherServer).CreateTopic(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Publisher/CreateTopic", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(PublisherServer).CreateTopic(ctx, req.(*Topic)) - } - return interceptor(ctx, in, info, handler) -} - -func _Publisher_UpdateTopic_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(UpdateTopicRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(PublisherServer).UpdateTopic(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Publisher/UpdateTopic", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(PublisherServer).UpdateTopic(ctx, req.(*UpdateTopicRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Publisher_Publish_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(PublishRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(PublisherServer).Publish(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Publisher/Publish", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(PublisherServer).Publish(ctx, req.(*PublishRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Publisher_GetTopic_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetTopicRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(PublisherServer).GetTopic(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Publisher/GetTopic", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(PublisherServer).GetTopic(ctx, req.(*GetTopicRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Publisher_ListTopics_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ListTopicsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(PublisherServer).ListTopics(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Publisher/ListTopics", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(PublisherServer).ListTopics(ctx, req.(*ListTopicsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Publisher_ListTopicSubscriptions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ListTopicSubscriptionsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(PublisherServer).ListTopicSubscriptions(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Publisher/ListTopicSubscriptions", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(PublisherServer).ListTopicSubscriptions(ctx, req.(*ListTopicSubscriptionsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Publisher_DeleteTopic_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(DeleteTopicRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(PublisherServer).DeleteTopic(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/google.pubsub.v1.Publisher/DeleteTopic", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(PublisherServer).DeleteTopic(ctx, req.(*DeleteTopicRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Publisher_serviceDesc = grpc.ServiceDesc{ - ServiceName: "google.pubsub.v1.Publisher", - HandlerType: (*PublisherServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "CreateTopic", - Handler: _Publisher_CreateTopic_Handler, - }, - { - MethodName: "UpdateTopic", - Handler: _Publisher_UpdateTopic_Handler, - }, - { - MethodName: "Publish", - Handler: _Publisher_Publish_Handler, - }, - { - MethodName: "GetTopic", - Handler: _Publisher_GetTopic_Handler, - }, - { - MethodName: "ListTopics", - Handler: _Publisher_ListTopics_Handler, - }, - { - MethodName: "ListTopicSubscriptions", - Handler: _Publisher_ListTopicSubscriptions_Handler, - }, - { - MethodName: "DeleteTopic", - Handler: _Publisher_DeleteTopic_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "google/pubsub/v1/pubsub.proto", -} - -func init() { - proto.RegisterFile("google/pubsub/v1/pubsub.proto", fileDescriptor_pubsub_2c3603090b805ba2) -} - -var fileDescriptor_pubsub_2c3603090b805ba2 = []byte{ - // 2026 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x59, 0xdb, 0x6f, 0xdb, 0xd6, - 0x19, 0xef, 0x91, 0x6f, 0xf2, 0x47, 0xdf, 0x72, 0x66, 0x27, 0x0a, 0x73, 0xb3, 0x19, 0x37, 0x56, - 0xd4, 0x44, 0xb2, 0x55, 0x34, 0x6b, 0xe2, 0x39, 0x85, 0x1d, 0x67, 0x69, 0x86, 0x64, 0xf5, 0xe8, - 0xac, 0x03, 0x86, 0x60, 0x02, 0x25, 0x9e, 0x28, 0xac, 0x24, 0x92, 0x25, 0x29, 0x2f, 0xee, 0x16, - 0xa0, 0x6b, 0x87, 0x01, 0xc3, 0xf2, 0xb0, 0xb6, 0x6f, 0x43, 0x1f, 0x06, 0xec, 0x6d, 0x8f, 0x03, - 0xf6, 0xba, 0x3f, 0x60, 0xaf, 0xfb, 0x17, 0xf6, 0xb8, 0xf7, 0xed, 0x71, 0x38, 0x17, 0x52, 0xbc, - 0x1c, 0x4a, 0x96, 0xd3, 0xbc, 0x91, 0xe7, 0xfb, 0xce, 0xf9, 0x7e, 0xdf, 0xfd, 0x23, 0x0f, 0x5c, - 0x6a, 0x3b, 0x4e, 0xbb, 0x4b, 0x6a, 0x6e, 0xbf, 0xe9, 0xf7, 0x9b, 0xb5, 0xa3, 0x2d, 0xf1, 0x54, - 0x75, 0x3d, 0x27, 0x70, 0xf0, 0x12, 0x27, 0x57, 0xc5, 0xe2, 0xd1, 0x96, 0x7a, 0x51, 0x6c, 0x30, - 0x5c, 0xab, 0x66, 0xd8, 0xb6, 0x13, 0x18, 0x81, 0xe5, 0xd8, 0x3e, 0xe7, 0x57, 0x2f, 0x87, 0xc7, - 0xd1, 0xb7, 0x66, 0xff, 0x59, 0xcd, 0xec, 0x7b, 0x8c, 0x41, 0xd0, 0x2f, 0xa4, 0xe9, 0xa4, 0xe7, - 0x06, 0xc7, 0x82, 0xb8, 0x9a, 0x26, 0x3e, 0xb3, 0x48, 0xd7, 0x6c, 0xf4, 0x0c, 0xbf, 0x23, 0x38, - 0xae, 0xa4, 0x39, 0x02, 0xab, 0x47, 0xfc, 0xc0, 0xe8, 0xb9, 0x9c, 0x41, 0xfb, 0x06, 0xc1, 0xd4, - 0x13, 0xc7, 0xb5, 0x5a, 0x18, 0xc3, 0xa4, 0x6d, 0xf4, 0x48, 0x09, 0xad, 0xa2, 0xf2, 0xac, 0xce, - 0x9e, 0xf1, 0x36, 0x4c, 0x77, 0x8d, 0x26, 0xe9, 0xfa, 0xa5, 0xc2, 0xea, 0x44, 0x59, 0xa9, 0x5f, - 0xad, 0xa6, 0xd5, 0xab, 0xb2, 0xcd, 0xd5, 0x47, 0x8c, 0xeb, 0xbe, 0x1d, 0x78, 0xc7, 0xba, 0xd8, - 0xa2, 0xde, 0x06, 0x25, 0xb6, 0x8c, 0x97, 0x60, 0xa2, 0x43, 0x8e, 0xc5, 0xf1, 0xf4, 0x11, 0x2f, - 0xc3, 0xd4, 0x91, 0xd1, 0xed, 0x93, 0x52, 0x81, 0xad, 0xf1, 0x97, 0x3b, 0x85, 0xf7, 0x91, 0xf6, - 0x55, 0x01, 0xe6, 0x0f, 0x98, 0x88, 0xc7, 0xc4, 0xf7, 0x8d, 0x36, 0xa1, 0xe8, 0x4c, 0x23, 0x30, - 0xd8, 0xf6, 0x39, 0x9d, 0x3d, 0xe3, 0x8f, 0x00, 0x8c, 0x20, 0xf0, 0xac, 0x66, 0x3f, 0x20, 0x21, - 0xc2, 0x5a, 0x16, 0x61, 0xe2, 0xa0, 0xea, 0x6e, 0xb4, 0x83, 0xa3, 0x8d, 0x1d, 0x81, 0x2f, 0x01, - 0xf4, 0x38, 0x5b, 0xc3, 0x32, 0x4b, 0x13, 0x0c, 0xd5, 0xac, 0x58, 0x79, 0x68, 0xe2, 0x1d, 0x98, - 0x73, 0xfb, 0xcd, 0xae, 0xe5, 0x3f, 0x6f, 0x50, 0x33, 0x96, 0x26, 0x57, 0x51, 0x59, 0xa9, 0xab, - 0x91, 0x44, 0x61, 0xe3, 0xea, 0x93, 0xd0, 0xc6, 0xba, 0x22, 0xf8, 0xe9, 0x8a, 0xba, 0x03, 0x8b, - 0x29, 0xe1, 0x63, 0xd9, 0x64, 0x03, 0x16, 0x1f, 0x90, 0x80, 0x99, 0x5b, 0x27, 0x9f, 0xf6, 0x89, - 0x1f, 0x50, 0xe6, 0x80, 0xbe, 0x8b, 0x03, 0xf8, 0x8b, 0xf6, 0x39, 0x02, 0xfc, 0x53, 0xd7, 0x34, - 0x02, 0x92, 0x60, 0xbe, 0x19, 0x67, 0x56, 0xea, 0xe7, 0x72, 0x5c, 0x29, 0x4e, 0xc1, 0xdb, 0xa0, - 0xf4, 0xd9, 0x21, 0x2c, 0x9c, 0x18, 0x1c, 0x99, 0xae, 0x3f, 0xa4, 0x11, 0xf7, 0xd8, 0xf0, 0x3b, - 0x3a, 0x70, 0x76, 0xfa, 0xac, 0xb5, 0x60, 0xe1, 0x80, 0x6b, 0x3e, 0x14, 0x2a, 0xde, 0x86, 0xa2, - 0x30, 0x6f, 0xe8, 0xbf, 0x2b, 0x23, 0xfc, 0xa7, 0x47, 0x1b, 0xb4, 0x3a, 0x2c, 0x46, 0x42, 0x7c, - 0xd7, 0xb1, 0x7d, 0x82, 0xaf, 0x80, 0x32, 0x70, 0xa0, 0x5f, 0x42, 0xab, 0x13, 0xe5, 0x59, 0x1d, - 0x22, 0x0f, 0xfa, 0x9a, 0x05, 0x67, 0x1e, 0x59, 0x3e, 0xb7, 0xa2, 0x1f, 0x62, 0x2b, 0xc1, 0x8c, - 0xeb, 0x39, 0x9f, 0x90, 0x56, 0x20, 0xd0, 0x85, 0xaf, 0xf8, 0x02, 0xcc, 0xba, 0xf4, 0x30, 0xdf, - 0xfa, 0x8c, 0x7b, 0x64, 0x4a, 0x2f, 0xd2, 0x85, 0x43, 0xeb, 0x33, 0x42, 0xa3, 0x85, 0x11, 0x03, - 0xa7, 0x43, 0xec, 0x30, 0x5a, 0xe8, 0xca, 0x13, 0xba, 0xa0, 0xf5, 0x00, 0xc7, 0x45, 0x09, 0x84, - 0x35, 0x98, 0x66, 0xaa, 0x73, 0x70, 0x43, 0xdc, 0x20, 0xd8, 0xf0, 0x35, 0x58, 0xb4, 0xc9, 0x8b, - 0xa0, 0x11, 0x13, 0xc5, 0x43, 0x63, 0x9e, 0x2e, 0x1f, 0x44, 0xe2, 0x3e, 0x85, 0x4b, 0x91, 0xb8, - 0xc3, 0x7e, 0xd3, 0x6f, 0x79, 0x96, 0xcb, 0x0a, 0xcd, 0x70, 0x0f, 0xbc, 0x8e, 0x86, 0x36, 0x5c, - 0xce, 0x13, 0x29, 0xb4, 0x5d, 0x87, 0x79, 0x3f, 0x4e, 0x10, 0x1e, 0x49, 0x2e, 0x9e, 0x58, 0xc5, - 0x0a, 0xe0, 0x7d, 0xd2, 0x25, 0xa9, 0xb8, 0x96, 0x27, 0xc1, 0xdf, 0x27, 0x60, 0x2e, 0x8e, 0x49, - 0x5a, 0xde, 0xa2, 0xad, 0x85, 0xb8, 0x49, 0x76, 0x40, 0x71, 0xfb, 0xfe, 0xf3, 0x46, 0xcb, 0xb1, - 0x9f, 0x59, 0x6d, 0x91, 0xe5, 0x17, 0x65, 0x71, 0xe9, 0x3f, 0xbf, 0xc7, 0x78, 0x74, 0x70, 0xa3, - 0x67, 0xbc, 0x09, 0xcb, 0x46, 0xab, 0xd3, 0x30, 0x89, 0x61, 0x76, 0x2d, 0x9b, 0x34, 0x7c, 0xd2, - 0x72, 0x6c, 0xd3, 0x2f, 0x4d, 0x31, 0xe3, 0x62, 0xa3, 0xd5, 0xd9, 0x17, 0xa4, 0x43, 0x4e, 0xc1, - 0x75, 0x58, 0xf1, 0x48, 0x60, 0x58, 0x76, 0xc3, 0x68, 0x75, 0x88, 0xd9, 0x88, 0x52, 0x62, 0x66, - 0x15, 0x95, 0x8b, 0xfa, 0xf7, 0x38, 0x71, 0x97, 0xd2, 0x44, 0x16, 0xf8, 0xf8, 0x67, 0xa0, 0x86, - 0x91, 0xee, 0x91, 0x80, 0xd8, 0x54, 0xc7, 0x46, 0xd8, 0x3b, 0x4a, 0x45, 0x86, 0xf9, 0x7c, 0x26, - 0x5b, 0xf7, 0x05, 0x83, 0x5e, 0x12, 0x9b, 0xf5, 0x70, 0x6f, 0x48, 0xc1, 0x7b, 0x51, 0xc9, 0x9f, - 0x65, 0x01, 0x5a, 0xc9, 0x2a, 0x1e, 0xb7, 0xeb, 0x77, 0x5d, 0xf9, 0xff, 0x81, 0x00, 0x06, 0x86, - 0xc5, 0x57, 0x61, 0x9e, 0xf9, 0x82, 0xd8, 0xa6, 0xeb, 0x58, 0x76, 0x98, 0xa0, 0x73, 0x74, 0xf1, - 0xbe, 0x58, 0xc3, 0x8f, 0x24, 0x7d, 0xe0, 0xc6, 0x30, 0x7f, 0x0d, 0x6b, 0x02, 0xaf, 0x5b, 0xa6, - 0x5b, 0xb0, 0xa8, 0x93, 0x16, 0xb1, 0x8e, 0x22, 0x67, 0xe1, 0x15, 0x98, 0xa6, 0x11, 0x61, 0x99, - 0x61, 0x88, 0x1a, 0xad, 0xce, 0x43, 0x13, 0xdf, 0x86, 0x19, 0xe1, 0x05, 0x51, 0x5d, 0x47, 0xd6, - 0xbe, 0x90, 0x5f, 0xfb, 0x01, 0x9c, 0x7d, 0x40, 0x82, 0xb8, 0x1f, 0xc2, 0x6c, 0xd0, 0x60, 0x2e, - 0x9e, 0x5c, 0xa1, 0xbd, 0xe2, 0x6b, 0xda, 0xb7, 0x08, 0xce, 0xf3, 0x06, 0x21, 0x3b, 0x61, 0x4f, - 0x72, 0x82, 0x52, 0xbf, 0x3c, 0x3c, 0x0c, 0x92, 0x12, 0x5e, 0xaf, 0x79, 0xb8, 0x50, 0xa2, 0x65, - 0x45, 0x5a, 0xc4, 0xde, 0x4c, 0xa9, 0xfe, 0x3d, 0x82, 0xf3, 0x12, 0x91, 0xa2, 0x88, 0xed, 0xcb, - 0x8a, 0xd8, 0x68, 0x8b, 0x9c, 0xb2, 0xc8, 0x7d, 0x00, 0xe7, 0x79, 0x91, 0x3b, 0xad, 0x77, 0x7f, - 0x0d, 0xe7, 0x1e, 0x3b, 0xa6, 0xf5, 0xec, 0x38, 0x56, 0x9f, 0x4e, 0xbe, 0x3d, 0x5d, 0xfd, 0x0a, - 0xe3, 0x55, 0x3f, 0xed, 0x4b, 0x04, 0xca, 0x41, 0xbf, 0xdb, 0x1d, 0x47, 0xe4, 0x4d, 0xc0, 0x1e, - 0x09, 0xfa, 0x9e, 0xdd, 0xb0, 0x7a, 0x3d, 0x62, 0x5a, 0x46, 0x40, 0xba, 0xc7, 0x4c, 0x72, 0x51, - 0x3f, 0xc3, 0x29, 0x0f, 0x07, 0x04, 0xbc, 0x06, 0x73, 0x3d, 0xe3, 0xc5, 0xa0, 0x4a, 0x4e, 0x30, - 0x67, 0x2b, 0x3d, 0xe3, 0x45, 0x58, 0x1d, 0xb5, 0x5f, 0xc0, 0x1c, 0x07, 0x21, 0x5c, 0xf8, 0x63, - 0x38, 0xe3, 0x89, 0xa4, 0x1c, 0xec, 0xe3, 0x6e, 0x5c, 0xcb, 0xaa, 0x96, 0xca, 0x5f, 0x7d, 0xc9, - 0x4b, 0x2e, 0xf8, 0x34, 0x60, 0x4a, 0xdc, 0xc8, 0xbb, 0x83, 0x72, 0x3e, 0x8e, 0xca, 0xe7, 0x60, - 0x86, 0x97, 0x04, 0xbf, 0x34, 0xc9, 0x5a, 0xe2, 0x34, 0xab, 0x09, 0x7e, 0x6e, 0xf7, 0x98, 0xc8, - 0xeb, 0x1e, 0xda, 0x4f, 0x00, 0xef, 0xb6, 0x3a, 0xb6, 0xf3, 0xcb, 0x2e, 0x31, 0xdb, 0xa7, 0x05, - 0x51, 0x88, 0x83, 0xd0, 0x7e, 0x53, 0x80, 0xe5, 0xc3, 0xc0, 0x23, 0x46, 0xcf, 0xb2, 0xdb, 0xe3, - 0x7a, 0x33, 0xef, 0x54, 0x7c, 0x0b, 0xce, 0xf5, 0x98, 0xcd, 0x64, 0xda, 0x4d, 0x94, 0xa7, 0xf4, - 0x15, 0x4e, 0x4e, 0xb7, 0xc7, 0xf7, 0xb2, 0xfb, 0x92, 0xb6, 0x5b, 0x4e, 0xee, 0xdb, 0xe5, 0xe2, - 0x76, 0xe0, 0x82, 0xcf, 0x74, 0x68, 0x0c, 0x69, 0xc7, 0x25, 0xce, 0xb2, 0x9b, 0x35, 0x6b, 0x1b, - 0x56, 0x52, 0x26, 0x78, 0x43, 0xb1, 0xf4, 0x11, 0xac, 0xdc, 0xf3, 0x08, 0x2d, 0xc6, 0xb6, 0xe1, - 0xfa, 0xcf, 0x9d, 0x20, 0x34, 0xb6, 0x6c, 0x62, 0x49, 0x3b, 0xa0, 0x20, 0x29, 0x00, 0xaf, 0x10, - 0xac, 0x88, 0xf2, 0x9e, 0x3a, 0xf1, 0x16, 0x14, 0x7d, 0xb1, 0x24, 0xca, 0xba, 0x2a, 0x29, 0x62, - 0xe1, 0xa6, 0x88, 0xf7, 0xf5, 0xca, 0xf9, 0x7f, 0x10, 0x14, 0xc3, 0x33, 0xc7, 0x98, 0xc2, 0xb6, - 0x41, 0x21, 0x2f, 0x5c, 0xcb, 0x23, 0xfc, 0x5b, 0x6b, 0x62, 0xe4, 0xb7, 0x16, 0x70, 0x76, 0xba, - 0x80, 0xef, 0x46, 0x43, 0xcc, 0x24, 0x73, 0xcc, 0xb5, 0x7c, 0x35, 0xbf, 0xeb, 0x01, 0xa6, 0x0b, - 0xcb, 0xac, 0x95, 0x88, 0xe3, 0xdf, 0x70, 0xe7, 0x3a, 0x86, 0x95, 0x94, 0x34, 0x11, 0xa5, 0xef, - 0xc3, 0x6c, 0xe8, 0xbe, 0x30, 0x3a, 0x87, 0xf9, 0x7a, 0xc0, 0x7c, 0xe2, 0x46, 0xf5, 0x2e, 0xac, - 0x88, 0x46, 0x95, 0x8a, 0x32, 0x35, 0x15, 0x65, 0xb3, 0x83, 0x48, 0xd2, 0xfe, 0x80, 0x40, 0x39, - 0x24, 0xa4, 0x33, 0x4e, 0x41, 0xd9, 0x84, 0x49, 0x16, 0x02, 0x85, 0x51, 0x21, 0xf0, 0xe1, 0x5b, - 0x3a, 0xe3, 0xc4, 0x17, 0x63, 0x08, 0x98, 0xc9, 0x3e, 0x7c, 0x6b, 0x80, 0x61, 0xaf, 0x08, 0xd3, - 0x81, 0xe1, 0xb5, 0x49, 0xa0, 0x2d, 0xc0, 0x1c, 0x07, 0xc3, 0x8d, 0x56, 0xff, 0xef, 0x12, 0x80, - 0x68, 0xbb, 0x4d, 0xe2, 0xe1, 0xdf, 0x21, 0xc0, 0x22, 0x35, 0xe3, 0x78, 0x46, 0x34, 0x7e, 0x75, - 0x04, 0x5d, 0xdb, 0xfc, 0xe2, 0x5f, 0xff, 0xfe, 0xa6, 0x50, 0x51, 0xdf, 0xae, 0x1d, 0x6d, 0xd5, - 0x7e, 0x45, 0x53, 0x60, 0x47, 0x84, 0x82, 0x5f, 0xab, 0xd4, 0x12, 0x53, 0x43, 0xad, 0xf2, 0xf2, - 0x0e, 0xaa, 0xe0, 0xaf, 0x11, 0xfb, 0xf6, 0x4f, 0xa0, 0x28, 0x67, 0xa5, 0xc8, 0x47, 0xc2, 0x91, - 0x78, 0xde, 0x63, 0x78, 0x6a, 0xf8, 0x26, 0xc3, 0x13, 0x97, 0x3f, 0x0c, 0x17, 0xfe, 0x73, 0xf4, - 0x9b, 0x21, 0x81, 0xeb, 0x9d, 0xac, 0xb4, 0xdc, 0x59, 0x73, 0x24, 0xb4, 0x1d, 0x06, 0xed, 0xfb, - 0xf5, 0x7a, 0x06, 0x5a, 0xf5, 0x24, 0x76, 0xfb, 0x16, 0xf1, 0xcf, 0xfd, 0xc4, 0x5c, 0x87, 0x25, - 0x5f, 0x34, 0x79, 0xf3, 0xa6, 0xfa, 0xce, 0x89, 0x78, 0x79, 0xf8, 0x68, 0x55, 0x86, 0xb6, 0x8c, - 0xaf, 0x31, 0xb4, 0x02, 0x5b, 0x0c, 0xe3, 0xcb, 0x24, 0x48, 0xfc, 0x47, 0x14, 0x7e, 0xd0, 0x8e, - 0xb2, 0x60, 0xee, 0x44, 0xa8, 0x9e, 0xcd, 0xa4, 0xc3, 0xfd, 0x9e, 0x1b, 0x1c, 0x87, 0x4e, 0xad, - 0x8c, 0xe9, 0xd4, 0xbf, 0x20, 0x38, 0x93, 0x19, 0x6c, 0x64, 0x16, 0xcb, 0x9b, 0x7e, 0x72, 0x01, - 0xfd, 0x88, 0x01, 0xda, 0xd7, 0x3e, 0x18, 0x0b, 0xd0, 0x9d, 0x5e, 0x5a, 0x0e, 0xf5, 0xeb, 0x57, - 0x08, 0x94, 0xd8, 0xcc, 0x83, 0xd7, 0xb3, 0xf8, 0xb2, 0x23, 0x51, 0x2e, 0xb2, 0x7d, 0x86, 0xec, - 0xae, 0x76, 0x7b, 0x3c, 0x64, 0xc6, 0x40, 0x02, 0xc5, 0xf4, 0x5b, 0x04, 0x93, 0x74, 0x4e, 0xc0, - 0x97, 0x64, 0xb3, 0x72, 0x34, 0x42, 0xc9, 0x42, 0x3e, 0x3e, 0x5e, 0x84, 0x21, 0xaf, 0xd5, 0xc7, - 0x43, 0xe3, 0xf6, 0xbb, 0x5d, 0x0a, 0xc3, 0x84, 0xf9, 0xc4, 0xd8, 0x82, 0x65, 0xad, 0x4f, 0x32, - 0xda, 0xa9, 0x1b, 0x23, 0xf9, 0x38, 0xc0, 0x32, 0xda, 0x44, 0x34, 0xf7, 0x97, 0xd2, 0x1f, 0x19, - 0xf8, 0x7a, 0x5e, 0x94, 0x64, 0x3e, 0x44, 0x72, 0x5d, 0xf1, 0x90, 0x29, 0x7f, 0x4f, 0xbb, 0x7b, - 0x9a, 0x20, 0x19, 0x88, 0xa1, 0x86, 0x78, 0x85, 0x60, 0x3e, 0xd1, 0x1a, 0x65, 0x96, 0x90, 0x75, - 0x6a, 0x99, 0x25, 0xa4, 0x3d, 0x56, 0xab, 0x30, 0xb4, 0xeb, 0x58, 0xcb, 0xcf, 0xf7, 0x48, 0xf8, - 0x97, 0x08, 0x16, 0x92, 0x63, 0x1e, 0x96, 0xc8, 0x91, 0x0e, 0x82, 0xea, 0x90, 0xc6, 0xad, 0xdd, - 0x60, 0x18, 0xae, 0xa9, 0x6b, 0xf2, 0x66, 0x12, 0xca, 0x17, 0x05, 0xf1, 0x15, 0x82, 0x85, 0xe4, - 0x68, 0x28, 0x43, 0x21, 0x1d, 0x1e, 0x87, 0xa2, 0x10, 0xd5, 0xa6, 0x5e, 0xe1, 0x7e, 0x0b, 0x47, - 0xab, 0x51, 0x70, 0x3e, 0x47, 0xb0, 0x90, 0x9c, 0x21, 0x64, 0x70, 0xa4, 0x53, 0x46, 0x6e, 0x08, - 0xdd, 0x64, 0x50, 0x36, 0x2a, 0x6f, 0x27, 0xa0, 0xe4, 0xa1, 0x60, 0x69, 0x4b, 0x67, 0x00, 0x59, - 0xda, 0xc6, 0x06, 0x15, 0x69, 0xa7, 0x8a, 0x8d, 0x0e, 0xa7, 0x4d, 0x5b, 0x9f, 0x90, 0xce, 0x1d, - 0x54, 0xa9, 0xff, 0x69, 0x06, 0x66, 0xc5, 0xcf, 0x6c, 0xe2, 0xe1, 0x4f, 0x40, 0xe1, 0x91, 0xc0, - 0x6f, 0x66, 0xf2, 0xfe, 0x11, 0xab, 0x79, 0x04, 0xed, 0x3a, 0x43, 0x73, 0x55, 0xbd, 0x2c, 0x8d, - 0x0a, 0xfe, 0x67, 0x59, 0xf8, 0xe0, 0x25, 0x28, 0xb1, 0xcb, 0x02, 0x59, 0x29, 0xcd, 0xde, 0x25, - 0xe4, 0x0b, 0xae, 0x31, 0xc1, 0xd7, 0xeb, 0xeb, 0x4c, 0x30, 0x13, 0x54, 0x1d, 0x2a, 0xfe, 0x0b, - 0x04, 0x33, 0x42, 0x71, 0xbc, 0x2a, 0xfd, 0xff, 0x15, 0xbb, 0x45, 0x50, 0xd7, 0x86, 0x70, 0x08, - 0x47, 0xd4, 0x19, 0x82, 0x1b, 0xda, 0xc6, 0x00, 0x81, 0x5c, 0xb8, 0xb8, 0x9a, 0xa1, 0x20, 0x1c, - 0x28, 0x86, 0x57, 0x2b, 0x78, 0x4d, 0x3a, 0x57, 0x9d, 0x4c, 0xfb, 0x0d, 0x26, 0x7b, 0x0d, 0x5f, - 0x19, 0x21, 0x9b, 0x06, 0x3e, 0x0c, 0x2e, 0x07, 0xf0, 0x55, 0x79, 0xc5, 0x49, 0xdc, 0x52, 0xa8, - 0xeb, 0xc3, 0x99, 0x84, 0xfa, 0x49, 0x08, 0xb2, 0x9a, 0x24, 0xee, 0x15, 0xfe, 0x86, 0xe0, 0xac, - 0xfc, 0xef, 0x3d, 0xae, 0x0d, 0x91, 0x24, 0x9d, 0x92, 0x36, 0x4f, 0xbe, 0x41, 0xc0, 0x4c, 0xce, - 0x9c, 0xf9, 0x96, 0x4a, 0x4d, 0x4c, 0x01, 0x28, 0xb1, 0x1b, 0x00, 0x59, 0xb0, 0x66, 0x2f, 0x08, - 0x72, 0x2b, 0x85, 0x30, 0x55, 0x65, 0x94, 0xb7, 0xf6, 0xbe, 0x46, 0xb0, 0xdc, 0x72, 0x7a, 0x19, - 0x61, 0x7b, 0x0a, 0xff, 0x3d, 0x7b, 0x40, 0xcf, 0x3d, 0x40, 0x3f, 0xbf, 0x25, 0x18, 0xda, 0x4e, - 0xd7, 0xb0, 0xdb, 0x55, 0xc7, 0x6b, 0xd7, 0xda, 0xc4, 0x66, 0x52, 0x6b, 0x9c, 0x64, 0xb8, 0x96, - 0x3f, 0xb8, 0x39, 0xde, 0xe6, 0x4f, 0xff, 0x43, 0xe8, 0xaf, 0x85, 0xb3, 0x0f, 0xf8, 0xde, 0x7b, - 0x5d, 0xa7, 0x6f, 0xd2, 0xa0, 0x3e, 0xec, 0x37, 0xab, 0x1f, 0x6f, 0xfd, 0x33, 0x24, 0x3c, 0x65, - 0x84, 0xa7, 0x9c, 0xf0, 0xf4, 0xe3, 0xad, 0xe6, 0x34, 0x3b, 0xf7, 0xdd, 0xff, 0x07, 0x00, 0x00, - 0xff, 0xff, 0xcb, 0xe1, 0xb8, 0xca, 0x90, 0x1e, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go b/vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go deleted file mode 100644 index fb104e6dfb8..00000000000 --- a/vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go +++ /dev/null @@ -1,156 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/rpc/status.proto - -package status // import "google.golang.org/genproto/googleapis/rpc/status" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import any "github.com/golang/protobuf/ptypes/any" - -// 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 `Status` type defines a logical error model that is suitable for different -// programming environments, including REST APIs and RPC APIs. It is used by -// [gRPC](https://github.com/grpc). The error model is designed to be: -// -// - Simple to use and understand for most users -// - Flexible enough to meet unexpected needs -// -// # Overview -// -// The `Status` message contains three pieces of data: error code, error message, -// and error details. The error code should be an enum value of -// [google.rpc.Code][google.rpc.Code], but it may accept additional error codes if needed. The -// error message should be a developer-facing English message that helps -// developers *understand* and *resolve* the error. If a localized user-facing -// error message is needed, put the localized message in the error details or -// localize it in the client. The optional error details may contain arbitrary -// information about the error. There is a predefined set of error detail types -// in the package `google.rpc` that can be used for common error conditions. -// -// # Language mapping -// -// The `Status` message is the logical representation of the error model, but it -// is not necessarily the actual wire format. When the `Status` message is -// exposed in different client libraries and different wire protocols, it can be -// mapped differently. For example, it will likely be mapped to some exceptions -// in Java, but more likely mapped to some error codes in C. -// -// # Other uses -// -// The error model and the `Status` message can be used in a variety of -// environments, either with or without APIs, to provide a -// consistent developer experience across different environments. -// -// Example uses of this error model include: -// -// - Partial errors. If a service needs to return partial errors to the client, -// it may embed the `Status` in the normal response to indicate the partial -// errors. -// -// - Workflow errors. A typical workflow has multiple steps. Each step may -// have a `Status` message for error reporting. -// -// - Batch operations. If a client uses batch request and batch response, the -// `Status` message should be used directly inside batch response, one for -// each error sub-response. -// -// - Asynchronous operations. If an API call embeds asynchronous operation -// results in its response, the status of those operations should be -// represented directly using the `Status` message. -// -// - Logging. If some API errors are stored in logs, the message `Status` could -// be used directly after any stripping needed for security/privacy reasons. -type Status struct { - // The status code, which should be an enum value of [google.rpc.Code][google.rpc.Code]. - Code int32 `protobuf:"varint,1,opt,name=code" json:"code,omitempty"` - // A developer-facing error message, which should be in English. Any - // user-facing error message should be localized and sent in the - // [google.rpc.Status.details][google.rpc.Status.details] field, or localized by the client. - Message string `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"` - // A list of messages that carry the error details. There is a common set of - // message types for APIs to use. - Details []*any.Any `protobuf:"bytes,3,rep,name=details" json:"details,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Status) Reset() { *m = Status{} } -func (m *Status) String() string { return proto.CompactTextString(m) } -func (*Status) ProtoMessage() {} -func (*Status) Descriptor() ([]byte, []int) { - return fileDescriptor_status_c656c685916bdf47, []int{0} -} -func (m *Status) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Status.Unmarshal(m, b) -} -func (m *Status) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Status.Marshal(b, m, deterministic) -} -func (dst *Status) XXX_Merge(src proto.Message) { - xxx_messageInfo_Status.Merge(dst, src) -} -func (m *Status) XXX_Size() int { - return xxx_messageInfo_Status.Size(m) -} -func (m *Status) XXX_DiscardUnknown() { - xxx_messageInfo_Status.DiscardUnknown(m) -} - -var xxx_messageInfo_Status proto.InternalMessageInfo - -func (m *Status) GetCode() int32 { - if m != nil { - return m.Code - } - return 0 -} - -func (m *Status) GetMessage() string { - if m != nil { - return m.Message - } - return "" -} - -func (m *Status) GetDetails() []*any.Any { - if m != nil { - return m.Details - } - return nil -} - -func init() { - proto.RegisterType((*Status)(nil), "google.rpc.Status") -} - -func init() { proto.RegisterFile("google/rpc/status.proto", fileDescriptor_status_c656c685916bdf47) } - -var fileDescriptor_status_c656c685916bdf47 = []byte{ - // 209 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4f, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0x2a, 0x48, 0xd6, 0x2f, 0x2e, 0x49, 0x2c, 0x29, 0x2d, 0xd6, 0x2b, 0x28, - 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x82, 0x48, 0xe8, 0x15, 0x15, 0x24, 0x4b, 0x49, 0x42, 0x15, 0x81, - 0x65, 0x92, 0x4a, 0xd3, 0xf4, 0x13, 0xf3, 0x2a, 0x21, 0xca, 0x94, 0xd2, 0xb8, 0xd8, 0x82, 0xc1, - 0xda, 0x84, 0x84, 0xb8, 0x58, 0x92, 0xf3, 0x53, 0x52, 0x25, 0x18, 0x15, 0x18, 0x35, 0x58, 0x83, - 0xc0, 0x6c, 0x21, 0x09, 0x2e, 0xf6, 0xdc, 0xd4, 0xe2, 0xe2, 0xc4, 0xf4, 0x54, 0x09, 0x26, 0x05, - 0x46, 0x0d, 0xce, 0x20, 0x18, 0x57, 0x48, 0x8f, 0x8b, 0x3d, 0x25, 0xb5, 0x24, 0x31, 0x33, 0xa7, - 0x58, 0x82, 0x59, 0x81, 0x59, 0x83, 0xdb, 0x48, 0x44, 0x0f, 0x6a, 0x21, 0xcc, 0x12, 0x3d, 0xc7, - 0xbc, 0xca, 0x20, 0x98, 0x22, 0xa7, 0x38, 0x2e, 0xbe, 0xe4, 0xfc, 0x5c, 0x3d, 0x84, 0xa3, 0x9c, - 0xb8, 0x21, 0xf6, 0x06, 0x80, 0x94, 0x07, 0x30, 0x46, 0x99, 0x43, 0xa5, 0xd2, 0xf3, 0x73, 0x12, - 0xf3, 0xd2, 0xf5, 0xf2, 0x8b, 0xd2, 0xf5, 0xd3, 0x53, 0xf3, 0xc0, 0x86, 0xe9, 0x43, 0xa4, 0x12, - 0x0b, 0x32, 0x8b, 0x91, 0xfc, 0x69, 0x0d, 0xa1, 0x16, 0x31, 0x31, 0x07, 0x05, 0x38, 0x27, 0xb1, - 0x81, 0x55, 0x1a, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xa4, 0x53, 0xf0, 0x7c, 0x10, 0x01, 0x00, - 0x00, -} diff --git a/vendor/google.golang.org/genproto/protobuf/field_mask/field_mask.pb.go b/vendor/google.golang.org/genproto/protobuf/field_mask/field_mask.pb.go deleted file mode 100644 index ace751f68d1..00000000000 --- a/vendor/google.golang.org/genproto/protobuf/field_mask/field_mask.pb.go +++ /dev/null @@ -1,288 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/field_mask.proto - -package field_mask // import "google.golang.org/genproto/protobuf/field_mask" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// 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 - -// `FieldMask` represents a set of symbolic field paths, for example: -// -// paths: "f.a" -// paths: "f.b.d" -// -// Here `f` represents a field in some root message, `a` and `b` -// fields in the message found in `f`, and `d` a field found in the -// message in `f.b`. -// -// Field masks are used to specify a subset of fields that should be -// returned by a get operation or modified by an update operation. -// Field masks also have a custom JSON encoding (see below). -// -// # Field Masks in Projections -// -// When used in the context of a projection, a response message or -// sub-message is filtered by the API to only contain those fields as -// specified in the mask. For example, if the mask in the previous -// example is applied to a response message as follows: -// -// f { -// a : 22 -// b { -// d : 1 -// x : 2 -// } -// y : 13 -// } -// z: 8 -// -// The result will not contain specific values for fields x,y and z -// (their value will be set to the default, and omitted in proto text -// output): -// -// -// f { -// a : 22 -// b { -// d : 1 -// } -// } -// -// A repeated field is not allowed except at the last position of a -// paths string. -// -// If a FieldMask object is not present in a get operation, the -// operation applies to all fields (as if a FieldMask of all fields -// had been specified). -// -// Note that a field mask does not necessarily apply to the -// top-level response message. In case of a REST get operation, the -// field mask applies directly to the response, but in case of a REST -// list operation, the mask instead applies to each individual message -// in the returned resource list. In case of a REST custom method, -// other definitions may be used. Where the mask applies will be -// clearly documented together with its declaration in the API. In -// any case, the effect on the returned resource/resources is required -// behavior for APIs. -// -// # Field Masks in Update Operations -// -// A field mask in update operations specifies which fields of the -// targeted resource are going to be updated. The API is required -// to only change the values of the fields as specified in the mask -// and leave the others untouched. If a resource is passed in to -// describe the updated values, the API ignores the values of all -// fields not covered by the mask. -// -// If a repeated field is specified for an update operation, the existing -// repeated values in the target resource will be overwritten by the new values. -// Note that a repeated field is only allowed in the last position of a `paths` -// string. -// -// If a sub-message is specified in the last position of the field mask for an -// update operation, then the existing sub-message in the target resource is -// overwritten. Given the target message: -// -// f { -// b { -// d : 1 -// x : 2 -// } -// c : 1 -// } -// -// And an update message: -// -// f { -// b { -// d : 10 -// } -// } -// -// then if the field mask is: -// -// paths: "f.b" -// -// then the result will be: -// -// f { -// b { -// d : 10 -// } -// c : 1 -// } -// -// However, if the update mask was: -// -// paths: "f.b.d" -// -// then the result would be: -// -// f { -// b { -// d : 10 -// x : 2 -// } -// c : 1 -// } -// -// In order to reset a field's value to the default, the field must -// be in the mask and set to the default value in the provided resource. -// Hence, in order to reset all fields of a resource, provide a default -// instance of the resource and set all fields in the mask, or do -// not provide a mask as described below. -// -// If a field mask is not present on update, the operation applies to -// all fields (as if a field mask of all fields has been specified). -// Note that in the presence of schema evolution, this may mean that -// fields the client does not know and has therefore not filled into -// the request will be reset to their default. If this is unwanted -// behavior, a specific service may require a client to always specify -// a field mask, producing an error if not. -// -// As with get operations, the location of the resource which -// describes the updated values in the request message depends on the -// operation kind. In any case, the effect of the field mask is -// required to be honored by the API. -// -// ## Considerations for HTTP REST -// -// The HTTP kind of an update operation which uses a field mask must -// be set to PATCH instead of PUT in order to satisfy HTTP semantics -// (PUT must only be used for full updates). -// -// # JSON Encoding of Field Masks -// -// In JSON, a field mask is encoded as a single string where paths are -// separated by a comma. Fields name in each path are converted -// to/from lower-camel naming conventions. -// -// As an example, consider the following message declarations: -// -// message Profile { -// User user = 1; -// Photo photo = 2; -// } -// message User { -// string display_name = 1; -// string address = 2; -// } -// -// In proto a field mask for `Profile` may look as such: -// -// mask { -// paths: "user.display_name" -// paths: "photo" -// } -// -// In JSON, the same mask is represented as below: -// -// { -// mask: "user.displayName,photo" -// } -// -// # Field Masks and Oneof Fields -// -// Field masks treat fields in oneofs just as regular fields. Consider the -// following message: -// -// message SampleMessage { -// oneof test_oneof { -// string name = 4; -// SubMessage sub_message = 9; -// } -// } -// -// The field mask can be: -// -// mask { -// paths: "name" -// } -// -// Or: -// -// mask { -// paths: "sub_message" -// } -// -// Note that oneof type names ("test_oneof" in this case) cannot be used in -// paths. -// -// ## Field Mask Verification -// -// The implementation of any API method which has a FieldMask type field in the -// request should verify the included field paths, and return an -// `INVALID_ARGUMENT` error if any path is duplicated or unmappable. -type FieldMask struct { - // The set of field mask paths. - Paths []string `protobuf:"bytes,1,rep,name=paths" json:"paths,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FieldMask) Reset() { *m = FieldMask{} } -func (m *FieldMask) String() string { return proto.CompactTextString(m) } -func (*FieldMask) ProtoMessage() {} -func (*FieldMask) Descriptor() ([]byte, []int) { - return fileDescriptor_field_mask_56ec45e1ddac5c77, []int{0} -} -func (m *FieldMask) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FieldMask.Unmarshal(m, b) -} -func (m *FieldMask) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FieldMask.Marshal(b, m, deterministic) -} -func (dst *FieldMask) XXX_Merge(src proto.Message) { - xxx_messageInfo_FieldMask.Merge(dst, src) -} -func (m *FieldMask) XXX_Size() int { - return xxx_messageInfo_FieldMask.Size(m) -} -func (m *FieldMask) XXX_DiscardUnknown() { - xxx_messageInfo_FieldMask.DiscardUnknown(m) -} - -var xxx_messageInfo_FieldMask proto.InternalMessageInfo - -func (m *FieldMask) GetPaths() []string { - if m != nil { - return m.Paths - } - return nil -} - -func init() { - proto.RegisterType((*FieldMask)(nil), "google.protobuf.FieldMask") -} - -func init() { - proto.RegisterFile("google/protobuf/field_mask.proto", fileDescriptor_field_mask_56ec45e1ddac5c77) -} - -var fileDescriptor_field_mask_56ec45e1ddac5c77 = []byte{ - // 171 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x48, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcb, 0x4c, 0xcd, - 0x49, 0x89, 0xcf, 0x4d, 0x2c, 0xce, 0xd6, 0x03, 0x8b, 0x09, 0xf1, 0x43, 0x54, 0xe8, 0xc1, 0x54, - 0x28, 0x29, 0x72, 0x71, 0xba, 0x81, 0x14, 0xf9, 0x26, 0x16, 0x67, 0x0b, 0x89, 0x70, 0xb1, 0x16, - 0x24, 0x96, 0x64, 0x14, 0x4b, 0x30, 0x2a, 0x30, 0x6b, 0x70, 0x06, 0x41, 0x38, 0x4e, 0x9d, 0x8c, - 0x5c, 0xc2, 0xc9, 0xf9, 0xb9, 0x7a, 0x68, 0x5a, 0x9d, 0xf8, 0xe0, 0x1a, 0x03, 0x40, 0x42, 0x01, - 0x8c, 0x51, 0x96, 0x50, 0x25, 0xe9, 0xf9, 0x39, 0x89, 0x79, 0xe9, 0x7a, 0xf9, 0x45, 0xe9, 0xfa, - 0xe9, 0xa9, 0x79, 0x60, 0x0d, 0xd8, 0xdc, 0x64, 0x8d, 0x60, 0x2e, 0x62, 0x62, 0x76, 0x0f, 0x70, - 0x5a, 0xc5, 0x24, 0xe7, 0x0e, 0x31, 0x21, 0x00, 0xaa, 0x5a, 0x2f, 0x3c, 0x35, 0x27, 0xc7, 0x3b, - 0x2f, 0xbf, 0x3c, 0x2f, 0xa4, 0xb2, 0x20, 0xb5, 0x38, 0x89, 0x0d, 0x6c, 0x8c, 0x31, 0x20, 0x00, - 0x00, 0xff, 0xff, 0x5a, 0xdb, 0x3a, 0xc0, 0xea, 0x00, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/AUTHORS b/vendor/google.golang.org/grpc/AUTHORS deleted file mode 100644 index e491a9e7f78..00000000000 --- a/vendor/google.golang.org/grpc/AUTHORS +++ /dev/null @@ -1 +0,0 @@ -Google Inc. diff --git a/vendor/google.golang.org/grpc/backoff.go b/vendor/google.golang.org/grpc/backoff.go deleted file mode 100644 index c40facce510..00000000000 --- a/vendor/google.golang.org/grpc/backoff.go +++ /dev/null @@ -1,96 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 grpc - -import ( - "math/rand" - "time" -) - -// DefaultBackoffConfig uses values specified for backoff in -// https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. -var DefaultBackoffConfig = BackoffConfig{ - MaxDelay: 120 * time.Second, - baseDelay: 1.0 * time.Second, - factor: 1.6, - jitter: 0.2, -} - -// backoffStrategy defines the methodology for backing off after a grpc -// connection failure. -// -// This is unexported until the gRPC project decides whether or not to allow -// alternative backoff strategies. Once a decision is made, this type and its -// method may be exported. -type backoffStrategy interface { - // backoff returns the amount of time to wait before the next retry given - // the number of consecutive failures. - backoff(retries int) time.Duration -} - -// BackoffConfig defines the parameters for the default gRPC backoff strategy. -type BackoffConfig struct { - // MaxDelay is the upper bound of backoff delay. - MaxDelay time.Duration - - // TODO(stevvooe): The following fields are not exported, as allowing - // changes would violate the current gRPC specification for backoff. If - // gRPC decides to allow more interesting backoff strategies, these fields - // may be opened up in the future. - - // baseDelay is the amount of time to wait before retrying after the first - // failure. - baseDelay time.Duration - - // factor is applied to the backoff after each retry. - factor float64 - - // jitter provides a range to randomize backoff delays. - jitter float64 -} - -func setDefaults(bc *BackoffConfig) { - md := bc.MaxDelay - *bc = DefaultBackoffConfig - - if md > 0 { - bc.MaxDelay = md - } -} - -func (bc BackoffConfig) backoff(retries int) time.Duration { - if retries == 0 { - return bc.baseDelay - } - backoff, max := float64(bc.baseDelay), float64(bc.MaxDelay) - for backoff < max && retries > 0 { - backoff *= bc.factor - retries-- - } - if backoff > max { - backoff = max - } - // Randomize backoff delays so that if a cluster of requests start at - // the same time, they won't operate in lockstep. - backoff *= 1 + bc.jitter*(rand.Float64()*2-1) - if backoff < 0 { - return 0 - } - return time.Duration(backoff) -} diff --git a/vendor/google.golang.org/grpc/balancer.go b/vendor/google.golang.org/grpc/balancer.go deleted file mode 100644 index e1730166cde..00000000000 --- a/vendor/google.golang.org/grpc/balancer.go +++ /dev/null @@ -1,416 +0,0 @@ -/* - * - * Copyright 2016 gRPC 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 grpc - -import ( - "fmt" - "net" - "sync" - - "golang.org/x/net/context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/naming" - "google.golang.org/grpc/status" -) - -// Address represents a server the client connects to. -// -// Deprecated: please use package balancer. -type Address struct { - // Addr is the server address on which a connection will be established. - Addr string - // Metadata is the information associated with Addr, which may be used - // to make load balancing decision. - Metadata interface{} -} - -// BalancerConfig specifies the configurations for Balancer. -// -// Deprecated: please use package balancer. -type BalancerConfig struct { - // DialCreds is the transport credential the Balancer implementation can - // use to dial to a remote load balancer server. The Balancer implementations - // can ignore this if it does not need to talk to another party securely. - DialCreds credentials.TransportCredentials - // Dialer is the custom dialer the Balancer implementation can use to dial - // to a remote load balancer server. The Balancer implementations - // can ignore this if it doesn't need to talk to remote balancer. - Dialer func(context.Context, string) (net.Conn, error) -} - -// BalancerGetOptions configures a Get call. -// -// Deprecated: please use package balancer. -type BalancerGetOptions struct { - // BlockingWait specifies whether Get should block when there is no - // connected address. - BlockingWait bool -} - -// Balancer chooses network addresses for RPCs. -// -// Deprecated: please use package balancer. -type Balancer interface { - // Start does the initialization work to bootstrap a Balancer. For example, - // this function may start the name resolution and watch the updates. It will - // be called when dialing. - Start(target string, config BalancerConfig) error - // Up informs the Balancer that gRPC has a connection to the server at - // addr. It returns down which is called once the connection to addr gets - // lost or closed. - // TODO: It is not clear how to construct and take advantage of the meaningful error - // parameter for down. Need realistic demands to guide. - Up(addr Address) (down func(error)) - // Get gets the address of a server for the RPC corresponding to ctx. - // i) If it returns a connected address, gRPC internals issues the RPC on the - // connection to this address; - // ii) If it returns an address on which the connection is under construction - // (initiated by Notify(...)) but not connected, gRPC internals - // * fails RPC if the RPC is fail-fast and connection is in the TransientFailure or - // Shutdown state; - // or - // * issues RPC on the connection otherwise. - // iii) If it returns an address on which the connection does not exist, gRPC - // internals treats it as an error and will fail the corresponding RPC. - // - // Therefore, the following is the recommended rule when writing a custom Balancer. - // If opts.BlockingWait is true, it should return a connected address or - // block if there is no connected address. It should respect the timeout or - // cancellation of ctx when blocking. If opts.BlockingWait is false (for fail-fast - // RPCs), it should return an address it has notified via Notify(...) immediately - // instead of blocking. - // - // The function returns put which is called once the rpc has completed or failed. - // put can collect and report RPC stats to a remote load balancer. - // - // This function should only return the errors Balancer cannot recover by itself. - // gRPC internals will fail the RPC if an error is returned. - Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) - // Notify returns a channel that is used by gRPC internals to watch the addresses - // gRPC needs to connect. The addresses might be from a name resolver or remote - // load balancer. gRPC internals will compare it with the existing connected - // addresses. If the address Balancer notified is not in the existing connected - // addresses, gRPC starts to connect the address. If an address in the existing - // connected addresses is not in the notification list, the corresponding connection - // is shutdown gracefully. Otherwise, there are no operations to take. Note that - // the Address slice must be the full list of the Addresses which should be connected. - // It is NOT delta. - Notify() <-chan []Address - // Close shuts down the balancer. - Close() error -} - -// downErr implements net.Error. It is constructed by gRPC internals and passed to the down -// call of Balancer. -type downErr struct { - timeout bool - temporary bool - desc string -} - -func (e downErr) Error() string { return e.desc } -func (e downErr) Timeout() bool { return e.timeout } -func (e downErr) Temporary() bool { return e.temporary } - -func downErrorf(timeout, temporary bool, format string, a ...interface{}) downErr { - return downErr{ - timeout: timeout, - temporary: temporary, - desc: fmt.Sprintf(format, a...), - } -} - -// RoundRobin returns a Balancer that selects addresses round-robin. It uses r to watch -// the name resolution updates and updates the addresses available correspondingly. -// -// Deprecated: please use package balancer/roundrobin. -func RoundRobin(r naming.Resolver) Balancer { - return &roundRobin{r: r} -} - -type addrInfo struct { - addr Address - connected bool -} - -type roundRobin struct { - r naming.Resolver - w naming.Watcher - addrs []*addrInfo // all the addresses the client should potentially connect - mu sync.Mutex - addrCh chan []Address // the channel to notify gRPC internals the list of addresses the client should connect to. - next int // index of the next address to return for Get() - waitCh chan struct{} // the channel to block when there is no connected address available - done bool // The Balancer is closed. -} - -func (rr *roundRobin) watchAddrUpdates() error { - updates, err := rr.w.Next() - if err != nil { - grpclog.Warningf("grpc: the naming watcher stops working due to %v.", err) - return err - } - rr.mu.Lock() - defer rr.mu.Unlock() - for _, update := range updates { - addr := Address{ - Addr: update.Addr, - Metadata: update.Metadata, - } - switch update.Op { - case naming.Add: - var exist bool - for _, v := range rr.addrs { - if addr == v.addr { - exist = true - grpclog.Infoln("grpc: The name resolver wanted to add an existing address: ", addr) - break - } - } - if exist { - continue - } - rr.addrs = append(rr.addrs, &addrInfo{addr: addr}) - case naming.Delete: - for i, v := range rr.addrs { - if addr == v.addr { - copy(rr.addrs[i:], rr.addrs[i+1:]) - rr.addrs = rr.addrs[:len(rr.addrs)-1] - break - } - } - default: - grpclog.Errorln("Unknown update.Op ", update.Op) - } - } - // Make a copy of rr.addrs and write it onto rr.addrCh so that gRPC internals gets notified. - open := make([]Address, len(rr.addrs)) - for i, v := range rr.addrs { - open[i] = v.addr - } - if rr.done { - return ErrClientConnClosing - } - select { - case <-rr.addrCh: - default: - } - rr.addrCh <- open - return nil -} - -func (rr *roundRobin) Start(target string, config BalancerConfig) error { - rr.mu.Lock() - defer rr.mu.Unlock() - if rr.done { - return ErrClientConnClosing - } - if rr.r == nil { - // If there is no name resolver installed, it is not needed to - // do name resolution. In this case, target is added into rr.addrs - // as the only address available and rr.addrCh stays nil. - rr.addrs = append(rr.addrs, &addrInfo{addr: Address{Addr: target}}) - return nil - } - w, err := rr.r.Resolve(target) - if err != nil { - return err - } - rr.w = w - rr.addrCh = make(chan []Address, 1) - go func() { - for { - if err := rr.watchAddrUpdates(); err != nil { - return - } - } - }() - return nil -} - -// Up sets the connected state of addr and sends notification if there are pending -// Get() calls. -func (rr *roundRobin) Up(addr Address) func(error) { - rr.mu.Lock() - defer rr.mu.Unlock() - var cnt int - for _, a := range rr.addrs { - if a.addr == addr { - if a.connected { - return nil - } - a.connected = true - } - if a.connected { - cnt++ - } - } - // addr is only one which is connected. Notify the Get() callers who are blocking. - if cnt == 1 && rr.waitCh != nil { - close(rr.waitCh) - rr.waitCh = nil - } - return func(err error) { - rr.down(addr, err) - } -} - -// down unsets the connected state of addr. -func (rr *roundRobin) down(addr Address, err error) { - rr.mu.Lock() - defer rr.mu.Unlock() - for _, a := range rr.addrs { - if addr == a.addr { - a.connected = false - break - } - } -} - -// Get returns the next addr in the rotation. -func (rr *roundRobin) Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) { - var ch chan struct{} - rr.mu.Lock() - if rr.done { - rr.mu.Unlock() - err = ErrClientConnClosing - return - } - - if len(rr.addrs) > 0 { - if rr.next >= len(rr.addrs) { - rr.next = 0 - } - next := rr.next - for { - a := rr.addrs[next] - next = (next + 1) % len(rr.addrs) - if a.connected { - addr = a.addr - rr.next = next - rr.mu.Unlock() - return - } - if next == rr.next { - // Has iterated all the possible address but none is connected. - break - } - } - } - if !opts.BlockingWait { - if len(rr.addrs) == 0 { - rr.mu.Unlock() - err = status.Errorf(codes.Unavailable, "there is no address available") - return - } - // Returns the next addr on rr.addrs for failfast RPCs. - addr = rr.addrs[rr.next].addr - rr.next++ - rr.mu.Unlock() - return - } - // Wait on rr.waitCh for non-failfast RPCs. - if rr.waitCh == nil { - ch = make(chan struct{}) - rr.waitCh = ch - } else { - ch = rr.waitCh - } - rr.mu.Unlock() - for { - select { - case <-ctx.Done(): - err = ctx.Err() - return - case <-ch: - rr.mu.Lock() - if rr.done { - rr.mu.Unlock() - err = ErrClientConnClosing - return - } - - if len(rr.addrs) > 0 { - if rr.next >= len(rr.addrs) { - rr.next = 0 - } - next := rr.next - for { - a := rr.addrs[next] - next = (next + 1) % len(rr.addrs) - if a.connected { - addr = a.addr - rr.next = next - rr.mu.Unlock() - return - } - if next == rr.next { - // Has iterated all the possible address but none is connected. - break - } - } - } - // The newly added addr got removed by Down() again. - if rr.waitCh == nil { - ch = make(chan struct{}) - rr.waitCh = ch - } else { - ch = rr.waitCh - } - rr.mu.Unlock() - } - } -} - -func (rr *roundRobin) Notify() <-chan []Address { - return rr.addrCh -} - -func (rr *roundRobin) Close() error { - rr.mu.Lock() - defer rr.mu.Unlock() - if rr.done { - return errBalancerClosed - } - rr.done = true - if rr.w != nil { - rr.w.Close() - } - if rr.waitCh != nil { - close(rr.waitCh) - rr.waitCh = nil - } - if rr.addrCh != nil { - close(rr.addrCh) - } - return nil -} - -// pickFirst is used to test multi-addresses in one addrConn in which all addresses share the same addrConn. -// It is a wrapper around roundRobin balancer. The logic of all methods works fine because balancer.Get() -// returns the only address Up by resetTransport(). -type pickFirst struct { - *roundRobin -} - -func pickFirstBalancerV1(r naming.Resolver) Balancer { - return &pickFirst{&roundRobin{r: r}} -} diff --git a/vendor/google.golang.org/grpc/balancer/balancer.go b/vendor/google.golang.org/grpc/balancer/balancer.go deleted file mode 100644 index 63b8d71371e..00000000000 --- a/vendor/google.golang.org/grpc/balancer/balancer.go +++ /dev/null @@ -1,228 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 balancer defines APIs for load balancing in gRPC. -// All APIs in this package are experimental. -package balancer - -import ( - "errors" - "net" - "strings" - - "golang.org/x/net/context" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/resolver" -) - -var ( - // m is a map from name to balancer builder. - m = make(map[string]Builder) -) - -// Register registers the balancer builder to the balancer map. b.Name -// (lowercased) will be used as the name registered with this builder. -// -// NOTE: this function must only be called during initialization time (i.e. in -// an init() function), and is not thread-safe. If multiple Balancers are -// registered with the same name, the one registered last will take effect. -func Register(b Builder) { - m[strings.ToLower(b.Name())] = b -} - -// Get returns the resolver builder registered with the given name. -// Note that the compare is done in a case-insenstive fashion. -// If no builder is register with the name, nil will be returned. -func Get(name string) Builder { - if b, ok := m[strings.ToLower(name)]; ok { - return b - } - return nil -} - -// SubConn represents a gRPC sub connection. -// Each sub connection contains a list of addresses. gRPC will -// try to connect to them (in sequence), and stop trying the -// remainder once one connection is successful. -// -// The reconnect backoff will be applied on the list, not a single address. -// For example, try_on_all_addresses -> backoff -> try_on_all_addresses. -// -// All SubConns start in IDLE, and will not try to connect. To trigger -// the connecting, Balancers must call Connect. -// When the connection encounters an error, it will reconnect immediately. -// When the connection becomes IDLE, it will not reconnect unless Connect is -// called. -// -// This interface is to be implemented by gRPC. Users should not need a -// brand new implementation of this interface. For the situations like -// testing, the new implementation should embed this interface. This allows -// gRPC to add new methods to this interface. -type SubConn interface { - // UpdateAddresses updates the addresses used in this SubConn. - // gRPC checks if currently-connected address is still in the new list. - // If it's in the list, the connection will be kept. - // If it's not in the list, the connection will gracefully closed, and - // a new connection will be created. - // - // This will trigger a state transition for the SubConn. - UpdateAddresses([]resolver.Address) - // Connect starts the connecting for this SubConn. - Connect() -} - -// NewSubConnOptions contains options to create new SubConn. -type NewSubConnOptions struct{} - -// ClientConn represents a gRPC ClientConn. -// -// This interface is to be implemented by gRPC. Users should not need a -// brand new implementation of this interface. For the situations like -// testing, the new implementation should embed this interface. This allows -// gRPC to add new methods to this interface. -type ClientConn interface { - // NewSubConn is called by balancer to create a new SubConn. - // It doesn't block and wait for the connections to be established. - // Behaviors of the SubConn can be controlled by options. - NewSubConn([]resolver.Address, NewSubConnOptions) (SubConn, error) - // RemoveSubConn removes the SubConn from ClientConn. - // The SubConn will be shutdown. - RemoveSubConn(SubConn) - - // UpdateBalancerState is called by balancer to nofity gRPC that some internal - // state in balancer has changed. - // - // gRPC will update the connectivity state of the ClientConn, and will call pick - // on the new picker to pick new SubConn. - UpdateBalancerState(s connectivity.State, p Picker) - - // ResolveNow is called by balancer to notify gRPC to do a name resolving. - ResolveNow(resolver.ResolveNowOption) - - // Target returns the dial target for this ClientConn. - Target() string -} - -// BuildOptions contains additional information for Build. -type BuildOptions struct { - // DialCreds is the transport credential the Balancer implementation can - // use to dial to a remote load balancer server. The Balancer implementations - // can ignore this if it does not need to talk to another party securely. - DialCreds credentials.TransportCredentials - // Dialer is the custom dialer the Balancer implementation can use to dial - // to a remote load balancer server. The Balancer implementations - // can ignore this if it doesn't need to talk to remote balancer. - Dialer func(context.Context, string) (net.Conn, error) - // ChannelzParentID is the entity parent's channelz unique identification number. - ChannelzParentID int64 -} - -// Builder creates a balancer. -type Builder interface { - // Build creates a new balancer with the ClientConn. - Build(cc ClientConn, opts BuildOptions) Balancer - // Name returns the name of balancers built by this builder. - // It will be used to pick balancers (for example in service config). - Name() string -} - -// PickOptions contains addition information for the Pick operation. -type PickOptions struct{} - -// DoneInfo contains additional information for done. -type DoneInfo struct { - // Err is the rpc error the RPC finished with. It could be nil. - Err error - // BytesSent indicates if any bytes have been sent to the server. - BytesSent bool - // BytesReceived indicates if any byte has been received from the server. - BytesReceived bool -} - -var ( - // ErrNoSubConnAvailable indicates no SubConn is available for pick(). - // gRPC will block the RPC until a new picker is available via UpdateBalancerState(). - ErrNoSubConnAvailable = errors.New("no SubConn is available") - // ErrTransientFailure indicates all SubConns are in TransientFailure. - // WaitForReady RPCs will block, non-WaitForReady RPCs will fail. - ErrTransientFailure = errors.New("all SubConns are in TransientFailure") -) - -// Picker is used by gRPC to pick a SubConn to send an RPC. -// Balancer is expected to generate a new picker from its snapshot every time its -// internal state has changed. -// -// The pickers used by gRPC can be updated by ClientConn.UpdateBalancerState(). -type Picker interface { - // Pick returns the SubConn to be used to send the RPC. - // The returned SubConn must be one returned by NewSubConn(). - // - // This functions is expected to return: - // - a SubConn that is known to be READY; - // - ErrNoSubConnAvailable if no SubConn is available, but progress is being - // made (for example, some SubConn is in CONNECTING mode); - // - other errors if no active connecting is happening (for example, all SubConn - // are in TRANSIENT_FAILURE mode). - // - // If a SubConn is returned: - // - If it is READY, gRPC will send the RPC on it; - // - If it is not ready, or becomes not ready after it's returned, gRPC will block - // until UpdateBalancerState() is called and will call pick on the new picker. - // - // If the returned error is not nil: - // - If the error is ErrNoSubConnAvailable, gRPC will block until UpdateBalancerState() - // - If the error is ErrTransientFailure: - // - If the RPC is wait-for-ready, gRPC will block until UpdateBalancerState() - // is called to pick again; - // - Otherwise, RPC will fail with unavailable error. - // - Else (error is other non-nil error): - // - The RPC will fail with unavailable error. - // - // The returned done() function will be called once the rpc has finished, with the - // final status of that RPC. - // done may be nil if balancer doesn't care about the RPC status. - Pick(ctx context.Context, opts PickOptions) (conn SubConn, done func(DoneInfo), err error) -} - -// Balancer takes input from gRPC, manages SubConns, and collects and aggregates -// the connectivity states. -// -// It also generates and updates the Picker used by gRPC to pick SubConns for RPCs. -// -// HandleSubConnectionStateChange, HandleResolvedAddrs and Close are guaranteed -// to be called synchronously from the same goroutine. -// There's no guarantee on picker.Pick, it may be called anytime. -type Balancer interface { - // HandleSubConnStateChange is called by gRPC when the connectivity state - // of sc has changed. - // Balancer is expected to aggregate all the state of SubConn and report - // that back to gRPC. - // Balancer should also generate and update Pickers when its internal state has - // been changed by the new state. - HandleSubConnStateChange(sc SubConn, state connectivity.State) - // HandleResolvedAddrs is called by gRPC to send updated resolved addresses to - // balancers. - // Balancer can create new SubConn or remove SubConn with the addresses. - // An empty address slice and a non-nil error will be passed if the resolver returns - // non-nil error to gRPC. - HandleResolvedAddrs([]resolver.Address, error) - // Close closes the balancer. The balancer is not required to call - // ClientConn.RemoveSubConn for its existing SubConns. - Close() -} diff --git a/vendor/google.golang.org/grpc/balancer/base/balancer.go b/vendor/google.golang.org/grpc/balancer/base/balancer.go deleted file mode 100644 index 23d13511bb2..00000000000 --- a/vendor/google.golang.org/grpc/balancer/base/balancer.go +++ /dev/null @@ -1,208 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 base - -import ( - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/resolver" -) - -type baseBuilder struct { - name string - pickerBuilder PickerBuilder -} - -func (bb *baseBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions) balancer.Balancer { - return &baseBalancer{ - cc: cc, - pickerBuilder: bb.pickerBuilder, - - subConns: make(map[resolver.Address]balancer.SubConn), - scStates: make(map[balancer.SubConn]connectivity.State), - csEvltr: &connectivityStateEvaluator{}, - // Initialize picker to a picker that always return - // ErrNoSubConnAvailable, because when state of a SubConn changes, we - // may call UpdateBalancerState with this picker. - picker: NewErrPicker(balancer.ErrNoSubConnAvailable), - } -} - -func (bb *baseBuilder) Name() string { - return bb.name -} - -type baseBalancer struct { - cc balancer.ClientConn - pickerBuilder PickerBuilder - - csEvltr *connectivityStateEvaluator - state connectivity.State - - subConns map[resolver.Address]balancer.SubConn - scStates map[balancer.SubConn]connectivity.State - picker balancer.Picker -} - -func (b *baseBalancer) HandleResolvedAddrs(addrs []resolver.Address, err error) { - if err != nil { - grpclog.Infof("base.baseBalancer: HandleResolvedAddrs called with error %v", err) - return - } - grpclog.Infoln("base.baseBalancer: got new resolved addresses: ", addrs) - // addrsSet is the set converted from addrs, it's used for quick lookup of an address. - addrsSet := make(map[resolver.Address]struct{}) - for _, a := range addrs { - addrsSet[a] = struct{}{} - if _, ok := b.subConns[a]; !ok { - // a is a new address (not existing in b.subConns). - sc, err := b.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{}) - if err != nil { - grpclog.Warningf("base.baseBalancer: failed to create new SubConn: %v", err) - continue - } - b.subConns[a] = sc - b.scStates[sc] = connectivity.Idle - sc.Connect() - } - } - for a, sc := range b.subConns { - // a was removed by resolver. - if _, ok := addrsSet[a]; !ok { - b.cc.RemoveSubConn(sc) - delete(b.subConns, a) - // Keep the state of this sc in b.scStates until sc's state becomes Shutdown. - // The entry will be deleted in HandleSubConnStateChange. - } - } -} - -// regeneratePicker takes a snapshot of the balancer, and generates a picker -// from it. The picker is -// - errPicker with ErrTransientFailure if the balancer is in TransientFailure, -// - built by the pickerBuilder with all READY SubConns otherwise. -func (b *baseBalancer) regeneratePicker() { - if b.state == connectivity.TransientFailure { - b.picker = NewErrPicker(balancer.ErrTransientFailure) - return - } - readySCs := make(map[resolver.Address]balancer.SubConn) - - // Filter out all ready SCs from full subConn map. - for addr, sc := range b.subConns { - if st, ok := b.scStates[sc]; ok && st == connectivity.Ready { - readySCs[addr] = sc - } - } - b.picker = b.pickerBuilder.Build(readySCs) -} - -func (b *baseBalancer) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { - grpclog.Infof("base.baseBalancer: handle SubConn state change: %p, %v", sc, s) - oldS, ok := b.scStates[sc] - if !ok { - grpclog.Infof("base.baseBalancer: got state changes for an unknown SubConn: %p, %v", sc, s) - return - } - b.scStates[sc] = s - switch s { - case connectivity.Idle: - sc.Connect() - case connectivity.Shutdown: - // When an address was removed by resolver, b called RemoveSubConn but - // kept the sc's state in scStates. Remove state for this sc here. - delete(b.scStates, sc) - } - - oldAggrState := b.state - b.state = b.csEvltr.recordTransition(oldS, s) - - // Regenerate picker when one of the following happens: - // - this sc became ready from not-ready - // - this sc became not-ready from ready - // - the aggregated state of balancer became TransientFailure from non-TransientFailure - // - the aggregated state of balancer became non-TransientFailure from TransientFailure - if (s == connectivity.Ready) != (oldS == connectivity.Ready) || - (b.state == connectivity.TransientFailure) != (oldAggrState == connectivity.TransientFailure) { - b.regeneratePicker() - } - - b.cc.UpdateBalancerState(b.state, b.picker) -} - -// Close is a nop because base balancer doesn't have internal state to clean up, -// and it doesn't need to call RemoveSubConn for the SubConns. -func (b *baseBalancer) Close() { -} - -// NewErrPicker returns a picker that always returns err on Pick(). -func NewErrPicker(err error) balancer.Picker { - return &errPicker{err: err} -} - -type errPicker struct { - err error // Pick() always returns this err. -} - -func (p *errPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { - return nil, nil, p.err -} - -// connectivityStateEvaluator gets updated by addrConns when their -// states transition, based on which it evaluates the state of -// ClientConn. -type connectivityStateEvaluator struct { - numReady uint64 // Number of addrConns in ready state. - numConnecting uint64 // Number of addrConns in connecting state. - numTransientFailure uint64 // Number of addrConns in transientFailure. -} - -// recordTransition records state change happening in every subConn and based on -// that it evaluates what aggregated state should be. -// It can only transition between Ready, Connecting and TransientFailure. Other states, -// Idle and Shutdown are transitioned into by ClientConn; in the beginning of the connection -// before any subConn is created ClientConn is in idle state. In the end when ClientConn -// closes it is in Shutdown state. -// -// recordTransition should only be called synchronously from the same goroutine. -func (cse *connectivityStateEvaluator) recordTransition(oldState, newState connectivity.State) connectivity.State { - // Update counters. - for idx, state := range []connectivity.State{oldState, newState} { - updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new. - switch state { - case connectivity.Ready: - cse.numReady += updateVal - case connectivity.Connecting: - cse.numConnecting += updateVal - case connectivity.TransientFailure: - cse.numTransientFailure += updateVal - } - } - - // Evaluate. - if cse.numReady > 0 { - return connectivity.Ready - } - if cse.numConnecting > 0 { - return connectivity.Connecting - } - return connectivity.TransientFailure -} diff --git a/vendor/google.golang.org/grpc/balancer/base/base.go b/vendor/google.golang.org/grpc/balancer/base/base.go deleted file mode 100644 index 012ace2f2f7..00000000000 --- a/vendor/google.golang.org/grpc/balancer/base/base.go +++ /dev/null @@ -1,52 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 base defines a balancer base that can be used to build balancers with -// different picking algorithms. -// -// The base balancer creates a new SubConn for each resolved address. The -// provided picker will only be notified about READY SubConns. -// -// This package is the base of round_robin balancer, its purpose is to be used -// to build round_robin like balancers with complex picking algorithms. -// Balancers with more complicated logic should try to implement a balancer -// builder from scratch. -// -// All APIs in this package are experimental. -package base - -import ( - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/resolver" -) - -// PickerBuilder creates balancer.Picker. -type PickerBuilder interface { - // Build takes a slice of ready SubConns, and returns a picker that will be - // used by gRPC to pick a SubConn. - Build(readySCs map[resolver.Address]balancer.SubConn) balancer.Picker -} - -// NewBalancerBuilder returns a balancer builder. The balancers -// built by this builder will use the picker builder to build pickers. -func NewBalancerBuilder(name string, pb PickerBuilder) balancer.Builder { - return &baseBuilder{ - name: name, - pickerBuilder: pb, - } -} diff --git a/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go b/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go deleted file mode 100644 index 2eda0a1c210..00000000000 --- a/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go +++ /dev/null @@ -1,79 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 roundrobin defines a roundrobin balancer. Roundrobin balancer is -// installed as one of the default balancers in gRPC, users don't need to -// explicitly install this balancer. -package roundrobin - -import ( - "sync" - - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/balancer/base" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/resolver" -) - -// Name is the name of round_robin balancer. -const Name = "round_robin" - -// newBuilder creates a new roundrobin balancer builder. -func newBuilder() balancer.Builder { - return base.NewBalancerBuilder(Name, &rrPickerBuilder{}) -} - -func init() { - balancer.Register(newBuilder()) -} - -type rrPickerBuilder struct{} - -func (*rrPickerBuilder) Build(readySCs map[resolver.Address]balancer.SubConn) balancer.Picker { - grpclog.Infof("roundrobinPicker: newPicker called with readySCs: %v", readySCs) - var scs []balancer.SubConn - for _, sc := range readySCs { - scs = append(scs, sc) - } - return &rrPicker{ - subConns: scs, - } -} - -type rrPicker struct { - // subConns is the snapshot of the roundrobin balancer when this picker was - // created. The slice is immutable. Each Get() will do a round robin - // selection from it and return the selected SubConn. - subConns []balancer.SubConn - - mu sync.Mutex - next int -} - -func (p *rrPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { - if len(p.subConns) <= 0 { - return nil, nil, balancer.ErrNoSubConnAvailable - } - - p.mu.Lock() - sc := p.subConns[p.next] - p.next = (p.next + 1) % len(p.subConns) - p.mu.Unlock() - return sc, nil, nil -} diff --git a/vendor/google.golang.org/grpc/balancer_conn_wrappers.go b/vendor/google.golang.org/grpc/balancer_conn_wrappers.go deleted file mode 100644 index c23f81706fb..00000000000 --- a/vendor/google.golang.org/grpc/balancer_conn_wrappers.go +++ /dev/null @@ -1,300 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 grpc - -import ( - "fmt" - "sync" - - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/resolver" -) - -// scStateUpdate contains the subConn and the new state it changed to. -type scStateUpdate struct { - sc balancer.SubConn - state connectivity.State -} - -// scStateUpdateBuffer is an unbounded channel for scStateChangeTuple. -// TODO make a general purpose buffer that uses interface{}. -type scStateUpdateBuffer struct { - c chan *scStateUpdate - mu sync.Mutex - backlog []*scStateUpdate -} - -func newSCStateUpdateBuffer() *scStateUpdateBuffer { - return &scStateUpdateBuffer{ - c: make(chan *scStateUpdate, 1), - } -} - -func (b *scStateUpdateBuffer) put(t *scStateUpdate) { - b.mu.Lock() - defer b.mu.Unlock() - if len(b.backlog) == 0 { - select { - case b.c <- t: - return - default: - } - } - b.backlog = append(b.backlog, t) -} - -func (b *scStateUpdateBuffer) load() { - b.mu.Lock() - defer b.mu.Unlock() - if len(b.backlog) > 0 { - select { - case b.c <- b.backlog[0]: - b.backlog[0] = nil - b.backlog = b.backlog[1:] - default: - } - } -} - -// get returns the channel that the scStateUpdate will be sent to. -// -// Upon receiving, the caller should call load to send another -// scStateChangeTuple onto the channel if there is any. -func (b *scStateUpdateBuffer) get() <-chan *scStateUpdate { - return b.c -} - -// resolverUpdate contains the new resolved addresses or error if there's -// any. -type resolverUpdate struct { - addrs []resolver.Address - err error -} - -// ccBalancerWrapper is a wrapper on top of cc for balancers. -// It implements balancer.ClientConn interface. -type ccBalancerWrapper struct { - cc *ClientConn - balancer balancer.Balancer - stateChangeQueue *scStateUpdateBuffer - resolverUpdateCh chan *resolverUpdate - done chan struct{} - - mu sync.Mutex - subConns map[*acBalancerWrapper]struct{} -} - -func newCCBalancerWrapper(cc *ClientConn, b balancer.Builder, bopts balancer.BuildOptions) *ccBalancerWrapper { - ccb := &ccBalancerWrapper{ - cc: cc, - stateChangeQueue: newSCStateUpdateBuffer(), - resolverUpdateCh: make(chan *resolverUpdate, 1), - done: make(chan struct{}), - subConns: make(map[*acBalancerWrapper]struct{}), - } - go ccb.watcher() - ccb.balancer = b.Build(ccb, bopts) - return ccb -} - -// watcher balancer functions sequentially, so the balancer can be implemented -// lock-free. -func (ccb *ccBalancerWrapper) watcher() { - for { - select { - case t := <-ccb.stateChangeQueue.get(): - ccb.stateChangeQueue.load() - select { - case <-ccb.done: - ccb.balancer.Close() - return - default: - } - ccb.balancer.HandleSubConnStateChange(t.sc, t.state) - case t := <-ccb.resolverUpdateCh: - select { - case <-ccb.done: - ccb.balancer.Close() - return - default: - } - ccb.balancer.HandleResolvedAddrs(t.addrs, t.err) - case <-ccb.done: - } - - select { - case <-ccb.done: - ccb.balancer.Close() - ccb.mu.Lock() - scs := ccb.subConns - ccb.subConns = nil - ccb.mu.Unlock() - for acbw := range scs { - ccb.cc.removeAddrConn(acbw.getAddrConn(), errConnDrain) - } - return - default: - } - } -} - -func (ccb *ccBalancerWrapper) close() { - close(ccb.done) -} - -func (ccb *ccBalancerWrapper) handleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { - // When updating addresses for a SubConn, if the address in use is not in - // the new addresses, the old ac will be tearDown() and a new ac will be - // created. tearDown() generates a state change with Shutdown state, we - // don't want the balancer to receive this state change. So before - // tearDown() on the old ac, ac.acbw (acWrapper) will be set to nil, and - // this function will be called with (nil, Shutdown). We don't need to call - // balancer method in this case. - if sc == nil { - return - } - ccb.stateChangeQueue.put(&scStateUpdate{ - sc: sc, - state: s, - }) -} - -func (ccb *ccBalancerWrapper) handleResolvedAddrs(addrs []resolver.Address, err error) { - select { - case <-ccb.resolverUpdateCh: - default: - } - ccb.resolverUpdateCh <- &resolverUpdate{ - addrs: addrs, - err: err, - } -} - -func (ccb *ccBalancerWrapper) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) { - if len(addrs) <= 0 { - return nil, fmt.Errorf("grpc: cannot create SubConn with empty address list") - } - ccb.mu.Lock() - defer ccb.mu.Unlock() - if ccb.subConns == nil { - return nil, fmt.Errorf("grpc: ClientConn balancer wrapper was closed") - } - ac, err := ccb.cc.newAddrConn(addrs) - if err != nil { - return nil, err - } - acbw := &acBalancerWrapper{ac: ac} - acbw.ac.mu.Lock() - ac.acbw = acbw - acbw.ac.mu.Unlock() - ccb.subConns[acbw] = struct{}{} - return acbw, nil -} - -func (ccb *ccBalancerWrapper) RemoveSubConn(sc balancer.SubConn) { - acbw, ok := sc.(*acBalancerWrapper) - if !ok { - return - } - ccb.mu.Lock() - defer ccb.mu.Unlock() - if ccb.subConns == nil { - return - } - delete(ccb.subConns, acbw) - ccb.cc.removeAddrConn(acbw.getAddrConn(), errConnDrain) -} - -func (ccb *ccBalancerWrapper) UpdateBalancerState(s connectivity.State, p balancer.Picker) { - ccb.mu.Lock() - defer ccb.mu.Unlock() - if ccb.subConns == nil { - return - } - ccb.cc.csMgr.updateState(s) - ccb.cc.blockingpicker.updatePicker(p) -} - -func (ccb *ccBalancerWrapper) ResolveNow(o resolver.ResolveNowOption) { - ccb.cc.resolveNow(o) -} - -func (ccb *ccBalancerWrapper) Target() string { - return ccb.cc.target -} - -// acBalancerWrapper is a wrapper on top of ac for balancers. -// It implements balancer.SubConn interface. -type acBalancerWrapper struct { - mu sync.Mutex - ac *addrConn -} - -func (acbw *acBalancerWrapper) UpdateAddresses(addrs []resolver.Address) { - acbw.mu.Lock() - defer acbw.mu.Unlock() - if len(addrs) <= 0 { - acbw.ac.tearDown(errConnDrain) - return - } - if !acbw.ac.tryUpdateAddrs(addrs) { - cc := acbw.ac.cc - acbw.ac.mu.Lock() - // Set old ac.acbw to nil so the Shutdown state update will be ignored - // by balancer. - // - // TODO(bar) the state transition could be wrong when tearDown() old ac - // and creating new ac, fix the transition. - acbw.ac.acbw = nil - acbw.ac.mu.Unlock() - acState := acbw.ac.getState() - acbw.ac.tearDown(errConnDrain) - - if acState == connectivity.Shutdown { - return - } - - ac, err := cc.newAddrConn(addrs) - if err != nil { - grpclog.Warningf("acBalancerWrapper: UpdateAddresses: failed to newAddrConn: %v", err) - return - } - acbw.ac = ac - ac.mu.Lock() - ac.acbw = acbw - ac.mu.Unlock() - if acState != connectivity.Idle { - ac.connect() - } - } -} - -func (acbw *acBalancerWrapper) Connect() { - acbw.mu.Lock() - defer acbw.mu.Unlock() - acbw.ac.connect() -} - -func (acbw *acBalancerWrapper) getAddrConn() *addrConn { - acbw.mu.Lock() - defer acbw.mu.Unlock() - return acbw.ac -} diff --git a/vendor/google.golang.org/grpc/balancer_v1_wrapper.go b/vendor/google.golang.org/grpc/balancer_v1_wrapper.go deleted file mode 100644 index b7abc6b7457..00000000000 --- a/vendor/google.golang.org/grpc/balancer_v1_wrapper.go +++ /dev/null @@ -1,372 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 grpc - -import ( - "strings" - "sync" - - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/resolver" - "google.golang.org/grpc/status" -) - -type balancerWrapperBuilder struct { - b Balancer // The v1 balancer. -} - -func (bwb *balancerWrapperBuilder) Build(cc balancer.ClientConn, opts balancer.BuildOptions) balancer.Balancer { - targetAddr := cc.Target() - targetSplitted := strings.Split(targetAddr, ":///") - if len(targetSplitted) >= 2 { - targetAddr = targetSplitted[1] - } - - bwb.b.Start(targetAddr, BalancerConfig{ - DialCreds: opts.DialCreds, - Dialer: opts.Dialer, - }) - _, pickfirst := bwb.b.(*pickFirst) - bw := &balancerWrapper{ - balancer: bwb.b, - pickfirst: pickfirst, - cc: cc, - targetAddr: targetAddr, - startCh: make(chan struct{}), - conns: make(map[resolver.Address]balancer.SubConn), - connSt: make(map[balancer.SubConn]*scState), - csEvltr: &connectivityStateEvaluator{}, - state: connectivity.Idle, - } - cc.UpdateBalancerState(connectivity.Idle, bw) - go bw.lbWatcher() - return bw -} - -func (bwb *balancerWrapperBuilder) Name() string { - return "wrapper" -} - -type scState struct { - addr Address // The v1 address type. - s connectivity.State - down func(error) -} - -type balancerWrapper struct { - balancer Balancer // The v1 balancer. - pickfirst bool - - cc balancer.ClientConn - targetAddr string // Target without the scheme. - - // To aggregate the connectivity state. - csEvltr *connectivityStateEvaluator - state connectivity.State - - mu sync.Mutex - conns map[resolver.Address]balancer.SubConn - connSt map[balancer.SubConn]*scState - // This channel is closed when handling the first resolver result. - // lbWatcher blocks until this is closed, to avoid race between - // - NewSubConn is created, cc wants to notify balancer of state changes; - // - Build hasn't return, cc doesn't have access to balancer. - startCh chan struct{} -} - -// lbWatcher watches the Notify channel of the balancer and manages -// connections accordingly. -func (bw *balancerWrapper) lbWatcher() { - <-bw.startCh - notifyCh := bw.balancer.Notify() - if notifyCh == nil { - // There's no resolver in the balancer. Connect directly. - a := resolver.Address{ - Addr: bw.targetAddr, - Type: resolver.Backend, - } - sc, err := bw.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{}) - if err != nil { - grpclog.Warningf("Error creating connection to %v. Err: %v", a, err) - } else { - bw.mu.Lock() - bw.conns[a] = sc - bw.connSt[sc] = &scState{ - addr: Address{Addr: bw.targetAddr}, - s: connectivity.Idle, - } - bw.mu.Unlock() - sc.Connect() - } - return - } - - for addrs := range notifyCh { - grpclog.Infof("balancerWrapper: got update addr from Notify: %v\n", addrs) - if bw.pickfirst { - var ( - oldA resolver.Address - oldSC balancer.SubConn - ) - bw.mu.Lock() - for oldA, oldSC = range bw.conns { - break - } - bw.mu.Unlock() - if len(addrs) <= 0 { - if oldSC != nil { - // Teardown old sc. - bw.mu.Lock() - delete(bw.conns, oldA) - delete(bw.connSt, oldSC) - bw.mu.Unlock() - bw.cc.RemoveSubConn(oldSC) - } - continue - } - - var newAddrs []resolver.Address - for _, a := range addrs { - newAddr := resolver.Address{ - Addr: a.Addr, - Type: resolver.Backend, // All addresses from balancer are all backends. - ServerName: "", - Metadata: a.Metadata, - } - newAddrs = append(newAddrs, newAddr) - } - if oldSC == nil { - // Create new sc. - sc, err := bw.cc.NewSubConn(newAddrs, balancer.NewSubConnOptions{}) - if err != nil { - grpclog.Warningf("Error creating connection to %v. Err: %v", newAddrs, err) - } else { - bw.mu.Lock() - // For pickfirst, there should be only one SubConn, so the - // address doesn't matter. All states updating (up and down) - // and picking should all happen on that only SubConn. - bw.conns[resolver.Address{}] = sc - bw.connSt[sc] = &scState{ - addr: addrs[0], // Use the first address. - s: connectivity.Idle, - } - bw.mu.Unlock() - sc.Connect() - } - } else { - bw.mu.Lock() - bw.connSt[oldSC].addr = addrs[0] - bw.mu.Unlock() - oldSC.UpdateAddresses(newAddrs) - } - } else { - var ( - add []resolver.Address // Addresses need to setup connections. - del []balancer.SubConn // Connections need to tear down. - ) - resAddrs := make(map[resolver.Address]Address) - for _, a := range addrs { - resAddrs[resolver.Address{ - Addr: a.Addr, - Type: resolver.Backend, // All addresses from balancer are all backends. - ServerName: "", - Metadata: a.Metadata, - }] = a - } - bw.mu.Lock() - for a := range resAddrs { - if _, ok := bw.conns[a]; !ok { - add = append(add, a) - } - } - for a, c := range bw.conns { - if _, ok := resAddrs[a]; !ok { - del = append(del, c) - delete(bw.conns, a) - // Keep the state of this sc in bw.connSt until its state becomes Shutdown. - } - } - bw.mu.Unlock() - for _, a := range add { - sc, err := bw.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{}) - if err != nil { - grpclog.Warningf("Error creating connection to %v. Err: %v", a, err) - } else { - bw.mu.Lock() - bw.conns[a] = sc - bw.connSt[sc] = &scState{ - addr: resAddrs[a], - s: connectivity.Idle, - } - bw.mu.Unlock() - sc.Connect() - } - } - for _, c := range del { - bw.cc.RemoveSubConn(c) - } - } - } -} - -func (bw *balancerWrapper) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { - bw.mu.Lock() - defer bw.mu.Unlock() - scSt, ok := bw.connSt[sc] - if !ok { - return - } - if s == connectivity.Idle { - sc.Connect() - } - oldS := scSt.s - scSt.s = s - if oldS != connectivity.Ready && s == connectivity.Ready { - scSt.down = bw.balancer.Up(scSt.addr) - } else if oldS == connectivity.Ready && s != connectivity.Ready { - if scSt.down != nil { - scSt.down(errConnClosing) - } - } - sa := bw.csEvltr.recordTransition(oldS, s) - if bw.state != sa { - bw.state = sa - } - bw.cc.UpdateBalancerState(bw.state, bw) - if s == connectivity.Shutdown { - // Remove state for this sc. - delete(bw.connSt, sc) - } -} - -func (bw *balancerWrapper) HandleResolvedAddrs([]resolver.Address, error) { - bw.mu.Lock() - defer bw.mu.Unlock() - select { - case <-bw.startCh: - default: - close(bw.startCh) - } - // There should be a resolver inside the balancer. - // All updates here, if any, are ignored. -} - -func (bw *balancerWrapper) Close() { - bw.mu.Lock() - defer bw.mu.Unlock() - select { - case <-bw.startCh: - default: - close(bw.startCh) - } - bw.balancer.Close() -} - -// The picker is the balancerWrapper itself. -// Pick should never return ErrNoSubConnAvailable. -// It either blocks or returns error, consistent with v1 balancer Get(). -func (bw *balancerWrapper) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { - failfast := true // Default failfast is true. - if ss, ok := rpcInfoFromContext(ctx); ok { - failfast = ss.failfast - } - a, p, err := bw.balancer.Get(ctx, BalancerGetOptions{BlockingWait: !failfast}) - if err != nil { - return nil, nil, err - } - var done func(balancer.DoneInfo) - if p != nil { - done = func(i balancer.DoneInfo) { p() } - } - var sc balancer.SubConn - bw.mu.Lock() - defer bw.mu.Unlock() - if bw.pickfirst { - // Get the first sc in conns. - for _, sc = range bw.conns { - break - } - } else { - var ok bool - sc, ok = bw.conns[resolver.Address{ - Addr: a.Addr, - Type: resolver.Backend, - ServerName: "", - Metadata: a.Metadata, - }] - if !ok && failfast { - return nil, nil, status.Errorf(codes.Unavailable, "there is no connection available") - } - if s, ok := bw.connSt[sc]; failfast && (!ok || s.s != connectivity.Ready) { - // If the returned sc is not ready and RPC is failfast, - // return error, and this RPC will fail. - return nil, nil, status.Errorf(codes.Unavailable, "there is no connection available") - } - } - - return sc, done, nil -} - -// connectivityStateEvaluator gets updated by addrConns when their -// states transition, based on which it evaluates the state of -// ClientConn. -type connectivityStateEvaluator struct { - mu sync.Mutex - numReady uint64 // Number of addrConns in ready state. - numConnecting uint64 // Number of addrConns in connecting state. - numTransientFailure uint64 // Number of addrConns in transientFailure. -} - -// recordTransition records state change happening in every subConn and based on -// that it evaluates what aggregated state should be. -// It can only transition between Ready, Connecting and TransientFailure. Other states, -// Idle and Shutdown are transitioned into by ClientConn; in the beginning of the connection -// before any subConn is created ClientConn is in idle state. In the end when ClientConn -// closes it is in Shutdown state. -// TODO Note that in later releases, a ClientConn with no activity will be put into an Idle state. -func (cse *connectivityStateEvaluator) recordTransition(oldState, newState connectivity.State) connectivity.State { - cse.mu.Lock() - defer cse.mu.Unlock() - - // Update counters. - for idx, state := range []connectivity.State{oldState, newState} { - updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new. - switch state { - case connectivity.Ready: - cse.numReady += updateVal - case connectivity.Connecting: - cse.numConnecting += updateVal - case connectivity.TransientFailure: - cse.numTransientFailure += updateVal - } - } - - // Evaluate. - if cse.numReady > 0 { - return connectivity.Ready - } - if cse.numConnecting > 0 { - return connectivity.Connecting - } - return connectivity.TransientFailure -} diff --git a/vendor/google.golang.org/grpc/call.go b/vendor/google.golang.org/grpc/call.go deleted file mode 100644 index f73b7d5528f..00000000000 --- a/vendor/google.golang.org/grpc/call.go +++ /dev/null @@ -1,93 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 grpc - -import ( - "golang.org/x/net/context" -) - -// Invoke sends the RPC request on the wire and returns after response is -// received. This is typically called by generated code. -// -// All errors returned by Invoke are compatible with the status package. -func (cc *ClientConn) Invoke(ctx context.Context, method string, args, reply interface{}, opts ...CallOption) error { - // allow interceptor to see all applicable call options, which means those - // configured as defaults from dial option as well as per-call options - opts = combine(cc.dopts.callOptions, opts) - - if cc.dopts.unaryInt != nil { - return cc.dopts.unaryInt(ctx, method, args, reply, cc, invoke, opts...) - } - return invoke(ctx, method, args, reply, cc, opts...) -} - -func combine(o1 []CallOption, o2 []CallOption) []CallOption { - // we don't use append because o1 could have extra capacity whose - // elements would be overwritten, which could cause inadvertent - // sharing (and race connditions) between concurrent calls - if len(o1) == 0 { - return o2 - } else if len(o2) == 0 { - return o1 - } - ret := make([]CallOption, len(o1)+len(o2)) - copy(ret, o1) - copy(ret[len(o1):], o2) - return ret -} - -// Invoke sends the RPC request on the wire and returns after response is -// received. This is typically called by generated code. -// -// DEPRECATED: Use ClientConn.Invoke instead. -func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) error { - return cc.Invoke(ctx, method, args, reply, opts...) -} - -var unaryStreamDesc = &StreamDesc{ServerStreams: false, ClientStreams: false} - -func invoke(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, opts ...CallOption) error { - // TODO: implement retries in clientStream and make this simply - // newClientStream, SendMsg, RecvMsg. - firstAttempt := true - for { - csInt, err := newClientStream(ctx, unaryStreamDesc, cc, method, opts...) - if err != nil { - return err - } - cs := csInt.(*clientStream) - if err := cs.SendMsg(req); err != nil { - if !cs.c.failFast && cs.attempt.s.Unprocessed() && firstAttempt { - // TODO: Add a field to header for grpc-transparent-retry-attempts - firstAttempt = false - continue - } - return err - } - if err := cs.RecvMsg(reply); err != nil { - if !cs.c.failFast && cs.attempt.s.Unprocessed() && firstAttempt { - // TODO: Add a field to header for grpc-transparent-retry-attempts - firstAttempt = false - continue - } - return err - } - return nil - } -} diff --git a/vendor/google.golang.org/grpc/channelz/funcs.go b/vendor/google.golang.org/grpc/channelz/funcs.go deleted file mode 100644 index 586a0336b47..00000000000 --- a/vendor/google.golang.org/grpc/channelz/funcs.go +++ /dev/null @@ -1,573 +0,0 @@ -/* - * - * Copyright 2018 gRPC 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 channelz defines APIs for enabling channelz service, entry -// registration/deletion, and accessing channelz data. It also defines channelz -// metric struct formats. -// -// All APIs in this package are experimental. -package channelz - -import ( - "sort" - "sync" - "sync/atomic" - - "google.golang.org/grpc/grpclog" -) - -var ( - db dbWrapper - idGen idGenerator - // EntryPerPage defines the number of channelz entries to be shown on a web page. - EntryPerPage = 50 - curState int32 -) - -// TurnOn turns on channelz data collection. -func TurnOn() { - if !IsOn() { - NewChannelzStorage() - atomic.StoreInt32(&curState, 1) - } -} - -// IsOn returns whether channelz data collection is on. -func IsOn() bool { - return atomic.CompareAndSwapInt32(&curState, 1, 1) -} - -// dbWarpper wraps around a reference to internal channelz data storage, and -// provide synchronized functionality to set and get the reference. -type dbWrapper struct { - mu sync.RWMutex - DB *channelMap -} - -func (d *dbWrapper) set(db *channelMap) { - d.mu.Lock() - d.DB = db - d.mu.Unlock() -} - -func (d *dbWrapper) get() *channelMap { - d.mu.RLock() - defer d.mu.RUnlock() - return d.DB -} - -// NewChannelzStorage initializes channelz data storage and id generator. -// -// Note: This function is exported for testing purpose only. User should not call -// it in most cases. -func NewChannelzStorage() { - db.set(&channelMap{ - topLevelChannels: make(map[int64]struct{}), - channels: make(map[int64]*channel), - listenSockets: make(map[int64]*listenSocket), - normalSockets: make(map[int64]*normalSocket), - servers: make(map[int64]*server), - subChannels: make(map[int64]*subChannel), - }) - idGen.reset() -} - -// GetTopChannels returns a slice of top channel's ChannelMetric, along with a -// boolean indicating whether there's more top channels to be queried for. -// -// The arg id specifies that only top channel with id at or above it will be included -// in the result. The returned slice is up to a length of EntryPerPage, and is -// sorted in ascending id order. -func GetTopChannels(id int64) ([]*ChannelMetric, bool) { - return db.get().GetTopChannels(id) -} - -// GetServers returns a slice of server's ServerMetric, along with a -// boolean indicating whether there's more servers to be queried for. -// -// The arg id specifies that only server with id at or above it will be included -// in the result. The returned slice is up to a length of EntryPerPage, and is -// sorted in ascending id order. -func GetServers(id int64) ([]*ServerMetric, bool) { - return db.get().GetServers(id) -} - -// GetServerSockets returns a slice of server's (identified by id) normal socket's -// SocketMetric, along with a boolean indicating whether there's more sockets to -// be queried for. -// -// The arg startID specifies that only sockets with id at or above it will be -// included in the result. The returned slice is up to a length of EntryPerPage, -// and is sorted in ascending id order. -func GetServerSockets(id int64, startID int64) ([]*SocketMetric, bool) { - return db.get().GetServerSockets(id, startID) -} - -// GetChannel returns the ChannelMetric for the channel (identified by id). -func GetChannel(id int64) *ChannelMetric { - return db.get().GetChannel(id) -} - -// GetSubChannel returns the SubChannelMetric for the subchannel (identified by id). -func GetSubChannel(id int64) *SubChannelMetric { - return db.get().GetSubChannel(id) -} - -// GetSocket returns the SocketInternalMetric for the socket (identified by id). -func GetSocket(id int64) *SocketMetric { - return db.get().GetSocket(id) -} - -// RegisterChannel registers the given channel c in channelz database with ref -// as its reference name, and add it to the child list of its parent (identified -// by pid). pid = 0 means no parent. It returns the unique channelz tracking id -// assigned to this channel. -func RegisterChannel(c Channel, pid int64, ref string) int64 { - id := idGen.genID() - cn := &channel{ - refName: ref, - c: c, - subChans: make(map[int64]string), - nestedChans: make(map[int64]string), - id: id, - pid: pid, - } - if pid == 0 { - db.get().addChannel(id, cn, true, pid, ref) - } else { - db.get().addChannel(id, cn, false, pid, ref) - } - return id -} - -// RegisterSubChannel registers the given channel c in channelz database with ref -// as its reference name, and add it to the child list of its parent (identified -// by pid). It returns the unique channelz tracking id assigned to this subchannel. -func RegisterSubChannel(c Channel, pid int64, ref string) int64 { - if pid == 0 { - grpclog.Error("a SubChannel's parent id cannot be 0") - return 0 - } - id := idGen.genID() - sc := &subChannel{ - refName: ref, - c: c, - sockets: make(map[int64]string), - id: id, - pid: pid, - } - db.get().addSubChannel(id, sc, pid, ref) - return id -} - -// RegisterServer registers the given server s in channelz database. It returns -// the unique channelz tracking id assigned to this server. -func RegisterServer(s Server, ref string) int64 { - id := idGen.genID() - svr := &server{ - refName: ref, - s: s, - sockets: make(map[int64]string), - listenSockets: make(map[int64]string), - id: id, - } - db.get().addServer(id, svr) - return id -} - -// RegisterListenSocket registers the given listen socket s in channelz database -// with ref as its reference name, and add it to the child list of its parent -// (identified by pid). It returns the unique channelz tracking id assigned to -// this listen socket. -func RegisterListenSocket(s Socket, pid int64, ref string) int64 { - if pid == 0 { - grpclog.Error("a ListenSocket's parent id cannot be 0") - return 0 - } - id := idGen.genID() - ls := &listenSocket{refName: ref, s: s, id: id, pid: pid} - db.get().addListenSocket(id, ls, pid, ref) - return id -} - -// RegisterNormalSocket registers the given normal socket s in channelz database -// with ref as its reference name, and add it to the child list of its parent -// (identified by pid). It returns the unique channelz tracking id assigned to -// this normal socket. -func RegisterNormalSocket(s Socket, pid int64, ref string) int64 { - if pid == 0 { - grpclog.Error("a NormalSocket's parent id cannot be 0") - return 0 - } - id := idGen.genID() - ns := &normalSocket{refName: ref, s: s, id: id, pid: pid} - db.get().addNormalSocket(id, ns, pid, ref) - return id -} - -// RemoveEntry removes an entry with unique channelz trakcing id to be id from -// channelz database. -func RemoveEntry(id int64) { - db.get().removeEntry(id) -} - -// channelMap is the storage data structure for channelz. -// Methods of channelMap can be divided in two two categories with respect to locking. -// 1. Methods acquire the global lock. -// 2. Methods that can only be called when global lock is held. -// A second type of method need always to be called inside a first type of method. -type channelMap struct { - mu sync.RWMutex - topLevelChannels map[int64]struct{} - servers map[int64]*server - channels map[int64]*channel - subChannels map[int64]*subChannel - listenSockets map[int64]*listenSocket - normalSockets map[int64]*normalSocket -} - -func (c *channelMap) addServer(id int64, s *server) { - c.mu.Lock() - s.cm = c - c.servers[id] = s - c.mu.Unlock() -} - -func (c *channelMap) addChannel(id int64, cn *channel, isTopChannel bool, pid int64, ref string) { - c.mu.Lock() - cn.cm = c - c.channels[id] = cn - if isTopChannel { - c.topLevelChannels[id] = struct{}{} - } else { - c.findEntry(pid).addChild(id, cn) - } - c.mu.Unlock() -} - -func (c *channelMap) addSubChannel(id int64, sc *subChannel, pid int64, ref string) { - c.mu.Lock() - sc.cm = c - c.subChannels[id] = sc - c.findEntry(pid).addChild(id, sc) - c.mu.Unlock() -} - -func (c *channelMap) addListenSocket(id int64, ls *listenSocket, pid int64, ref string) { - c.mu.Lock() - ls.cm = c - c.listenSockets[id] = ls - c.findEntry(pid).addChild(id, ls) - c.mu.Unlock() -} - -func (c *channelMap) addNormalSocket(id int64, ns *normalSocket, pid int64, ref string) { - c.mu.Lock() - ns.cm = c - c.normalSockets[id] = ns - c.findEntry(pid).addChild(id, ns) - c.mu.Unlock() -} - -// removeEntry triggers the removal of an entry, which may not indeed delete the -// entry, if it has to wait on the deletion of its children, or may lead to a chain -// of entry deletion. For example, deleting the last socket of a gracefully shutting -// down server will lead to the server being also deleted. -func (c *channelMap) removeEntry(id int64) { - c.mu.Lock() - c.findEntry(id).triggerDelete() - c.mu.Unlock() -} - -// c.mu must be held by the caller. -func (c *channelMap) findEntry(id int64) entry { - var v entry - var ok bool - if v, ok = c.channels[id]; ok { - return v - } - if v, ok = c.subChannels[id]; ok { - return v - } - if v, ok = c.servers[id]; ok { - return v - } - if v, ok = c.listenSockets[id]; ok { - return v - } - if v, ok = c.normalSockets[id]; ok { - return v - } - return &dummyEntry{idNotFound: id} -} - -// c.mu must be held by the caller -// deleteEntry simply deletes an entry from the channelMap. Before calling this -// method, caller must check this entry is ready to be deleted, i.e removeEntry() -// has been called on it, and no children still exist. -// Conditionals are ordered by the expected frequency of deletion of each entity -// type, in order to optimize performance. -func (c *channelMap) deleteEntry(id int64) { - var ok bool - if _, ok = c.normalSockets[id]; ok { - delete(c.normalSockets, id) - return - } - if _, ok = c.subChannels[id]; ok { - delete(c.subChannels, id) - return - } - if _, ok = c.channels[id]; ok { - delete(c.channels, id) - delete(c.topLevelChannels, id) - return - } - if _, ok = c.listenSockets[id]; ok { - delete(c.listenSockets, id) - return - } - if _, ok = c.servers[id]; ok { - delete(c.servers, id) - return - } -} - -type int64Slice []int64 - -func (s int64Slice) Len() int { return len(s) } -func (s int64Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s int64Slice) Less(i, j int) bool { return s[i] < s[j] } - -func copyMap(m map[int64]string) map[int64]string { - n := make(map[int64]string) - for k, v := range m { - n[k] = v - } - return n -} - -func min(a, b int) int { - if a < b { - return a - } - return b -} - -func (c *channelMap) GetTopChannels(id int64) ([]*ChannelMetric, bool) { - c.mu.RLock() - l := len(c.topLevelChannels) - ids := make([]int64, 0, l) - cns := make([]*channel, 0, min(l, EntryPerPage)) - - for k := range c.topLevelChannels { - ids = append(ids, k) - } - sort.Sort(int64Slice(ids)) - idx := sort.Search(len(ids), func(i int) bool { return ids[i] >= id }) - count := 0 - var end bool - var t []*ChannelMetric - for i, v := range ids[idx:] { - if count == EntryPerPage { - break - } - if cn, ok := c.channels[v]; ok { - cns = append(cns, cn) - t = append(t, &ChannelMetric{ - NestedChans: copyMap(cn.nestedChans), - SubChans: copyMap(cn.subChans), - }) - count++ - } - if i == len(ids[idx:])-1 { - end = true - break - } - } - c.mu.RUnlock() - if count == 0 { - end = true - } - - for i, cn := range cns { - t[i].ChannelData = cn.c.ChannelzMetric() - t[i].ID = cn.id - t[i].RefName = cn.refName - } - return t, end -} - -func (c *channelMap) GetServers(id int64) ([]*ServerMetric, bool) { - c.mu.RLock() - l := len(c.servers) - ids := make([]int64, 0, l) - ss := make([]*server, 0, min(l, EntryPerPage)) - for k := range c.servers { - ids = append(ids, k) - } - sort.Sort(int64Slice(ids)) - idx := sort.Search(len(ids), func(i int) bool { return ids[i] >= id }) - count := 0 - var end bool - var s []*ServerMetric - for i, v := range ids[idx:] { - if count == EntryPerPage { - break - } - if svr, ok := c.servers[v]; ok { - ss = append(ss, svr) - s = append(s, &ServerMetric{ - ListenSockets: copyMap(svr.listenSockets), - }) - count++ - } - if i == len(ids[idx:])-1 { - end = true - break - } - } - c.mu.RUnlock() - if count == 0 { - end = true - } - - for i, svr := range ss { - s[i].ServerData = svr.s.ChannelzMetric() - s[i].ID = svr.id - s[i].RefName = svr.refName - } - return s, end -} - -func (c *channelMap) GetServerSockets(id int64, startID int64) ([]*SocketMetric, bool) { - var svr *server - var ok bool - c.mu.RLock() - if svr, ok = c.servers[id]; !ok { - // server with id doesn't exist. - c.mu.RUnlock() - return nil, true - } - svrskts := svr.sockets - l := len(svrskts) - ids := make([]int64, 0, l) - sks := make([]*normalSocket, 0, min(l, EntryPerPage)) - for k := range svrskts { - ids = append(ids, k) - } - sort.Sort((int64Slice(ids))) - idx := sort.Search(len(ids), func(i int) bool { return ids[i] >= id }) - count := 0 - var end bool - for i, v := range ids[idx:] { - if count == EntryPerPage { - break - } - if ns, ok := c.normalSockets[v]; ok { - sks = append(sks, ns) - count++ - } - if i == len(ids[idx:])-1 { - end = true - break - } - } - c.mu.RUnlock() - if count == 0 { - end = true - } - var s []*SocketMetric - for _, ns := range sks { - sm := &SocketMetric{} - sm.SocketData = ns.s.ChannelzMetric() - sm.ID = ns.id - sm.RefName = ns.refName - s = append(s, sm) - } - return s, end -} - -func (c *channelMap) GetChannel(id int64) *ChannelMetric { - cm := &ChannelMetric{} - var cn *channel - var ok bool - c.mu.RLock() - if cn, ok = c.channels[id]; !ok { - // channel with id doesn't exist. - c.mu.RUnlock() - return nil - } - cm.NestedChans = copyMap(cn.nestedChans) - cm.SubChans = copyMap(cn.subChans) - c.mu.RUnlock() - cm.ChannelData = cn.c.ChannelzMetric() - cm.ID = cn.id - cm.RefName = cn.refName - return cm -} - -func (c *channelMap) GetSubChannel(id int64) *SubChannelMetric { - cm := &SubChannelMetric{} - var sc *subChannel - var ok bool - c.mu.RLock() - if sc, ok = c.subChannels[id]; !ok { - // subchannel with id doesn't exist. - c.mu.RUnlock() - return nil - } - cm.Sockets = copyMap(sc.sockets) - c.mu.RUnlock() - cm.ChannelData = sc.c.ChannelzMetric() - cm.ID = sc.id - cm.RefName = sc.refName - return cm -} - -func (c *channelMap) GetSocket(id int64) *SocketMetric { - sm := &SocketMetric{} - c.mu.RLock() - if ls, ok := c.listenSockets[id]; ok { - c.mu.RUnlock() - sm.SocketData = ls.s.ChannelzMetric() - sm.ID = ls.id - sm.RefName = ls.refName - return sm - } - if ns, ok := c.normalSockets[id]; ok { - c.mu.RUnlock() - sm.SocketData = ns.s.ChannelzMetric() - sm.ID = ns.id - sm.RefName = ns.refName - return sm - } - c.mu.RUnlock() - return nil -} - -type idGenerator struct { - id int64 -} - -func (i *idGenerator) reset() { - atomic.StoreInt64(&i.id, 0) -} - -func (i *idGenerator) genID() int64 { - return atomic.AddInt64(&i.id, 1) -} diff --git a/vendor/google.golang.org/grpc/channelz/types.go b/vendor/google.golang.org/grpc/channelz/types.go deleted file mode 100644 index 153d75340e4..00000000000 --- a/vendor/google.golang.org/grpc/channelz/types.go +++ /dev/null @@ -1,418 +0,0 @@ -/* - * - * Copyright 2018 gRPC 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 channelz - -import ( - "net" - "time" - - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/grpclog" -) - -// entry represents a node in the channelz database. -type entry interface { - // addChild adds a child e, whose channelz id is id to child list - addChild(id int64, e entry) - // deleteChild deletes a child with channelz id to be id from child list - deleteChild(id int64) - // triggerDelete tries to delete self from channelz database. However, if child - // list is not empty, then deletion from the database is on hold until the last - // child is deleted from database. - triggerDelete() - // deleteSelfIfReady check whether triggerDelete() has been called before, and whether child - // list is now empty. If both conditions are met, then delete self from database. - deleteSelfIfReady() -} - -// dummyEntry is a fake entry to handle entry not found case. -type dummyEntry struct { - idNotFound int64 -} - -func (d *dummyEntry) addChild(id int64, e entry) { - // Note: It is possible for a normal program to reach here under race condition. - // For example, there could be a race between ClientConn.Close() info being propagated - // to addrConn and http2Client. ClientConn.Close() cancel the context and result - // in http2Client to error. The error info is then caught by transport monitor - // and before addrConn.tearDown() is called in side ClientConn.Close(). Therefore, - // the addrConn will create a new transport. And when registering the new transport in - // channelz, its parent addrConn could have already been torn down and deleted - // from channelz tracking, and thus reach the code here. - grpclog.Infof("attempt to add child of type %T with id %d to a parent (id=%d) that doesn't currently exist", e, id, d.idNotFound) -} - -func (d *dummyEntry) deleteChild(id int64) { - // It is possible for a normal program to reach here under race condition. - // Refer to the example described in addChild(). - grpclog.Infof("attempt to delete child with id %d from a parent (id=%d) that doesn't currently exist", id, d.idNotFound) -} - -func (d *dummyEntry) triggerDelete() { - grpclog.Warningf("attempt to delete an entry (id=%d) that doesn't currently exist", d.idNotFound) -} - -func (*dummyEntry) deleteSelfIfReady() { - // code should not reach here. deleteSelfIfReady is always called on an existing entry. -} - -// ChannelMetric defines the info channelz provides for a specific Channel, which -// includes ChannelInternalMetric and channelz-specific data, such as channelz id, -// child list, etc. -type ChannelMetric struct { - // ID is the channelz id of this channel. - ID int64 - // RefName is the human readable reference string of this channel. - RefName string - // ChannelData contains channel internal metric reported by the channel through - // ChannelzMetric(). - ChannelData *ChannelInternalMetric - // NestedChans tracks the nested channel type children of this channel in the format of - // a map from nested channel channelz id to corresponding reference string. - NestedChans map[int64]string - // SubChans tracks the subchannel type children of this channel in the format of a - // map from subchannel channelz id to corresponding reference string. - SubChans map[int64]string - // Sockets tracks the socket type children of this channel in the format of a map - // from socket channelz id to corresponding reference string. - // Note current grpc implementation doesn't allow channel having sockets directly, - // therefore, this is field is unused. - Sockets map[int64]string -} - -// SubChannelMetric defines the info channelz provides for a specific SubChannel, -// which includes ChannelInternalMetric and channelz-specific data, such as -// channelz id, child list, etc. -type SubChannelMetric struct { - // ID is the channelz id of this subchannel. - ID int64 - // RefName is the human readable reference string of this subchannel. - RefName string - // ChannelData contains subchannel internal metric reported by the subchannel - // through ChannelzMetric(). - ChannelData *ChannelInternalMetric - // NestedChans tracks the nested channel type children of this subchannel in the format of - // a map from nested channel channelz id to corresponding reference string. - // Note current grpc implementation doesn't allow subchannel to have nested channels - // as children, therefore, this field is unused. - NestedChans map[int64]string - // SubChans tracks the subchannel type children of this subchannel in the format of a - // map from subchannel channelz id to corresponding reference string. - // Note current grpc implementation doesn't allow subchannel to have subchannels - // as children, therefore, this field is unused. - SubChans map[int64]string - // Sockets tracks the socket type children of this subchannel in the format of a map - // from socket channelz id to corresponding reference string. - Sockets map[int64]string -} - -// ChannelInternalMetric defines the struct that the implementor of Channel interface -// should return from ChannelzMetric(). -type ChannelInternalMetric struct { - // current connectivity state of the channel. - State connectivity.State - // The target this channel originally tried to connect to. May be absent - Target string - // The number of calls started on the channel. - CallsStarted int64 - // The number of calls that have completed with an OK status. - CallsSucceeded int64 - // The number of calls that have a completed with a non-OK status. - CallsFailed int64 - // The last time a call was started on the channel. - LastCallStartedTimestamp time.Time - //TODO: trace -} - -// Channel is the interface that should be satisfied in order to be tracked by -// channelz as Channel or SubChannel. -type Channel interface { - ChannelzMetric() *ChannelInternalMetric -} - -type channel struct { - refName string - c Channel - closeCalled bool - nestedChans map[int64]string - subChans map[int64]string - id int64 - pid int64 - cm *channelMap -} - -func (c *channel) addChild(id int64, e entry) { - switch v := e.(type) { - case *subChannel: - c.subChans[id] = v.refName - case *channel: - c.nestedChans[id] = v.refName - default: - grpclog.Errorf("cannot add a child (id = %d) of type %T to a channel", id, e) - } -} - -func (c *channel) deleteChild(id int64) { - delete(c.subChans, id) - delete(c.nestedChans, id) - c.deleteSelfIfReady() -} - -func (c *channel) triggerDelete() { - c.closeCalled = true - c.deleteSelfIfReady() -} - -func (c *channel) deleteSelfIfReady() { - if !c.closeCalled || len(c.subChans)+len(c.nestedChans) != 0 { - return - } - c.cm.deleteEntry(c.id) - // not top channel - if c.pid != 0 { - c.cm.findEntry(c.pid).deleteChild(c.id) - } -} - -type subChannel struct { - refName string - c Channel - closeCalled bool - sockets map[int64]string - id int64 - pid int64 - cm *channelMap -} - -func (sc *subChannel) addChild(id int64, e entry) { - if v, ok := e.(*normalSocket); ok { - sc.sockets[id] = v.refName - } else { - grpclog.Errorf("cannot add a child (id = %d) of type %T to a subChannel", id, e) - } -} - -func (sc *subChannel) deleteChild(id int64) { - delete(sc.sockets, id) - sc.deleteSelfIfReady() -} - -func (sc *subChannel) triggerDelete() { - sc.closeCalled = true - sc.deleteSelfIfReady() -} - -func (sc *subChannel) deleteSelfIfReady() { - if !sc.closeCalled || len(sc.sockets) != 0 { - return - } - sc.cm.deleteEntry(sc.id) - sc.cm.findEntry(sc.pid).deleteChild(sc.id) -} - -// SocketMetric defines the info channelz provides for a specific Socket, which -// includes SocketInternalMetric and channelz-specific data, such as channelz id, etc. -type SocketMetric struct { - // ID is the channelz id of this socket. - ID int64 - // RefName is the human readable reference string of this socket. - RefName string - // SocketData contains socket internal metric reported by the socket through - // ChannelzMetric(). - SocketData *SocketInternalMetric -} - -// SocketInternalMetric defines the struct that the implementor of Socket interface -// should return from ChannelzMetric(). -type SocketInternalMetric struct { - // The number of streams that have been started. - StreamsStarted int64 - // The number of streams that have ended successfully: - // On client side, receiving frame with eos bit set. - // On server side, sending frame with eos bit set. - StreamsSucceeded int64 - // The number of streams that have ended unsuccessfully: - // On client side, termination without receiving frame with eos bit set. - // On server side, termination without sending frame with eos bit set. - StreamsFailed int64 - // The number of messages successfully sent on this socket. - MessagesSent int64 - MessagesReceived int64 - // The number of keep alives sent. This is typically implemented with HTTP/2 - // ping messages. - KeepAlivesSent int64 - // The last time a stream was created by this endpoint. Usually unset for - // servers. - LastLocalStreamCreatedTimestamp time.Time - // The last time a stream was created by the remote endpoint. Usually unset - // for clients. - LastRemoteStreamCreatedTimestamp time.Time - // The last time a message was sent by this endpoint. - LastMessageSentTimestamp time.Time - // The last time a message was received by this endpoint. - LastMessageReceivedTimestamp time.Time - // The amount of window, granted to the local endpoint by the remote endpoint. - // This may be slightly out of date due to network latency. This does NOT - // include stream level or TCP level flow control info. - LocalFlowControlWindow int64 - // The amount of window, granted to the remote endpoint by the local endpoint. - // This may be slightly out of date due to network latency. This does NOT - // include stream level or TCP level flow control info. - RemoteFlowControlWindow int64 - // The locally bound address. - LocalAddr net.Addr - // The remote bound address. May be absent. - RemoteAddr net.Addr - // Optional, represents the name of the remote endpoint, if different than - // the original target name. - RemoteName string - //TODO: socket options - //TODO: Security -} - -// Socket is the interface that should be satisfied in order to be tracked by -// channelz as Socket. -type Socket interface { - ChannelzMetric() *SocketInternalMetric -} - -type listenSocket struct { - refName string - s Socket - id int64 - pid int64 - cm *channelMap -} - -func (ls *listenSocket) addChild(id int64, e entry) { - grpclog.Errorf("cannot add a child (id = %d) of type %T to a listen socket", id, e) -} - -func (ls *listenSocket) deleteChild(id int64) { - grpclog.Errorf("cannot delete a child (id = %d) from a listen socket", id) -} - -func (ls *listenSocket) triggerDelete() { - ls.cm.deleteEntry(ls.id) - ls.cm.findEntry(ls.pid).deleteChild(ls.id) -} - -func (ls *listenSocket) deleteSelfIfReady() { - grpclog.Errorf("cannot call deleteSelfIfReady on a listen socket") -} - -type normalSocket struct { - refName string - s Socket - id int64 - pid int64 - cm *channelMap -} - -func (ns *normalSocket) addChild(id int64, e entry) { - grpclog.Errorf("cannot add a child (id = %d) of type %T to a normal socket", id, e) -} - -func (ns *normalSocket) deleteChild(id int64) { - grpclog.Errorf("cannot delete a child (id = %d) from a normal socket", id) -} - -func (ns *normalSocket) triggerDelete() { - ns.cm.deleteEntry(ns.id) - ns.cm.findEntry(ns.pid).deleteChild(ns.id) -} - -func (ns *normalSocket) deleteSelfIfReady() { - grpclog.Errorf("cannot call deleteSelfIfReady on a normal socket") -} - -// ServerMetric defines the info channelz provides for a specific Server, which -// includes ServerInternalMetric and channelz-specific data, such as channelz id, -// child list, etc. -type ServerMetric struct { - // ID is the channelz id of this server. - ID int64 - // RefName is the human readable reference string of this server. - RefName string - // ServerData contains server internal metric reported by the server through - // ChannelzMetric(). - ServerData *ServerInternalMetric - // ListenSockets tracks the listener socket type children of this server in the - // format of a map from socket channelz id to corresponding reference string. - ListenSockets map[int64]string -} - -// ServerInternalMetric defines the struct that the implementor of Server interface -// should return from ChannelzMetric(). -type ServerInternalMetric struct { - // The number of incoming calls started on the server. - CallsStarted int64 - // The number of incoming calls that have completed with an OK status. - CallsSucceeded int64 - // The number of incoming calls that have a completed with a non-OK status. - CallsFailed int64 - // The last time a call was started on the server. - LastCallStartedTimestamp time.Time - //TODO: trace -} - -// Server is the interface to be satisfied in order to be tracked by channelz as -// Server. -type Server interface { - ChannelzMetric() *ServerInternalMetric -} - -type server struct { - refName string - s Server - closeCalled bool - sockets map[int64]string - listenSockets map[int64]string - id int64 - cm *channelMap -} - -func (s *server) addChild(id int64, e entry) { - switch v := e.(type) { - case *normalSocket: - s.sockets[id] = v.refName - case *listenSocket: - s.listenSockets[id] = v.refName - default: - grpclog.Errorf("cannot add a child (id = %d) of type %T to a server", id, e) - } -} - -func (s *server) deleteChild(id int64) { - delete(s.sockets, id) - delete(s.listenSockets, id) - s.deleteSelfIfReady() -} - -func (s *server) triggerDelete() { - s.closeCalled = true - s.deleteSelfIfReady() -} - -func (s *server) deleteSelfIfReady() { - if !s.closeCalled || len(s.sockets)+len(s.listenSockets) != 0 { - return - } - s.cm.deleteEntry(s.id) -} diff --git a/vendor/google.golang.org/grpc/clientconn.go b/vendor/google.golang.org/grpc/clientconn.go deleted file mode 100644 index e8d95b43b74..00000000000 --- a/vendor/google.golang.org/grpc/clientconn.go +++ /dev/null @@ -1,1591 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 grpc - -import ( - "errors" - "fmt" - "math" - "net" - "reflect" - "strings" - "sync" - "time" - - "golang.org/x/net/context" - "golang.org/x/net/trace" - "google.golang.org/grpc/balancer" - _ "google.golang.org/grpc/balancer/roundrobin" // To register roundrobin. - "google.golang.org/grpc/channelz" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/keepalive" - "google.golang.org/grpc/resolver" - _ "google.golang.org/grpc/resolver/dns" // To register dns resolver. - _ "google.golang.org/grpc/resolver/passthrough" // To register passthrough resolver. - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" - "google.golang.org/grpc/transport" -) - -const ( - // minimum time to give a connection to complete - minConnectTimeout = 20 * time.Second -) - -var ( - // ErrClientConnClosing indicates that the operation is illegal because - // the ClientConn is closing. - // - // Deprecated: this error should not be relied upon by users; use the status - // code of Canceled instead. - ErrClientConnClosing = status.Error(codes.Canceled, "grpc: the client connection is closing") - // errConnDrain indicates that the connection starts to be drained and does not accept any new RPCs. - errConnDrain = errors.New("grpc: the connection is drained") - // errConnClosing indicates that the connection is closing. - errConnClosing = errors.New("grpc: the connection is closing") - // errConnUnavailable indicates that the connection is unavailable. - errConnUnavailable = errors.New("grpc: the connection is unavailable") - // errBalancerClosed indicates that the balancer is closed. - errBalancerClosed = errors.New("grpc: balancer is closed") - // We use an accessor so that minConnectTimeout can be - // atomically read and updated while testing. - getMinConnectTimeout = func() time.Duration { - return minConnectTimeout - } -) - -// The following errors are returned from Dial and DialContext -var ( - // errNoTransportSecurity indicates that there is no transport security - // being set for ClientConn. Users should either set one or explicitly - // call WithInsecure DialOption to disable security. - errNoTransportSecurity = errors.New("grpc: no transport security set (use grpc.WithInsecure() explicitly or set credentials)") - // errTransportCredentialsMissing indicates that users want to transmit security - // information (e.g., oauth2 token) which requires secure connection on an insecure - // connection. - errTransportCredentialsMissing = errors.New("grpc: the credentials require transport level security (use grpc.WithTransportCredentials() to set)") - // errCredentialsConflict indicates that grpc.WithTransportCredentials() - // and grpc.WithInsecure() are both called for a connection. - errCredentialsConflict = errors.New("grpc: transport credentials are set for an insecure connection (grpc.WithTransportCredentials() and grpc.WithInsecure() are both called)") - // errNetworkIO indicates that the connection is down due to some network I/O error. - errNetworkIO = errors.New("grpc: failed with network I/O error") -) - -// dialOptions configure a Dial call. dialOptions are set by the DialOption -// values passed to Dial. -type dialOptions struct { - unaryInt UnaryClientInterceptor - streamInt StreamClientInterceptor - cp Compressor - dc Decompressor - bs backoffStrategy - block bool - insecure bool - timeout time.Duration - scChan <-chan ServiceConfig - copts transport.ConnectOptions - callOptions []CallOption - // This is used by v1 balancer dial option WithBalancer to support v1 - // balancer, and also by WithBalancerName dial option. - balancerBuilder balancer.Builder - // This is to support grpclb. - resolverBuilder resolver.Builder - waitForHandshake bool - channelzParentID int64 - disableServiceConfig bool -} - -const ( - defaultClientMaxReceiveMessageSize = 1024 * 1024 * 4 - defaultClientMaxSendMessageSize = math.MaxInt32 -) - -// RegisterChannelz turns on channelz service. -// This is an EXPERIMENTAL API. -func RegisterChannelz() { - channelz.TurnOn() -} - -// DialOption configures how we set up the connection. -type DialOption func(*dialOptions) - -// WithWaitForHandshake blocks until the initial settings frame is received from the -// server before assigning RPCs to the connection. -// Experimental API. -func WithWaitForHandshake() DialOption { - return func(o *dialOptions) { - o.waitForHandshake = true - } -} - -// WithWriteBufferSize lets you set the size of write buffer, this determines how much data can be batched -// before doing a write on the wire. -func WithWriteBufferSize(s int) DialOption { - return func(o *dialOptions) { - o.copts.WriteBufferSize = s - } -} - -// WithReadBufferSize lets you set the size of read buffer, this determines how much data can be read at most -// for each read syscall. -func WithReadBufferSize(s int) DialOption { - return func(o *dialOptions) { - o.copts.ReadBufferSize = s - } -} - -// WithInitialWindowSize returns a DialOption which sets the value for initial window size on a stream. -// The lower bound for window size is 64K and any value smaller than that will be ignored. -func WithInitialWindowSize(s int32) DialOption { - return func(o *dialOptions) { - o.copts.InitialWindowSize = s - } -} - -// WithInitialConnWindowSize returns a DialOption which sets the value for initial window size on a connection. -// The lower bound for window size is 64K and any value smaller than that will be ignored. -func WithInitialConnWindowSize(s int32) DialOption { - return func(o *dialOptions) { - o.copts.InitialConnWindowSize = s - } -} - -// WithMaxMsgSize returns a DialOption which sets the maximum message size the client can receive. -// -// Deprecated: use WithDefaultCallOptions(MaxCallRecvMsgSize(s)) instead. -func WithMaxMsgSize(s int) DialOption { - return WithDefaultCallOptions(MaxCallRecvMsgSize(s)) -} - -// WithDefaultCallOptions returns a DialOption which sets the default CallOptions for calls over the connection. -func WithDefaultCallOptions(cos ...CallOption) DialOption { - return func(o *dialOptions) { - o.callOptions = append(o.callOptions, cos...) - } -} - -// WithCodec returns a DialOption which sets a codec for message marshaling and unmarshaling. -// -// Deprecated: use WithDefaultCallOptions(CallCustomCodec(c)) instead. -func WithCodec(c Codec) DialOption { - return WithDefaultCallOptions(CallCustomCodec(c)) -} - -// WithCompressor returns a DialOption which sets a Compressor to use for -// message compression. It has lower priority than the compressor set by -// the UseCompressor CallOption. -// -// Deprecated: use UseCompressor instead. -func WithCompressor(cp Compressor) DialOption { - return func(o *dialOptions) { - o.cp = cp - } -} - -// WithDecompressor returns a DialOption which sets a Decompressor to use for -// incoming message decompression. If incoming response messages are encoded -// using the decompressor's Type(), it will be used. Otherwise, the message -// encoding will be used to look up the compressor registered via -// encoding.RegisterCompressor, which will then be used to decompress the -// message. If no compressor is registered for the encoding, an Unimplemented -// status error will be returned. -// -// Deprecated: use encoding.RegisterCompressor instead. -func WithDecompressor(dc Decompressor) DialOption { - return func(o *dialOptions) { - o.dc = dc - } -} - -// WithBalancer returns a DialOption which sets a load balancer with the v1 API. -// Name resolver will be ignored if this DialOption is specified. -// -// Deprecated: use the new balancer APIs in balancer package and WithBalancerName. -func WithBalancer(b Balancer) DialOption { - return func(o *dialOptions) { - o.balancerBuilder = &balancerWrapperBuilder{ - b: b, - } - } -} - -// WithBalancerName sets the balancer that the ClientConn will be initialized -// with. Balancer registered with balancerName will be used. This function -// panics if no balancer was registered by balancerName. -// -// The balancer cannot be overridden by balancer option specified by service -// config. -// -// This is an EXPERIMENTAL API. -func WithBalancerName(balancerName string) DialOption { - builder := balancer.Get(balancerName) - if builder == nil { - panic(fmt.Sprintf("grpc.WithBalancerName: no balancer is registered for name %v", balancerName)) - } - return func(o *dialOptions) { - o.balancerBuilder = builder - } -} - -// withResolverBuilder is only for grpclb. -func withResolverBuilder(b resolver.Builder) DialOption { - return func(o *dialOptions) { - o.resolverBuilder = b - } -} - -// WithServiceConfig returns a DialOption which has a channel to read the service configuration. -// -// Deprecated: service config should be received through name resolver, as specified here. -// https://github.com/grpc/grpc/blob/master/doc/service_config.md -func WithServiceConfig(c <-chan ServiceConfig) DialOption { - return func(o *dialOptions) { - o.scChan = c - } -} - -// WithBackoffMaxDelay configures the dialer to use the provided maximum delay -// when backing off after failed connection attempts. -func WithBackoffMaxDelay(md time.Duration) DialOption { - return WithBackoffConfig(BackoffConfig{MaxDelay: md}) -} - -// WithBackoffConfig configures the dialer to use the provided backoff -// parameters after connection failures. -// -// Use WithBackoffMaxDelay until more parameters on BackoffConfig are opened up -// for use. -func WithBackoffConfig(b BackoffConfig) DialOption { - // Set defaults to ensure that provided BackoffConfig is valid and - // unexported fields get default values. - setDefaults(&b) - return withBackoff(b) -} - -// withBackoff sets the backoff strategy used for connectRetryNum after a -// failed connection attempt. -// -// This can be exported if arbitrary backoff strategies are allowed by gRPC. -func withBackoff(bs backoffStrategy) DialOption { - return func(o *dialOptions) { - o.bs = bs - } -} - -// WithBlock returns a DialOption which makes caller of Dial blocks until the underlying -// connection is up. Without this, Dial returns immediately and connecting the server -// happens in background. -func WithBlock() DialOption { - return func(o *dialOptions) { - o.block = true - } -} - -// WithInsecure returns a DialOption which disables transport security for this ClientConn. -// Note that transport security is required unless WithInsecure is set. -func WithInsecure() DialOption { - return func(o *dialOptions) { - o.insecure = true - } -} - -// WithTransportCredentials returns a DialOption which configures a -// connection level security credentials (e.g., TLS/SSL). -func WithTransportCredentials(creds credentials.TransportCredentials) DialOption { - return func(o *dialOptions) { - o.copts.TransportCredentials = creds - } -} - -// WithPerRPCCredentials returns a DialOption which sets -// credentials and places auth state on each outbound RPC. -func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption { - return func(o *dialOptions) { - o.copts.PerRPCCredentials = append(o.copts.PerRPCCredentials, creds) - } -} - -// WithTimeout returns a DialOption that configures a timeout for dialing a ClientConn -// initially. This is valid if and only if WithBlock() is present. -// -// Deprecated: use DialContext and context.WithTimeout instead. -func WithTimeout(d time.Duration) DialOption { - return func(o *dialOptions) { - o.timeout = d - } -} - -func withContextDialer(f func(context.Context, string) (net.Conn, error)) DialOption { - return func(o *dialOptions) { - o.copts.Dialer = f - } -} - -// WithDialer returns a DialOption that specifies a function to use for dialing network addresses. -// If FailOnNonTempDialError() is set to true, and an error is returned by f, gRPC checks the error's -// Temporary() method to decide if it should try to reconnect to the network address. -func WithDialer(f func(string, time.Duration) (net.Conn, error)) DialOption { - return withContextDialer( - func(ctx context.Context, addr string) (net.Conn, error) { - if deadline, ok := ctx.Deadline(); ok { - return f(addr, deadline.Sub(time.Now())) - } - return f(addr, 0) - }) -} - -// WithStatsHandler returns a DialOption that specifies the stats handler -// for all the RPCs and underlying network connections in this ClientConn. -func WithStatsHandler(h stats.Handler) DialOption { - return func(o *dialOptions) { - o.copts.StatsHandler = h - } -} - -// FailOnNonTempDialError returns a DialOption that specifies if gRPC fails on non-temporary dial errors. -// If f is true, and dialer returns a non-temporary error, gRPC will fail the connection to the network -// address and won't try to reconnect. -// The default value of FailOnNonTempDialError is false. -// This is an EXPERIMENTAL API. -func FailOnNonTempDialError(f bool) DialOption { - return func(o *dialOptions) { - o.copts.FailOnNonTempDialError = f - } -} - -// WithUserAgent returns a DialOption that specifies a user agent string for all the RPCs. -func WithUserAgent(s string) DialOption { - return func(o *dialOptions) { - o.copts.UserAgent = s - } -} - -// WithKeepaliveParams returns a DialOption that specifies keepalive parameters for the client transport. -func WithKeepaliveParams(kp keepalive.ClientParameters) DialOption { - return func(o *dialOptions) { - o.copts.KeepaliveParams = kp - } -} - -// WithUnaryInterceptor returns a DialOption that specifies the interceptor for unary RPCs. -func WithUnaryInterceptor(f UnaryClientInterceptor) DialOption { - return func(o *dialOptions) { - o.unaryInt = f - } -} - -// WithStreamInterceptor returns a DialOption that specifies the interceptor for streaming RPCs. -func WithStreamInterceptor(f StreamClientInterceptor) DialOption { - return func(o *dialOptions) { - o.streamInt = f - } -} - -// WithAuthority returns a DialOption that specifies the value to be used as -// the :authority pseudo-header. This value only works with WithInsecure and -// has no effect if TransportCredentials are present. -func WithAuthority(a string) DialOption { - return func(o *dialOptions) { - o.copts.Authority = a - } -} - -// WithChannelzParentID returns a DialOption that specifies the channelz ID of current ClientConn's -// parent. This function is used in nested channel creation (e.g. grpclb dial). -func WithChannelzParentID(id int64) DialOption { - return func(o *dialOptions) { - o.channelzParentID = id - } -} - -// WithDisableServiceConfig returns a DialOption that causes grpc to ignore any -// service config provided by the resolver and provides a hint to the resolver -// to not fetch service configs. -func WithDisableServiceConfig() DialOption { - return func(o *dialOptions) { - o.disableServiceConfig = true - } -} - -// Dial creates a client connection to the given target. -func Dial(target string, opts ...DialOption) (*ClientConn, error) { - return DialContext(context.Background(), target, opts...) -} - -// DialContext creates a client connection to the given target. By default, it's -// a non-blocking dial (the function won't wait for connections to be -// established, and connecting happens in the background). To make it a blocking -// dial, use WithBlock() dial option. -// -// In the non-blocking case, the ctx does not act against the connection. It -// only controls the setup steps. -// -// In the blocking case, ctx can be used to cancel or expire the pending -// connection. Once this function returns, the cancellation and expiration of -// ctx will be noop. Users should call ClientConn.Close to terminate all the -// pending operations after this function returns. -// -// The target name syntax is defined in -// https://github.com/grpc/grpc/blob/master/doc/naming.md. -// e.g. to use dns resolver, a "dns:///" prefix should be applied to the target. -func DialContext(ctx context.Context, target string, opts ...DialOption) (conn *ClientConn, err error) { - cc := &ClientConn{ - target: target, - csMgr: &connectivityStateManager{}, - conns: make(map[*addrConn]struct{}), - - blockingpicker: newPickerWrapper(), - } - cc.ctx, cc.cancel = context.WithCancel(context.Background()) - - for _, opt := range opts { - opt(&cc.dopts) - } - - if channelz.IsOn() { - if cc.dopts.channelzParentID != 0 { - cc.channelzID = channelz.RegisterChannel(cc, cc.dopts.channelzParentID, target) - } else { - cc.channelzID = channelz.RegisterChannel(cc, 0, target) - } - } - - if !cc.dopts.insecure { - if cc.dopts.copts.TransportCredentials == nil { - return nil, errNoTransportSecurity - } - } else { - if cc.dopts.copts.TransportCredentials != nil { - return nil, errCredentialsConflict - } - for _, cd := range cc.dopts.copts.PerRPCCredentials { - if cd.RequireTransportSecurity() { - return nil, errTransportCredentialsMissing - } - } - } - - cc.mkp = cc.dopts.copts.KeepaliveParams - - if cc.dopts.copts.Dialer == nil { - cc.dopts.copts.Dialer = newProxyDialer( - func(ctx context.Context, addr string) (net.Conn, error) { - network, addr := parseDialTarget(addr) - return dialContext(ctx, network, addr) - }, - ) - } - - if cc.dopts.copts.UserAgent != "" { - cc.dopts.copts.UserAgent += " " + grpcUA - } else { - cc.dopts.copts.UserAgent = grpcUA - } - - if cc.dopts.timeout > 0 { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, cc.dopts.timeout) - defer cancel() - } - - defer func() { - select { - case <-ctx.Done(): - conn, err = nil, ctx.Err() - default: - } - - if err != nil { - cc.Close() - } - }() - - scSet := false - if cc.dopts.scChan != nil { - // Try to get an initial service config. - select { - case sc, ok := <-cc.dopts.scChan: - if ok { - cc.sc = sc - scSet = true - } - default: - } - } - if cc.dopts.bs == nil { - cc.dopts.bs = DefaultBackoffConfig - } - if cc.dopts.resolverBuilder == nil { - // Only try to parse target when resolver builder is not already set. - cc.parsedTarget = parseTarget(cc.target) - grpclog.Infof("parsed scheme: %q", cc.parsedTarget.Scheme) - cc.dopts.resolverBuilder = resolver.Get(cc.parsedTarget.Scheme) - if cc.dopts.resolverBuilder == nil { - // If resolver builder is still nil, the parse target's scheme is - // not registered. Fallback to default resolver and set Endpoint to - // the original unparsed target. - grpclog.Infof("scheme %q not registered, fallback to default scheme", cc.parsedTarget.Scheme) - cc.parsedTarget = resolver.Target{ - Scheme: resolver.GetDefaultScheme(), - Endpoint: target, - } - cc.dopts.resolverBuilder = resolver.Get(cc.parsedTarget.Scheme) - } - } else { - cc.parsedTarget = resolver.Target{Endpoint: target} - } - creds := cc.dopts.copts.TransportCredentials - if creds != nil && creds.Info().ServerName != "" { - cc.authority = creds.Info().ServerName - } else if cc.dopts.insecure && cc.dopts.copts.Authority != "" { - cc.authority = cc.dopts.copts.Authority - } else { - // Use endpoint from "scheme://authority/endpoint" as the default - // authority for ClientConn. - cc.authority = cc.parsedTarget.Endpoint - } - - if cc.dopts.scChan != nil && !scSet { - // Blocking wait for the initial service config. - select { - case sc, ok := <-cc.dopts.scChan: - if ok { - cc.sc = sc - } - case <-ctx.Done(): - return nil, ctx.Err() - } - } - if cc.dopts.scChan != nil { - go cc.scWatcher() - } - - var credsClone credentials.TransportCredentials - if creds := cc.dopts.copts.TransportCredentials; creds != nil { - credsClone = creds.Clone() - } - cc.balancerBuildOpts = balancer.BuildOptions{ - DialCreds: credsClone, - Dialer: cc.dopts.copts.Dialer, - ChannelzParentID: cc.channelzID, - } - - // Build the resolver. - cc.resolverWrapper, err = newCCResolverWrapper(cc) - if err != nil { - return nil, fmt.Errorf("failed to build resolver: %v", err) - } - // Start the resolver wrapper goroutine after resolverWrapper is created. - // - // If the goroutine is started before resolverWrapper is ready, the - // following may happen: The goroutine sends updates to cc. cc forwards - // those to balancer. Balancer creates new addrConn. addrConn fails to - // connect, and calls resolveNow(). resolveNow() tries to use the non-ready - // resolverWrapper. - cc.resolverWrapper.start() - - // A blocking dial blocks until the clientConn is ready. - if cc.dopts.block { - for { - s := cc.GetState() - if s == connectivity.Ready { - break - } - if !cc.WaitForStateChange(ctx, s) { - // ctx got timeout or canceled. - return nil, ctx.Err() - } - } - } - - return cc, nil -} - -// connectivityStateManager keeps the connectivity.State of ClientConn. -// This struct will eventually be exported so the balancers can access it. -type connectivityStateManager struct { - mu sync.Mutex - state connectivity.State - notifyChan chan struct{} -} - -// updateState updates the connectivity.State of ClientConn. -// If there's a change it notifies goroutines waiting on state change to -// happen. -func (csm *connectivityStateManager) updateState(state connectivity.State) { - csm.mu.Lock() - defer csm.mu.Unlock() - if csm.state == connectivity.Shutdown { - return - } - if csm.state == state { - return - } - csm.state = state - if csm.notifyChan != nil { - // There are other goroutines waiting on this channel. - close(csm.notifyChan) - csm.notifyChan = nil - } -} - -func (csm *connectivityStateManager) getState() connectivity.State { - csm.mu.Lock() - defer csm.mu.Unlock() - return csm.state -} - -func (csm *connectivityStateManager) getNotifyChan() <-chan struct{} { - csm.mu.Lock() - defer csm.mu.Unlock() - if csm.notifyChan == nil { - csm.notifyChan = make(chan struct{}) - } - return csm.notifyChan -} - -// ClientConn represents a client connection to an RPC server. -type ClientConn struct { - ctx context.Context - cancel context.CancelFunc - - target string - parsedTarget resolver.Target - authority string - dopts dialOptions - csMgr *connectivityStateManager - - balancerBuildOpts balancer.BuildOptions - resolverWrapper *ccResolverWrapper - blockingpicker *pickerWrapper - - mu sync.RWMutex - sc ServiceConfig - scRaw string - conns map[*addrConn]struct{} - // Keepalive parameter can be updated if a GoAway is received. - mkp keepalive.ClientParameters - curBalancerName string - preBalancerName string // previous balancer name. - curAddresses []resolver.Address - balancerWrapper *ccBalancerWrapper - - channelzID int64 // channelz unique identification number - czmu sync.RWMutex - callsStarted int64 - callsSucceeded int64 - callsFailed int64 - lastCallStartedTime time.Time -} - -// WaitForStateChange waits until the connectivity.State of ClientConn changes from sourceState or -// ctx expires. A true value is returned in former case and false in latter. -// This is an EXPERIMENTAL API. -func (cc *ClientConn) WaitForStateChange(ctx context.Context, sourceState connectivity.State) bool { - ch := cc.csMgr.getNotifyChan() - if cc.csMgr.getState() != sourceState { - return true - } - select { - case <-ctx.Done(): - return false - case <-ch: - return true - } -} - -// GetState returns the connectivity.State of ClientConn. -// This is an EXPERIMENTAL API. -func (cc *ClientConn) GetState() connectivity.State { - return cc.csMgr.getState() -} - -func (cc *ClientConn) scWatcher() { - for { - select { - case sc, ok := <-cc.dopts.scChan: - if !ok { - return - } - cc.mu.Lock() - // TODO: load balance policy runtime change is ignored. - // We may revist this decision in the future. - cc.sc = sc - cc.scRaw = "" - cc.mu.Unlock() - case <-cc.ctx.Done(): - return - } - } -} - -func (cc *ClientConn) handleResolvedAddrs(addrs []resolver.Address, err error) { - cc.mu.Lock() - defer cc.mu.Unlock() - if cc.conns == nil { - // cc was closed. - return - } - - if reflect.DeepEqual(cc.curAddresses, addrs) { - return - } - - cc.curAddresses = addrs - - if cc.dopts.balancerBuilder == nil { - // Only look at balancer types and switch balancer if balancer dial - // option is not set. - var isGRPCLB bool - for _, a := range addrs { - if a.Type == resolver.GRPCLB { - isGRPCLB = true - break - } - } - var newBalancerName string - if isGRPCLB { - newBalancerName = grpclbName - } else { - // Address list doesn't contain grpclb address. Try to pick a - // non-grpclb balancer. - newBalancerName = cc.curBalancerName - // If current balancer is grpclb, switch to the previous one. - if newBalancerName == grpclbName { - newBalancerName = cc.preBalancerName - } - // The following could be true in two cases: - // - the first time handling resolved addresses - // (curBalancerName="") - // - the first time handling non-grpclb addresses - // (curBalancerName="grpclb", preBalancerName="") - if newBalancerName == "" { - newBalancerName = PickFirstBalancerName - } - } - cc.switchBalancer(newBalancerName) - } else if cc.balancerWrapper == nil { - // Balancer dial option was set, and this is the first time handling - // resolved addresses. Build a balancer with dopts.balancerBuilder. - cc.balancerWrapper = newCCBalancerWrapper(cc, cc.dopts.balancerBuilder, cc.balancerBuildOpts) - } - - cc.balancerWrapper.handleResolvedAddrs(addrs, nil) -} - -// switchBalancer starts the switching from current balancer to the balancer -// with the given name. -// -// It will NOT send the current address list to the new balancer. If needed, -// caller of this function should send address list to the new balancer after -// this function returns. -// -// Caller must hold cc.mu. -func (cc *ClientConn) switchBalancer(name string) { - if cc.conns == nil { - return - } - - if strings.ToLower(cc.curBalancerName) == strings.ToLower(name) { - return - } - - grpclog.Infof("ClientConn switching balancer to %q", name) - if cc.dopts.balancerBuilder != nil { - grpclog.Infoln("ignoring balancer switching: Balancer DialOption used instead") - return - } - // TODO(bar switching) change this to two steps: drain and close. - // Keep track of sc in wrapper. - if cc.balancerWrapper != nil { - cc.balancerWrapper.close() - } - // Clear all stickiness state. - cc.blockingpicker.clearStickinessState() - - builder := balancer.Get(name) - if builder == nil { - grpclog.Infof("failed to get balancer builder for: %v, using pick_first instead", name) - builder = newPickfirstBuilder() - } - cc.preBalancerName = cc.curBalancerName - cc.curBalancerName = builder.Name() - cc.balancerWrapper = newCCBalancerWrapper(cc, builder, cc.balancerBuildOpts) -} - -func (cc *ClientConn) handleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { - cc.mu.Lock() - if cc.conns == nil { - cc.mu.Unlock() - return - } - // TODO(bar switching) send updates to all balancer wrappers when balancer - // gracefully switching is supported. - cc.balancerWrapper.handleSubConnStateChange(sc, s) - cc.mu.Unlock() -} - -// newAddrConn creates an addrConn for addrs and adds it to cc.conns. -// -// Caller needs to make sure len(addrs) > 0. -func (cc *ClientConn) newAddrConn(addrs []resolver.Address) (*addrConn, error) { - ac := &addrConn{ - cc: cc, - addrs: addrs, - dopts: cc.dopts, - } - ac.ctx, ac.cancel = context.WithCancel(cc.ctx) - // Track ac in cc. This needs to be done before any getTransport(...) is called. - cc.mu.Lock() - if cc.conns == nil { - cc.mu.Unlock() - return nil, ErrClientConnClosing - } - if channelz.IsOn() { - ac.channelzID = channelz.RegisterSubChannel(ac, cc.channelzID, "") - } - cc.conns[ac] = struct{}{} - cc.mu.Unlock() - return ac, nil -} - -// removeAddrConn removes the addrConn in the subConn from clientConn. -// It also tears down the ac with the given error. -func (cc *ClientConn) removeAddrConn(ac *addrConn, err error) { - cc.mu.Lock() - if cc.conns == nil { - cc.mu.Unlock() - return - } - delete(cc.conns, ac) - cc.mu.Unlock() - ac.tearDown(err) -} - -// ChannelzMetric returns ChannelInternalMetric of current ClientConn. -// This is an EXPERIMENTAL API. -func (cc *ClientConn) ChannelzMetric() *channelz.ChannelInternalMetric { - state := cc.GetState() - cc.czmu.RLock() - defer cc.czmu.RUnlock() - return &channelz.ChannelInternalMetric{ - State: state, - Target: cc.target, - CallsStarted: cc.callsStarted, - CallsSucceeded: cc.callsSucceeded, - CallsFailed: cc.callsFailed, - LastCallStartedTimestamp: cc.lastCallStartedTime, - } -} - -func (cc *ClientConn) incrCallsStarted() { - cc.czmu.Lock() - cc.callsStarted++ - // TODO(yuxuanli): will make this a time.Time pointer improve performance? - cc.lastCallStartedTime = time.Now() - cc.czmu.Unlock() -} - -func (cc *ClientConn) incrCallsSucceeded() { - cc.czmu.Lock() - cc.callsSucceeded++ - cc.czmu.Unlock() -} - -func (cc *ClientConn) incrCallsFailed() { - cc.czmu.Lock() - cc.callsFailed++ - cc.czmu.Unlock() -} - -// connect starts to creating transport and also starts the transport monitor -// goroutine for this ac. -// It does nothing if the ac is not IDLE. -// TODO(bar) Move this to the addrConn section. -// This was part of resetAddrConn, keep it here to make the diff look clean. -func (ac *addrConn) connect() error { - ac.mu.Lock() - if ac.state == connectivity.Shutdown { - ac.mu.Unlock() - return errConnClosing - } - if ac.state != connectivity.Idle { - ac.mu.Unlock() - return nil - } - ac.state = connectivity.Connecting - ac.cc.handleSubConnStateChange(ac.acbw, ac.state) - ac.mu.Unlock() - - // Start a goroutine connecting to the server asynchronously. - go func() { - if err := ac.resetTransport(); err != nil { - grpclog.Warningf("Failed to dial %s: %v; please retry.", ac.addrs[0].Addr, err) - if err != errConnClosing { - // Keep this ac in cc.conns, to get the reason it's torn down. - ac.tearDown(err) - } - return - } - ac.transportMonitor() - }() - return nil -} - -// tryUpdateAddrs tries to update ac.addrs with the new addresses list. -// -// It checks whether current connected address of ac is in the new addrs list. -// - If true, it updates ac.addrs and returns true. The ac will keep using -// the existing connection. -// - If false, it does nothing and returns false. -func (ac *addrConn) tryUpdateAddrs(addrs []resolver.Address) bool { - ac.mu.Lock() - defer ac.mu.Unlock() - grpclog.Infof("addrConn: tryUpdateAddrs curAddr: %v, addrs: %v", ac.curAddr, addrs) - if ac.state == connectivity.Shutdown { - ac.addrs = addrs - return true - } - - var curAddrFound bool - for _, a := range addrs { - if reflect.DeepEqual(ac.curAddr, a) { - curAddrFound = true - break - } - } - grpclog.Infof("addrConn: tryUpdateAddrs curAddrFound: %v", curAddrFound) - if curAddrFound { - ac.addrs = addrs - ac.reconnectIdx = 0 // Start reconnecting from beginning in the new list. - } - - return curAddrFound -} - -// GetMethodConfig gets the method config of the input method. -// If there's an exact match for input method (i.e. /service/method), we return -// the corresponding MethodConfig. -// If there isn't an exact match for the input method, we look for the default config -// under the service (i.e /service/). If there is a default MethodConfig for -// the service, we return it. -// Otherwise, we return an empty MethodConfig. -func (cc *ClientConn) GetMethodConfig(method string) MethodConfig { - // TODO: Avoid the locking here. - cc.mu.RLock() - defer cc.mu.RUnlock() - m, ok := cc.sc.Methods[method] - if !ok { - i := strings.LastIndex(method, "/") - m = cc.sc.Methods[method[:i+1]] - } - return m -} - -func (cc *ClientConn) getTransport(ctx context.Context, failfast bool) (transport.ClientTransport, func(balancer.DoneInfo), error) { - t, done, err := cc.blockingpicker.pick(ctx, failfast, balancer.PickOptions{}) - if err != nil { - return nil, nil, toRPCErr(err) - } - return t, done, nil -} - -// handleServiceConfig parses the service config string in JSON format to Go native -// struct ServiceConfig, and store both the struct and the JSON string in ClientConn. -func (cc *ClientConn) handleServiceConfig(js string) error { - if cc.dopts.disableServiceConfig { - return nil - } - sc, err := parseServiceConfig(js) - if err != nil { - return err - } - cc.mu.Lock() - cc.scRaw = js - cc.sc = sc - if sc.LB != nil && *sc.LB != grpclbName { // "grpclb" is not a valid balancer option in service config. - if cc.curBalancerName == grpclbName { - // If current balancer is grpclb, there's at least one grpclb - // balancer address in the resolved list. Don't switch the balancer, - // but change the previous balancer name, so if a new resolved - // address list doesn't contain grpclb address, balancer will be - // switched to *sc.LB. - cc.preBalancerName = *sc.LB - } else { - cc.switchBalancer(*sc.LB) - cc.balancerWrapper.handleResolvedAddrs(cc.curAddresses, nil) - } - } - - if envConfigStickinessOn { - var newStickinessMDKey string - if sc.stickinessMetadataKey != nil && *sc.stickinessMetadataKey != "" { - newStickinessMDKey = *sc.stickinessMetadataKey - } - // newStickinessMDKey is "" if one of the following happens: - // - stickinessMetadataKey is set to "" - // - stickinessMetadataKey field doesn't exist in service config - cc.blockingpicker.updateStickinessMDKey(strings.ToLower(newStickinessMDKey)) - } - - cc.mu.Unlock() - return nil -} - -func (cc *ClientConn) resolveNow(o resolver.ResolveNowOption) { - cc.mu.Lock() - r := cc.resolverWrapper - cc.mu.Unlock() - if r == nil { - return - } - go r.resolveNow(o) -} - -// Close tears down the ClientConn and all underlying connections. -func (cc *ClientConn) Close() error { - defer cc.cancel() - - cc.mu.Lock() - if cc.conns == nil { - cc.mu.Unlock() - return ErrClientConnClosing - } - conns := cc.conns - cc.conns = nil - cc.csMgr.updateState(connectivity.Shutdown) - - rWrapper := cc.resolverWrapper - cc.resolverWrapper = nil - bWrapper := cc.balancerWrapper - cc.balancerWrapper = nil - cc.mu.Unlock() - - cc.blockingpicker.close() - - if rWrapper != nil { - rWrapper.close() - } - if bWrapper != nil { - bWrapper.close() - } - - for ac := range conns { - ac.tearDown(ErrClientConnClosing) - } - if channelz.IsOn() { - channelz.RemoveEntry(cc.channelzID) - } - return nil -} - -// addrConn is a network connection to a given address. -type addrConn struct { - ctx context.Context - cancel context.CancelFunc - - cc *ClientConn - addrs []resolver.Address - dopts dialOptions - events trace.EventLog - acbw balancer.SubConn - - mu sync.Mutex - curAddr resolver.Address - reconnectIdx int // The index in addrs list to start reconnecting from. - state connectivity.State - // ready is closed and becomes nil when a new transport is up or failed - // due to timeout. - ready chan struct{} - transport transport.ClientTransport - - // The reason this addrConn is torn down. - tearDownErr error - - connectRetryNum int - // backoffDeadline is the time until which resetTransport needs to - // wait before increasing connectRetryNum count. - backoffDeadline time.Time - // connectDeadline is the time by which all connection - // negotiations must complete. - connectDeadline time.Time - - channelzID int64 // channelz unique identification number - czmu sync.RWMutex - callsStarted int64 - callsSucceeded int64 - callsFailed int64 - lastCallStartedTime time.Time -} - -// adjustParams updates parameters used to create transports upon -// receiving a GoAway. -func (ac *addrConn) adjustParams(r transport.GoAwayReason) { - switch r { - case transport.GoAwayTooManyPings: - v := 2 * ac.dopts.copts.KeepaliveParams.Time - ac.cc.mu.Lock() - if v > ac.cc.mkp.Time { - ac.cc.mkp.Time = v - } - ac.cc.mu.Unlock() - } -} - -// printf records an event in ac's event log, unless ac has been closed. -// REQUIRES ac.mu is held. -func (ac *addrConn) printf(format string, a ...interface{}) { - if ac.events != nil { - ac.events.Printf(format, a...) - } -} - -// errorf records an error in ac's event log, unless ac has been closed. -// REQUIRES ac.mu is held. -func (ac *addrConn) errorf(format string, a ...interface{}) { - if ac.events != nil { - ac.events.Errorf(format, a...) - } -} - -// resetTransport recreates a transport to the address for ac. The old -// transport will close itself on error or when the clientconn is closed. -// The created transport must receive initial settings frame from the server. -// In case that doesn't happen, transportMonitor will kill the newly created -// transport after connectDeadline has expired. -// In case there was an error on the transport before the settings frame was -// received, resetTransport resumes connecting to backends after the one that -// was previously connected to. In case end of the list is reached, resetTransport -// backs off until the original deadline. -// If the DialOption WithWaitForHandshake was set, resetTrasport returns -// successfully only after server settings are received. -// -// TODO(bar) make sure all state transitions are valid. -func (ac *addrConn) resetTransport() error { - ac.mu.Lock() - if ac.state == connectivity.Shutdown { - ac.mu.Unlock() - return errConnClosing - } - if ac.ready != nil { - close(ac.ready) - ac.ready = nil - } - ac.transport = nil - ridx := ac.reconnectIdx - ac.mu.Unlock() - ac.cc.mu.RLock() - ac.dopts.copts.KeepaliveParams = ac.cc.mkp - ac.cc.mu.RUnlock() - var backoffDeadline, connectDeadline time.Time - for connectRetryNum := 0; ; connectRetryNum++ { - ac.mu.Lock() - if ac.backoffDeadline.IsZero() { - // This means either a successful HTTP2 connection was established - // or this is the first time this addrConn is trying to establish a - // connection. - backoffFor := ac.dopts.bs.backoff(connectRetryNum) // time.Duration. - // This will be the duration that dial gets to finish. - dialDuration := getMinConnectTimeout() - if backoffFor > dialDuration { - // Give dial more time as we keep failing to connect. - dialDuration = backoffFor - } - start := time.Now() - backoffDeadline = start.Add(backoffFor) - connectDeadline = start.Add(dialDuration) - ridx = 0 // Start connecting from the beginning. - } else { - // Continue trying to connect with the same deadlines. - connectRetryNum = ac.connectRetryNum - backoffDeadline = ac.backoffDeadline - connectDeadline = ac.connectDeadline - ac.backoffDeadline = time.Time{} - ac.connectDeadline = time.Time{} - ac.connectRetryNum = 0 - } - if ac.state == connectivity.Shutdown { - ac.mu.Unlock() - return errConnClosing - } - ac.printf("connecting") - if ac.state != connectivity.Connecting { - ac.state = connectivity.Connecting - ac.cc.handleSubConnStateChange(ac.acbw, ac.state) - } - // copy ac.addrs in case of race - addrsIter := make([]resolver.Address, len(ac.addrs)) - copy(addrsIter, ac.addrs) - copts := ac.dopts.copts - ac.mu.Unlock() - connected, err := ac.createTransport(connectRetryNum, ridx, backoffDeadline, connectDeadline, addrsIter, copts) - if err != nil { - return err - } - if connected { - return nil - } - } -} - -// createTransport creates a connection to one of the backends in addrs. -// It returns true if a connection was established. -func (ac *addrConn) createTransport(connectRetryNum, ridx int, backoffDeadline, connectDeadline time.Time, addrs []resolver.Address, copts transport.ConnectOptions) (bool, error) { - for i := ridx; i < len(addrs); i++ { - addr := addrs[i] - target := transport.TargetInfo{ - Addr: addr.Addr, - Metadata: addr.Metadata, - Authority: ac.cc.authority, - } - done := make(chan struct{}) - onPrefaceReceipt := func() { - ac.mu.Lock() - close(done) - if !ac.backoffDeadline.IsZero() { - // If we haven't already started reconnecting to - // other backends. - // Note, this can happen when writer notices an error - // and triggers resetTransport while at the same time - // reader receives the preface and invokes this closure. - ac.backoffDeadline = time.Time{} - ac.connectDeadline = time.Time{} - ac.connectRetryNum = 0 - } - ac.mu.Unlock() - } - // Do not cancel in the success path because of - // this issue in Go1.6: https://github.com/golang/go/issues/15078. - connectCtx, cancel := context.WithDeadline(ac.ctx, connectDeadline) - if channelz.IsOn() { - copts.ChannelzParentID = ac.channelzID - } - newTr, err := transport.NewClientTransport(connectCtx, ac.cc.ctx, target, copts, onPrefaceReceipt) - if err != nil { - cancel() - ac.cc.blockingpicker.updateConnectionError(err) - ac.mu.Lock() - if ac.state == connectivity.Shutdown { - // ac.tearDown(...) has been invoked. - ac.mu.Unlock() - return false, errConnClosing - } - ac.mu.Unlock() - grpclog.Warningf("grpc: addrConn.createTransport failed to connect to %v. Err :%v. Reconnecting...", addr, err) - continue - } - if ac.dopts.waitForHandshake { - select { - case <-done: - case <-connectCtx.Done(): - // Didn't receive server preface, must kill this new transport now. - grpclog.Warningf("grpc: addrConn.createTransport failed to receive server preface before deadline.") - newTr.Close() - break - case <-ac.ctx.Done(): - } - } - ac.mu.Lock() - if ac.state == connectivity.Shutdown { - ac.mu.Unlock() - // ac.tearDonn(...) has been invoked. - newTr.Close() - return false, errConnClosing - } - ac.printf("ready") - ac.state = connectivity.Ready - ac.cc.handleSubConnStateChange(ac.acbw, ac.state) - ac.transport = newTr - ac.curAddr = addr - if ac.ready != nil { - close(ac.ready) - ac.ready = nil - } - select { - case <-done: - // If the server has responded back with preface already, - // don't set the reconnect parameters. - default: - ac.connectRetryNum = connectRetryNum - ac.backoffDeadline = backoffDeadline - ac.connectDeadline = connectDeadline - ac.reconnectIdx = i + 1 // Start reconnecting from the next backend in the list. - } - ac.mu.Unlock() - return true, nil - } - ac.mu.Lock() - if ac.state == connectivity.Shutdown { - ac.mu.Unlock() - return false, errConnClosing - } - ac.state = connectivity.TransientFailure - ac.cc.handleSubConnStateChange(ac.acbw, ac.state) - ac.cc.resolveNow(resolver.ResolveNowOption{}) - if ac.ready != nil { - close(ac.ready) - ac.ready = nil - } - ac.mu.Unlock() - timer := time.NewTimer(backoffDeadline.Sub(time.Now())) - select { - case <-timer.C: - case <-ac.ctx.Done(): - timer.Stop() - return false, ac.ctx.Err() - } - return false, nil -} - -// Run in a goroutine to track the error in transport and create the -// new transport if an error happens. It returns when the channel is closing. -func (ac *addrConn) transportMonitor() { - for { - var timer *time.Timer - var cdeadline <-chan time.Time - ac.mu.Lock() - t := ac.transport - if !ac.connectDeadline.IsZero() { - timer = time.NewTimer(ac.connectDeadline.Sub(time.Now())) - cdeadline = timer.C - } - ac.mu.Unlock() - // Block until we receive a goaway or an error occurs. - select { - case <-t.GoAway(): - done := t.Error() - cleanup := t.Close - // Since this transport will be orphaned (won't have a transportMonitor) - // we need to launch a goroutine to keep track of clientConn.Close() - // happening since it might not be noticed by any other goroutine for a while. - go func() { - <-done - cleanup() - }() - case <-t.Error(): - // In case this is triggered because clientConn.Close() - // was called, we want to immeditately close the transport - // since no other goroutine might notice it for a while. - t.Close() - case <-cdeadline: - ac.mu.Lock() - // This implies that client received server preface. - if ac.backoffDeadline.IsZero() { - ac.mu.Unlock() - continue - } - ac.mu.Unlock() - timer = nil - // No server preface received until deadline. - // Kill the connection. - grpclog.Warningf("grpc: addrConn.transportMonitor didn't get server preface after waiting. Closing the new transport now.") - t.Close() - } - if timer != nil { - timer.Stop() - } - // If a GoAway happened, regardless of error, adjust our keepalive - // parameters as appropriate. - select { - case <-t.GoAway(): - ac.adjustParams(t.GetGoAwayReason()) - default: - } - ac.mu.Lock() - if ac.state == connectivity.Shutdown { - ac.mu.Unlock() - return - } - // Set connectivity state to TransientFailure before calling - // resetTransport. Transition READY->CONNECTING is not valid. - ac.state = connectivity.TransientFailure - ac.cc.handleSubConnStateChange(ac.acbw, ac.state) - ac.cc.resolveNow(resolver.ResolveNowOption{}) - ac.curAddr = resolver.Address{} - ac.mu.Unlock() - if err := ac.resetTransport(); err != nil { - ac.mu.Lock() - ac.printf("transport exiting: %v", err) - ac.mu.Unlock() - grpclog.Warningf("grpc: addrConn.transportMonitor exits due to: %v", err) - if err != errConnClosing { - // Keep this ac in cc.conns, to get the reason it's torn down. - ac.tearDown(err) - } - return - } - } -} - -// wait blocks until i) the new transport is up or ii) ctx is done or iii) ac is closed or -// iv) transport is in connectivity.TransientFailure and there is a balancer/failfast is true. -func (ac *addrConn) wait(ctx context.Context, hasBalancer, failfast bool) (transport.ClientTransport, error) { - for { - ac.mu.Lock() - switch { - case ac.state == connectivity.Shutdown: - if failfast || !hasBalancer { - // RPC is failfast or balancer is nil. This RPC should fail with ac.tearDownErr. - err := ac.tearDownErr - ac.mu.Unlock() - return nil, err - } - ac.mu.Unlock() - return nil, errConnClosing - case ac.state == connectivity.Ready: - ct := ac.transport - ac.mu.Unlock() - return ct, nil - case ac.state == connectivity.TransientFailure: - if failfast || hasBalancer { - ac.mu.Unlock() - return nil, errConnUnavailable - } - } - ready := ac.ready - if ready == nil { - ready = make(chan struct{}) - ac.ready = ready - } - ac.mu.Unlock() - select { - case <-ctx.Done(): - return nil, toRPCErr(ctx.Err()) - // Wait until the new transport is ready or failed. - case <-ready: - } - } -} - -// getReadyTransport returns the transport if ac's state is READY. -// Otherwise it returns nil, false. -// If ac's state is IDLE, it will trigger ac to connect. -func (ac *addrConn) getReadyTransport() (transport.ClientTransport, bool) { - ac.mu.Lock() - if ac.state == connectivity.Ready { - t := ac.transport - ac.mu.Unlock() - return t, true - } - var idle bool - if ac.state == connectivity.Idle { - idle = true - } - ac.mu.Unlock() - // Trigger idle ac to connect. - if idle { - ac.connect() - } - return nil, false -} - -// tearDown starts to tear down the addrConn. -// TODO(zhaoq): Make this synchronous to avoid unbounded memory consumption in -// some edge cases (e.g., the caller opens and closes many addrConn's in a -// tight loop. -// tearDown doesn't remove ac from ac.cc.conns. -func (ac *addrConn) tearDown(err error) { - ac.cancel() - ac.mu.Lock() - defer ac.mu.Unlock() - if ac.state == connectivity.Shutdown { - return - } - ac.curAddr = resolver.Address{} - if err == errConnDrain && ac.transport != nil { - // GracefulClose(...) may be executed multiple times when - // i) receiving multiple GoAway frames from the server; or - // ii) there are concurrent name resolver/Balancer triggered - // address removal and GoAway. - ac.transport.GracefulClose() - } - ac.state = connectivity.Shutdown - ac.tearDownErr = err - ac.cc.handleSubConnStateChange(ac.acbw, ac.state) - if ac.events != nil { - ac.events.Finish() - ac.events = nil - } - if ac.ready != nil { - close(ac.ready) - ac.ready = nil - } - if channelz.IsOn() { - channelz.RemoveEntry(ac.channelzID) - } -} - -func (ac *addrConn) getState() connectivity.State { - ac.mu.Lock() - defer ac.mu.Unlock() - return ac.state -} - -func (ac *addrConn) getCurAddr() (ret resolver.Address) { - ac.mu.Lock() - ret = ac.curAddr - ac.mu.Unlock() - return -} - -func (ac *addrConn) ChannelzMetric() *channelz.ChannelInternalMetric { - ac.mu.Lock() - addr := ac.curAddr.Addr - ac.mu.Unlock() - state := ac.getState() - ac.czmu.RLock() - defer ac.czmu.RUnlock() - return &channelz.ChannelInternalMetric{ - State: state, - Target: addr, - CallsStarted: ac.callsStarted, - CallsSucceeded: ac.callsSucceeded, - CallsFailed: ac.callsFailed, - LastCallStartedTimestamp: ac.lastCallStartedTime, - } -} - -func (ac *addrConn) incrCallsStarted() { - ac.czmu.Lock() - ac.callsStarted++ - ac.lastCallStartedTime = time.Now() - ac.czmu.Unlock() -} - -func (ac *addrConn) incrCallsSucceeded() { - ac.czmu.Lock() - ac.callsSucceeded++ - ac.czmu.Unlock() -} - -func (ac *addrConn) incrCallsFailed() { - ac.czmu.Lock() - ac.callsFailed++ - ac.czmu.Unlock() -} - -// ErrClientConnTimeout indicates that the ClientConn cannot establish the -// underlying connections within the specified timeout. -// -// Deprecated: This error is never returned by grpc and should not be -// referenced by users. -var ErrClientConnTimeout = errors.New("grpc: timed out when dialing") diff --git a/vendor/google.golang.org/grpc/codec.go b/vendor/google.golang.org/grpc/codec.go deleted file mode 100644 index 12977654781..00000000000 --- a/vendor/google.golang.org/grpc/codec.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 grpc - -import ( - "google.golang.org/grpc/encoding" - _ "google.golang.org/grpc/encoding/proto" // to register the Codec for "proto" -) - -// baseCodec contains the functionality of both Codec and encoding.Codec, but -// omits the name/string, which vary between the two and are not needed for -// anything besides the registry in the encoding package. -type baseCodec interface { - Marshal(v interface{}) ([]byte, error) - Unmarshal(data []byte, v interface{}) error -} - -var _ baseCodec = Codec(nil) -var _ baseCodec = encoding.Codec(nil) - -// Codec defines the interface gRPC uses to encode and decode messages. -// Note that implementations of this interface must be thread safe; -// a Codec's methods can be called from concurrent goroutines. -// -// Deprecated: use encoding.Codec instead. -type Codec interface { - // Marshal returns the wire format of v. - Marshal(v interface{}) ([]byte, error) - // Unmarshal parses the wire format into v. - Unmarshal(data []byte, v interface{}) error - // String returns the name of the Codec implementation. This is unused by - // gRPC. - String() string -} diff --git a/vendor/google.golang.org/grpc/codes/code_string.go b/vendor/google.golang.org/grpc/codes/code_string.go deleted file mode 100644 index 0b206a57822..00000000000 --- a/vendor/google.golang.org/grpc/codes/code_string.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 codes - -import "strconv" - -func (c Code) String() string { - switch c { - case OK: - return "OK" - case Canceled: - return "Canceled" - case Unknown: - return "Unknown" - case InvalidArgument: - return "InvalidArgument" - case DeadlineExceeded: - return "DeadlineExceeded" - case NotFound: - return "NotFound" - case AlreadyExists: - return "AlreadyExists" - case PermissionDenied: - return "PermissionDenied" - case ResourceExhausted: - return "ResourceExhausted" - case FailedPrecondition: - return "FailedPrecondition" - case Aborted: - return "Aborted" - case OutOfRange: - return "OutOfRange" - case Unimplemented: - return "Unimplemented" - case Internal: - return "Internal" - case Unavailable: - return "Unavailable" - case DataLoss: - return "DataLoss" - case Unauthenticated: - return "Unauthenticated" - default: - return "Code(" + strconv.FormatInt(int64(c), 10) + ")" - } -} diff --git a/vendor/google.golang.org/grpc/codes/codes.go b/vendor/google.golang.org/grpc/codes/codes.go deleted file mode 100644 index a8280ae660d..00000000000 --- a/vendor/google.golang.org/grpc/codes/codes.go +++ /dev/null @@ -1,184 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 codes defines the canonical error codes used by gRPC. It is -// consistent across various languages. -package codes // import "google.golang.org/grpc/codes" - -import ( - "fmt" -) - -// A Code is an unsigned 32-bit error code as defined in the gRPC spec. -type Code uint32 - -const ( - // OK is returned on success. - OK Code = 0 - - // Canceled indicates the operation was canceled (typically by the caller). - Canceled Code = 1 - - // Unknown error. An example of where this error may be returned is - // if a Status value received from another address space belongs to - // an error-space that is not known in this address space. Also - // errors raised by APIs that do not return enough error information - // may be converted to this error. - Unknown Code = 2 - - // InvalidArgument indicates client specified an invalid argument. - // Note that this differs from FailedPrecondition. It indicates arguments - // that are problematic regardless of the state of the system - // (e.g., a malformed file name). - InvalidArgument Code = 3 - - // DeadlineExceeded means operation expired before completion. - // For operations that change the state of the system, this error may be - // returned even if the operation has completed successfully. For - // example, a successful response from a server could have been delayed - // long enough for the deadline to expire. - DeadlineExceeded Code = 4 - - // NotFound means some requested entity (e.g., file or directory) was - // not found. - NotFound Code = 5 - - // AlreadyExists means an attempt to create an entity failed because one - // already exists. - AlreadyExists Code = 6 - - // PermissionDenied indicates the caller does not have permission to - // execute the specified operation. It must not be used for rejections - // caused by exhausting some resource (use ResourceExhausted - // instead for those errors). It must not be - // used if the caller cannot be identified (use Unauthenticated - // instead for those errors). - PermissionDenied Code = 7 - - // ResourceExhausted indicates some resource has been exhausted, perhaps - // a per-user quota, or perhaps the entire file system is out of space. - ResourceExhausted Code = 8 - - // FailedPrecondition indicates operation was rejected because the - // system is not in a state required for the operation's execution. - // For example, directory to be deleted may be non-empty, an rmdir - // operation is applied to a non-directory, etc. - // - // A litmus test that may help a service implementor in deciding - // between FailedPrecondition, Aborted, and Unavailable: - // (a) Use Unavailable if the client can retry just the failing call. - // (b) Use Aborted if the client should retry at a higher-level - // (e.g., restarting a read-modify-write sequence). - // (c) Use FailedPrecondition if the client should not retry until - // the system state has been explicitly fixed. E.g., if an "rmdir" - // fails because the directory is non-empty, FailedPrecondition - // should be returned since the client should not retry unless - // they have first fixed up the directory by deleting files from it. - // (d) Use FailedPrecondition if the client performs conditional - // REST Get/Update/Delete on a resource and the resource on the - // server does not match the condition. E.g., conflicting - // read-modify-write on the same resource. - FailedPrecondition Code = 9 - - // Aborted indicates the operation was aborted, typically due to a - // concurrency issue like sequencer check failures, transaction aborts, - // etc. - // - // See litmus test above for deciding between FailedPrecondition, - // Aborted, and Unavailable. - Aborted Code = 10 - - // OutOfRange means operation was attempted past the valid range. - // E.g., seeking or reading past end of file. - // - // Unlike InvalidArgument, this error indicates a problem that may - // be fixed if the system state changes. For example, a 32-bit file - // system will generate InvalidArgument if asked to read at an - // offset that is not in the range [0,2^32-1], but it will generate - // OutOfRange if asked to read from an offset past the current - // file size. - // - // There is a fair bit of overlap between FailedPrecondition and - // OutOfRange. We recommend using OutOfRange (the more specific - // error) when it applies so that callers who are iterating through - // a space can easily look for an OutOfRange error to detect when - // they are done. - OutOfRange Code = 11 - - // Unimplemented indicates operation is not implemented or not - // supported/enabled in this service. - Unimplemented Code = 12 - - // Internal errors. Means some invariants expected by underlying - // system has been broken. If you see one of these errors, - // something is very broken. - Internal Code = 13 - - // Unavailable indicates the service is currently unavailable. - // This is a most likely a transient condition and may be corrected - // by retrying with a backoff. - // - // See litmus test above for deciding between FailedPrecondition, - // Aborted, and Unavailable. - Unavailable Code = 14 - - // DataLoss indicates unrecoverable data loss or corruption. - DataLoss Code = 15 - - // Unauthenticated indicates the request does not have valid - // authentication credentials for the operation. - Unauthenticated Code = 16 -) - -var strToCode = map[string]Code{ - `"OK"`: OK, - `"CANCELLED"`:/* [sic] */ Canceled, - `"UNKNOWN"`: Unknown, - `"INVALID_ARGUMENT"`: InvalidArgument, - `"DEADLINE_EXCEEDED"`: DeadlineExceeded, - `"NOT_FOUND"`: NotFound, - `"ALREADY_EXISTS"`: AlreadyExists, - `"PERMISSION_DENIED"`: PermissionDenied, - `"RESOURCE_EXHAUSTED"`: ResourceExhausted, - `"FAILED_PRECONDITION"`: FailedPrecondition, - `"ABORTED"`: Aborted, - `"OUT_OF_RANGE"`: OutOfRange, - `"UNIMPLEMENTED"`: Unimplemented, - `"INTERNAL"`: Internal, - `"UNAVAILABLE"`: Unavailable, - `"DATA_LOSS"`: DataLoss, - `"UNAUTHENTICATED"`: Unauthenticated, -} - -// UnmarshalJSON unmarshals b into the Code. -func (c *Code) UnmarshalJSON(b []byte) error { - // From json.Unmarshaler: By convention, to approximate the behavior of - // Unmarshal itself, Unmarshalers implement UnmarshalJSON([]byte("null")) as - // a no-op. - if string(b) == "null" { - return nil - } - if c == nil { - return fmt.Errorf("nil receiver passed to UnmarshalJSON") - } - if jc, ok := strToCode[string(b)]; ok { - *c = jc - return nil - } - return fmt.Errorf("invalid code: %q", string(b)) -} diff --git a/vendor/google.golang.org/grpc/connectivity/connectivity.go b/vendor/google.golang.org/grpc/connectivity/connectivity.go deleted file mode 100644 index 568ef5dc68b..00000000000 --- a/vendor/google.golang.org/grpc/connectivity/connectivity.go +++ /dev/null @@ -1,72 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 connectivity defines connectivity semantics. -// For details, see https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md. -// All APIs in this package are experimental. -package connectivity - -import ( - "golang.org/x/net/context" - "google.golang.org/grpc/grpclog" -) - -// State indicates the state of connectivity. -// It can be the state of a ClientConn or SubConn. -type State int - -func (s State) String() string { - switch s { - case Idle: - return "IDLE" - case Connecting: - return "CONNECTING" - case Ready: - return "READY" - case TransientFailure: - return "TRANSIENT_FAILURE" - case Shutdown: - return "SHUTDOWN" - default: - grpclog.Errorf("unknown connectivity state: %d", s) - return "Invalid-State" - } -} - -const ( - // Idle indicates the ClientConn is idle. - Idle State = iota - // Connecting indicates the ClienConn is connecting. - Connecting - // Ready indicates the ClientConn is ready for work. - Ready - // TransientFailure indicates the ClientConn has seen a failure but expects to recover. - TransientFailure - // Shutdown indicates the ClientConn has started shutting down. - Shutdown -) - -// Reporter reports the connectivity states. -type Reporter interface { - // CurrentState returns the current state of the reporter. - CurrentState() State - // WaitForStateChange blocks until the reporter's state is different from the given state, - // and returns true. - // It returns false if <-ctx.Done() can proceed (ctx got timeout or got canceled). - WaitForStateChange(context.Context, State) bool -} diff --git a/vendor/google.golang.org/grpc/credentials/credentials.go b/vendor/google.golang.org/grpc/credentials/credentials.go deleted file mode 100644 index 3351bf0ee5f..00000000000 --- a/vendor/google.golang.org/grpc/credentials/credentials.go +++ /dev/null @@ -1,220 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 credentials implements various credentials supported by gRPC library, -// which encapsulate all the state needed by a client to authenticate with a -// server and make various assertions, e.g., about the client's identity, role, -// or whether it is authorized to make a particular call. -package credentials // import "google.golang.org/grpc/credentials" - -import ( - "crypto/tls" - "crypto/x509" - "errors" - "fmt" - "io/ioutil" - "net" - "strings" - - "golang.org/x/net/context" -) - -// alpnProtoStr are the specified application level protocols for gRPC. -var alpnProtoStr = []string{"h2"} - -// PerRPCCredentials defines the common interface for the credentials which need to -// attach security information to every RPC (e.g., oauth2). -type PerRPCCredentials interface { - // GetRequestMetadata gets the current request metadata, refreshing - // tokens if required. This should be called by the transport layer on - // each request, and the data should be populated in headers or other - // context. If a status code is returned, it will be used as the status - // for the RPC. uri is the URI of the entry point for the request. - // When supported by the underlying implementation, ctx can be used for - // timeout and cancellation. - // TODO(zhaoq): Define the set of the qualified keys instead of leaving - // it as an arbitrary string. - GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) - // RequireTransportSecurity indicates whether the credentials requires - // transport security. - RequireTransportSecurity() bool -} - -// ProtocolInfo provides information regarding the gRPC wire protocol version, -// security protocol, security protocol version in use, server name, etc. -type ProtocolInfo struct { - // ProtocolVersion is the gRPC wire protocol version. - ProtocolVersion string - // SecurityProtocol is the security protocol in use. - SecurityProtocol string - // SecurityVersion is the security protocol version. - SecurityVersion string - // ServerName is the user-configured server name. - ServerName string -} - -// AuthInfo defines the common interface for the auth information the users are interested in. -type AuthInfo interface { - AuthType() string -} - -// ErrConnDispatched indicates that rawConn has been dispatched out of gRPC -// and the caller should not close rawConn. -var ErrConnDispatched = errors.New("credentials: rawConn is dispatched out of gRPC") - -// TransportCredentials defines the common interface for all the live gRPC wire -// protocols and supported transport security protocols (e.g., TLS, SSL). -type TransportCredentials interface { - // ClientHandshake does the authentication handshake specified by the corresponding - // authentication protocol on rawConn for clients. It returns the authenticated - // connection and the corresponding auth information about the connection. - // Implementations must use the provided context to implement timely cancellation. - // gRPC will try to reconnect if the error returned is a temporary error - // (io.EOF, context.DeadlineExceeded or err.Temporary() == true). - // If the returned error is a wrapper error, implementations should make sure that - // the error implements Temporary() to have the correct retry behaviors. - // - // If the returned net.Conn is closed, it MUST close the net.Conn provided. - ClientHandshake(context.Context, string, net.Conn) (net.Conn, AuthInfo, error) - // ServerHandshake does the authentication handshake for servers. It returns - // the authenticated connection and the corresponding auth information about - // the connection. - // - // If the returned net.Conn is closed, it MUST close the net.Conn provided. - ServerHandshake(net.Conn) (net.Conn, AuthInfo, error) - // Info provides the ProtocolInfo of this TransportCredentials. - Info() ProtocolInfo - // Clone makes a copy of this TransportCredentials. - Clone() TransportCredentials - // OverrideServerName overrides the server name used to verify the hostname on the returned certificates from the server. - // gRPC internals also use it to override the virtual hosting name if it is set. - // It must be called before dialing. Currently, this is only used by grpclb. - OverrideServerName(string) error -} - -// TLSInfo contains the auth information for a TLS authenticated connection. -// It implements the AuthInfo interface. -type TLSInfo struct { - State tls.ConnectionState -} - -// AuthType returns the type of TLSInfo as a string. -func (t TLSInfo) AuthType() string { - return "tls" -} - -// tlsCreds is the credentials required for authenticating a connection using TLS. -type tlsCreds struct { - // TLS configuration - config *tls.Config -} - -func (c tlsCreds) Info() ProtocolInfo { - return ProtocolInfo{ - SecurityProtocol: "tls", - SecurityVersion: "1.2", - ServerName: c.config.ServerName, - } -} - -func (c *tlsCreds) ClientHandshake(ctx context.Context, authority string, rawConn net.Conn) (_ net.Conn, _ AuthInfo, err error) { - // use local cfg to avoid clobbering ServerName if using multiple endpoints - cfg := cloneTLSConfig(c.config) - if cfg.ServerName == "" { - colonPos := strings.LastIndex(authority, ":") - if colonPos == -1 { - colonPos = len(authority) - } - cfg.ServerName = authority[:colonPos] - } - conn := tls.Client(rawConn, cfg) - errChannel := make(chan error, 1) - go func() { - errChannel <- conn.Handshake() - }() - select { - case err := <-errChannel: - if err != nil { - return nil, nil, err - } - case <-ctx.Done(): - return nil, nil, ctx.Err() - } - return conn, TLSInfo{conn.ConnectionState()}, nil -} - -func (c *tlsCreds) ServerHandshake(rawConn net.Conn) (net.Conn, AuthInfo, error) { - conn := tls.Server(rawConn, c.config) - if err := conn.Handshake(); err != nil { - return nil, nil, err - } - return conn, TLSInfo{conn.ConnectionState()}, nil -} - -func (c *tlsCreds) Clone() TransportCredentials { - return NewTLS(c.config) -} - -func (c *tlsCreds) OverrideServerName(serverNameOverride string) error { - c.config.ServerName = serverNameOverride - return nil -} - -// NewTLS uses c to construct a TransportCredentials based on TLS. -func NewTLS(c *tls.Config) TransportCredentials { - tc := &tlsCreds{cloneTLSConfig(c)} - tc.config.NextProtos = alpnProtoStr - return tc -} - -// NewClientTLSFromCert constructs TLS credentials from the input certificate for client. -// serverNameOverride is for testing only. If set to a non empty string, -// it will override the virtual host name of authority (e.g. :authority header field) in requests. -func NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) TransportCredentials { - return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}) -} - -// NewClientTLSFromFile constructs TLS credentials from the input certificate file for client. -// serverNameOverride is for testing only. If set to a non empty string, -// it will override the virtual host name of authority (e.g. :authority header field) in requests. -func NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredentials, error) { - b, err := ioutil.ReadFile(certFile) - if err != nil { - return nil, err - } - cp := x509.NewCertPool() - if !cp.AppendCertsFromPEM(b) { - return nil, fmt.Errorf("credentials: failed to append certificates") - } - return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}), nil -} - -// NewServerTLSFromCert constructs TLS credentials from the input certificate for server. -func NewServerTLSFromCert(cert *tls.Certificate) TransportCredentials { - return NewTLS(&tls.Config{Certificates: []tls.Certificate{*cert}}) -} - -// NewServerTLSFromFile constructs TLS credentials from the input certificate file and key -// file for server. -func NewServerTLSFromFile(certFile, keyFile string) (TransportCredentials, error) { - cert, err := tls.LoadX509KeyPair(certFile, keyFile) - if err != nil { - return nil, err - } - return NewTLS(&tls.Config{Certificates: []tls.Certificate{cert}}), nil -} diff --git a/vendor/google.golang.org/grpc/credentials/credentials_util_go17.go b/vendor/google.golang.org/grpc/credentials/credentials_util_go17.go deleted file mode 100644 index 60409aac0fb..00000000000 --- a/vendor/google.golang.org/grpc/credentials/credentials_util_go17.go +++ /dev/null @@ -1,60 +0,0 @@ -// +build go1.7 -// +build !go1.8 - -/* - * - * Copyright 2016 gRPC 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 credentials - -import ( - "crypto/tls" -) - -// cloneTLSConfig returns a shallow clone of the exported -// fields of cfg, ignoring the unexported sync.Once, which -// contains a mutex and must not be copied. -// -// If cfg is nil, a new zero tls.Config is returned. -func cloneTLSConfig(cfg *tls.Config) *tls.Config { - if cfg == nil { - return &tls.Config{} - } - return &tls.Config{ - Rand: cfg.Rand, - Time: cfg.Time, - Certificates: cfg.Certificates, - NameToCertificate: cfg.NameToCertificate, - GetCertificate: cfg.GetCertificate, - RootCAs: cfg.RootCAs, - NextProtos: cfg.NextProtos, - ServerName: cfg.ServerName, - ClientAuth: cfg.ClientAuth, - ClientCAs: cfg.ClientCAs, - InsecureSkipVerify: cfg.InsecureSkipVerify, - CipherSuites: cfg.CipherSuites, - PreferServerCipherSuites: cfg.PreferServerCipherSuites, - SessionTicketsDisabled: cfg.SessionTicketsDisabled, - SessionTicketKey: cfg.SessionTicketKey, - ClientSessionCache: cfg.ClientSessionCache, - MinVersion: cfg.MinVersion, - MaxVersion: cfg.MaxVersion, - CurvePreferences: cfg.CurvePreferences, - DynamicRecordSizingDisabled: cfg.DynamicRecordSizingDisabled, - Renegotiation: cfg.Renegotiation, - } -} diff --git a/vendor/google.golang.org/grpc/credentials/credentials_util_go18.go b/vendor/google.golang.org/grpc/credentials/credentials_util_go18.go deleted file mode 100644 index 93f0e1d8de2..00000000000 --- a/vendor/google.golang.org/grpc/credentials/credentials_util_go18.go +++ /dev/null @@ -1,38 +0,0 @@ -// +build go1.8 - -/* - * - * Copyright 2017 gRPC 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 credentials - -import ( - "crypto/tls" -) - -// cloneTLSConfig returns a shallow clone of the exported -// fields of cfg, ignoring the unexported sync.Once, which -// contains a mutex and must not be copied. -// -// If cfg is nil, a new zero tls.Config is returned. -func cloneTLSConfig(cfg *tls.Config) *tls.Config { - if cfg == nil { - return &tls.Config{} - } - - return cfg.Clone() -} diff --git a/vendor/google.golang.org/grpc/credentials/credentials_util_pre_go17.go b/vendor/google.golang.org/grpc/credentials/credentials_util_pre_go17.go deleted file mode 100644 index d6bbcc9fdd9..00000000000 --- a/vendor/google.golang.org/grpc/credentials/credentials_util_pre_go17.go +++ /dev/null @@ -1,57 +0,0 @@ -// +build !go1.7 - -/* - * - * Copyright 2016 gRPC 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 credentials - -import ( - "crypto/tls" -) - -// cloneTLSConfig returns a shallow clone of the exported -// fields of cfg, ignoring the unexported sync.Once, which -// contains a mutex and must not be copied. -// -// If cfg is nil, a new zero tls.Config is returned. -func cloneTLSConfig(cfg *tls.Config) *tls.Config { - if cfg == nil { - return &tls.Config{} - } - return &tls.Config{ - Rand: cfg.Rand, - Time: cfg.Time, - Certificates: cfg.Certificates, - NameToCertificate: cfg.NameToCertificate, - GetCertificate: cfg.GetCertificate, - RootCAs: cfg.RootCAs, - NextProtos: cfg.NextProtos, - ServerName: cfg.ServerName, - ClientAuth: cfg.ClientAuth, - ClientCAs: cfg.ClientCAs, - InsecureSkipVerify: cfg.InsecureSkipVerify, - CipherSuites: cfg.CipherSuites, - PreferServerCipherSuites: cfg.PreferServerCipherSuites, - SessionTicketsDisabled: cfg.SessionTicketsDisabled, - SessionTicketKey: cfg.SessionTicketKey, - ClientSessionCache: cfg.ClientSessionCache, - MinVersion: cfg.MinVersion, - MaxVersion: cfg.MaxVersion, - CurvePreferences: cfg.CurvePreferences, - } -} diff --git a/vendor/google.golang.org/grpc/credentials/oauth/oauth.go b/vendor/google.golang.org/grpc/credentials/oauth/oauth.go deleted file mode 100644 index f6d597a14fe..00000000000 --- a/vendor/google.golang.org/grpc/credentials/oauth/oauth.go +++ /dev/null @@ -1,173 +0,0 @@ -/* - * - * Copyright 2015 gRPC 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 oauth implements gRPC credentials using OAuth. -package oauth - -import ( - "fmt" - "io/ioutil" - "sync" - - "golang.org/x/net/context" - "golang.org/x/oauth2" - "golang.org/x/oauth2/google" - "golang.org/x/oauth2/jwt" - "google.golang.org/grpc/credentials" -) - -// TokenSource supplies PerRPCCredentials from an oauth2.TokenSource. -type TokenSource struct { - oauth2.TokenSource -} - -// GetRequestMetadata gets the request metadata as a map from a TokenSource. -func (ts TokenSource) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { - token, err := ts.Token() - if err != nil { - return nil, err - } - return map[string]string{ - "authorization": token.Type() + " " + token.AccessToken, - }, nil -} - -// RequireTransportSecurity indicates whether the credentials requires transport security. -func (ts TokenSource) RequireTransportSecurity() bool { - return true -} - -type jwtAccess struct { - jsonKey []byte -} - -// NewJWTAccessFromFile creates PerRPCCredentials from the given keyFile. -func NewJWTAccessFromFile(keyFile string) (credentials.PerRPCCredentials, error) { - jsonKey, err := ioutil.ReadFile(keyFile) - if err != nil { - return nil, fmt.Errorf("credentials: failed to read the service account key file: %v", err) - } - return NewJWTAccessFromKey(jsonKey) -} - -// NewJWTAccessFromKey creates PerRPCCredentials from the given jsonKey. -func NewJWTAccessFromKey(jsonKey []byte) (credentials.PerRPCCredentials, error) { - return jwtAccess{jsonKey}, nil -} - -func (j jwtAccess) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { - ts, err := google.JWTAccessTokenSourceFromJSON(j.jsonKey, uri[0]) - if err != nil { - return nil, err - } - token, err := ts.Token() - if err != nil { - return nil, err - } - return map[string]string{ - "authorization": token.Type() + " " + token.AccessToken, - }, nil -} - -func (j jwtAccess) RequireTransportSecurity() bool { - return true -} - -// oauthAccess supplies PerRPCCredentials from a given token. -type oauthAccess struct { - token oauth2.Token -} - -// NewOauthAccess constructs the PerRPCCredentials using a given token. -func NewOauthAccess(token *oauth2.Token) credentials.PerRPCCredentials { - return oauthAccess{token: *token} -} - -func (oa oauthAccess) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { - return map[string]string{ - "authorization": oa.token.Type() + " " + oa.token.AccessToken, - }, nil -} - -func (oa oauthAccess) RequireTransportSecurity() bool { - return true -} - -// NewComputeEngine constructs the PerRPCCredentials that fetches access tokens from -// Google Compute Engine (GCE)'s metadata server. It is only valid to use this -// if your program is running on a GCE instance. -// TODO(dsymonds): Deprecate and remove this. -func NewComputeEngine() credentials.PerRPCCredentials { - return TokenSource{google.ComputeTokenSource("")} -} - -// serviceAccount represents PerRPCCredentials via JWT signing key. -type serviceAccount struct { - mu sync.Mutex - config *jwt.Config - t *oauth2.Token -} - -func (s *serviceAccount) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { - s.mu.Lock() - defer s.mu.Unlock() - if !s.t.Valid() { - var err error - s.t, err = s.config.TokenSource(ctx).Token() - if err != nil { - return nil, err - } - } - return map[string]string{ - "authorization": s.t.Type() + " " + s.t.AccessToken, - }, nil -} - -func (s *serviceAccount) RequireTransportSecurity() bool { - return true -} - -// NewServiceAccountFromKey constructs the PerRPCCredentials using the JSON key slice -// from a Google Developers service account. -func NewServiceAccountFromKey(jsonKey []byte, scope ...string) (credentials.PerRPCCredentials, error) { - config, err := google.JWTConfigFromJSON(jsonKey, scope...) - if err != nil { - return nil, err - } - return &serviceAccount{config: config}, nil -} - -// NewServiceAccountFromFile constructs the PerRPCCredentials using the JSON key file -// of a Google Developers service account. -func NewServiceAccountFromFile(keyFile string, scope ...string) (credentials.PerRPCCredentials, error) { - jsonKey, err := ioutil.ReadFile(keyFile) - if err != nil { - return nil, fmt.Errorf("credentials: failed to read the service account key file: %v", err) - } - return NewServiceAccountFromKey(jsonKey, scope...) -} - -// NewApplicationDefault returns "Application Default Credentials". For more -// detail, see https://developers.google.com/accounts/docs/application-default-credentials. -func NewApplicationDefault(ctx context.Context, scope ...string) (credentials.PerRPCCredentials, error) { - t, err := google.DefaultTokenSource(ctx, scope...) - if err != nil { - return nil, err - } - return TokenSource{t}, nil -} diff --git a/vendor/google.golang.org/grpc/doc.go b/vendor/google.golang.org/grpc/doc.go deleted file mode 100644 index 187adbb117f..00000000000 --- a/vendor/google.golang.org/grpc/doc.go +++ /dev/null @@ -1,24 +0,0 @@ -/* - * - * Copyright 2015 gRPC 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 grpc implements an RPC system called gRPC. - -See grpc.io for more information about gRPC. -*/ -package grpc // import "google.golang.org/grpc" diff --git a/vendor/google.golang.org/grpc/encoding/encoding.go b/vendor/google.golang.org/grpc/encoding/encoding.go deleted file mode 100644 index ade8b7cec73..00000000000 --- a/vendor/google.golang.org/grpc/encoding/encoding.go +++ /dev/null @@ -1,118 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 encoding defines the interface for the compressor and codec, and -// functions to register and retrieve compressors and codecs. -// -// This package is EXPERIMENTAL. -package encoding - -import ( - "io" - "strings" -) - -// Identity specifies the optional encoding for uncompressed streams. -// It is intended for grpc internal use only. -const Identity = "identity" - -// Compressor is used for compressing and decompressing when sending or -// receiving messages. -type Compressor interface { - // Compress writes the data written to wc to w after compressing it. If an - // error occurs while initializing the compressor, that error is returned - // instead. - Compress(w io.Writer) (io.WriteCloser, error) - // Decompress reads data from r, decompresses it, and provides the - // uncompressed data via the returned io.Reader. If an error occurs while - // initializing the decompressor, that error is returned instead. - Decompress(r io.Reader) (io.Reader, error) - // Name is the name of the compression codec and is used to set the content - // coding header. The result must be static; the result cannot change - // between calls. - Name() string -} - -var registeredCompressor = make(map[string]Compressor) - -// RegisterCompressor registers the compressor with gRPC by its name. It can -// be activated when sending an RPC via grpc.UseCompressor(). It will be -// automatically accessed when receiving a message based on the content coding -// header. Servers also use it to send a response with the same encoding as -// the request. -// -// NOTE: this function must only be called during initialization time (i.e. in -// an init() function), and is not thread-safe. If multiple Compressors are -// registered with the same name, the one registered last will take effect. -func RegisterCompressor(c Compressor) { - registeredCompressor[c.Name()] = c -} - -// GetCompressor returns Compressor for the given compressor name. -func GetCompressor(name string) Compressor { - return registeredCompressor[name] -} - -// Codec defines the interface gRPC uses to encode and decode messages. Note -// that implementations of this interface must be thread safe; a Codec's -// methods can be called from concurrent goroutines. -type Codec interface { - // Marshal returns the wire format of v. - Marshal(v interface{}) ([]byte, error) - // Unmarshal parses the wire format into v. - Unmarshal(data []byte, v interface{}) error - // Name returns the name of the Codec implementation. The returned string - // will be used as part of content type in transmission. The result must be - // static; the result cannot change between calls. - Name() string -} - -var registeredCodecs = make(map[string]Codec) - -// RegisterCodec registers the provided Codec for use with all gRPC clients and -// servers. -// -// The Codec will be stored and looked up by result of its Name() method, which -// should match the content-subtype of the encoding handled by the Codec. This -// is case-insensitive, and is stored and looked up as lowercase. If the -// result of calling Name() is an empty string, RegisterCodec will panic. See -// Content-Type on -// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for -// more details. -// -// NOTE: this function must only be called during initialization time (i.e. in -// an init() function), and is not thread-safe. If multiple Compressors are -// registered with the same name, the one registered last will take effect. -func RegisterCodec(codec Codec) { - if codec == nil { - panic("cannot register a nil Codec") - } - contentSubtype := strings.ToLower(codec.Name()) - if contentSubtype == "" { - panic("cannot register Codec with empty string result for String()") - } - registeredCodecs[contentSubtype] = codec -} - -// GetCodec gets a registered Codec by content-subtype, or nil if no Codec is -// registered for the content-subtype. -// -// The content-subtype is expected to be lowercase. -func GetCodec(contentSubtype string) Codec { - return registeredCodecs[contentSubtype] -} diff --git a/vendor/google.golang.org/grpc/encoding/proto/proto.go b/vendor/google.golang.org/grpc/encoding/proto/proto.go deleted file mode 100644 index 66b97a6f692..00000000000 --- a/vendor/google.golang.org/grpc/encoding/proto/proto.go +++ /dev/null @@ -1,110 +0,0 @@ -/* - * - * Copyright 2018 gRPC 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 proto defines the protobuf codec. Importing this package will -// register the codec. -package proto - -import ( - "math" - "sync" - - "github.com/golang/protobuf/proto" - "google.golang.org/grpc/encoding" -) - -// Name is the name registered for the proto compressor. -const Name = "proto" - -func init() { - encoding.RegisterCodec(codec{}) -} - -// codec is a Codec implementation with protobuf. It is the default codec for gRPC. -type codec struct{} - -type cachedProtoBuffer struct { - lastMarshaledSize uint32 - proto.Buffer -} - -func capToMaxInt32(val int) uint32 { - if val > math.MaxInt32 { - return uint32(math.MaxInt32) - } - return uint32(val) -} - -func marshal(v interface{}, cb *cachedProtoBuffer) ([]byte, error) { - protoMsg := v.(proto.Message) - newSlice := make([]byte, 0, cb.lastMarshaledSize) - - cb.SetBuf(newSlice) - cb.Reset() - if err := cb.Marshal(protoMsg); err != nil { - return nil, err - } - out := cb.Bytes() - cb.lastMarshaledSize = capToMaxInt32(len(out)) - return out, nil -} - -func (codec) Marshal(v interface{}) ([]byte, error) { - if pm, ok := v.(proto.Marshaler); ok { - // object can marshal itself, no need for buffer - return pm.Marshal() - } - - cb := protoBufferPool.Get().(*cachedProtoBuffer) - out, err := marshal(v, cb) - - // put back buffer and lose the ref to the slice - cb.SetBuf(nil) - protoBufferPool.Put(cb) - return out, err -} - -func (codec) Unmarshal(data []byte, v interface{}) error { - protoMsg := v.(proto.Message) - protoMsg.Reset() - - if pu, ok := protoMsg.(proto.Unmarshaler); ok { - // object can unmarshal itself, no need for buffer - return pu.Unmarshal(data) - } - - cb := protoBufferPool.Get().(*cachedProtoBuffer) - cb.SetBuf(data) - err := cb.Unmarshal(protoMsg) - cb.SetBuf(nil) - protoBufferPool.Put(cb) - return err -} - -func (codec) Name() string { - return Name -} - -var protoBufferPool = &sync.Pool{ - New: func() interface{} { - return &cachedProtoBuffer{ - Buffer: proto.Buffer{}, - lastMarshaledSize: 16, - } - }, -} diff --git a/vendor/google.golang.org/grpc/envconfig.go b/vendor/google.golang.org/grpc/envconfig.go deleted file mode 100644 index d50178e5171..00000000000 --- a/vendor/google.golang.org/grpc/envconfig.go +++ /dev/null @@ -1,37 +0,0 @@ -/* - * - * Copyright 2018 gRPC 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 grpc - -import ( - "os" - "strings" -) - -const ( - envConfigPrefix = "GRPC_GO_" - envConfigStickinessStr = envConfigPrefix + "STICKINESS" -) - -var ( - envConfigStickinessOn bool -) - -func init() { - envConfigStickinessOn = strings.EqualFold(os.Getenv(envConfigStickinessStr), "on") -} diff --git a/vendor/google.golang.org/grpc/go16.go b/vendor/google.golang.org/grpc/go16.go deleted file mode 100644 index 535ee9356f3..00000000000 --- a/vendor/google.golang.org/grpc/go16.go +++ /dev/null @@ -1,70 +0,0 @@ -// +build go1.6,!go1.7 - -/* - * - * Copyright 2016 gRPC 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 grpc - -import ( - "fmt" - "io" - "net" - "net/http" - - "golang.org/x/net/context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - "google.golang.org/grpc/transport" -) - -// dialContext connects to the address on the named network. -func dialContext(ctx context.Context, network, address string) (net.Conn, error) { - return (&net.Dialer{Cancel: ctx.Done()}).Dial(network, address) -} - -func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) error { - req.Cancel = ctx.Done() - if err := req.Write(conn); err != nil { - return fmt.Errorf("failed to write the HTTP request: %v", err) - } - return nil -} - -// toRPCErr converts an error into an error from the status package. -func toRPCErr(err error) error { - if err == nil || err == io.EOF { - return err - } - if _, ok := status.FromError(err); ok { - return err - } - switch e := err.(type) { - case transport.StreamError: - return status.Error(e.Code, e.Desc) - case transport.ConnectionError: - return status.Error(codes.Unavailable, e.Desc) - default: - switch err { - case context.DeadlineExceeded: - return status.Error(codes.DeadlineExceeded, err.Error()) - case context.Canceled: - return status.Error(codes.Canceled, err.Error()) - } - } - return status.Error(codes.Unknown, err.Error()) -} diff --git a/vendor/google.golang.org/grpc/go17.go b/vendor/google.golang.org/grpc/go17.go deleted file mode 100644 index ec676a93c39..00000000000 --- a/vendor/google.golang.org/grpc/go17.go +++ /dev/null @@ -1,71 +0,0 @@ -// +build go1.7 - -/* - * - * Copyright 2016 gRPC 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 grpc - -import ( - "context" - "fmt" - "io" - "net" - "net/http" - - netctx "golang.org/x/net/context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - "google.golang.org/grpc/transport" -) - -// dialContext connects to the address on the named network. -func dialContext(ctx context.Context, network, address string) (net.Conn, error) { - return (&net.Dialer{}).DialContext(ctx, network, address) -} - -func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) error { - req = req.WithContext(ctx) - if err := req.Write(conn); err != nil { - return fmt.Errorf("failed to write the HTTP request: %v", err) - } - return nil -} - -// toRPCErr converts an error into an error from the status package. -func toRPCErr(err error) error { - if err == nil || err == io.EOF { - return err - } - if _, ok := status.FromError(err); ok { - return err - } - switch e := err.(type) { - case transport.StreamError: - return status.Error(e.Code, e.Desc) - case transport.ConnectionError: - return status.Error(codes.Unavailable, e.Desc) - default: - switch err { - case context.DeadlineExceeded, netctx.DeadlineExceeded: - return status.Error(codes.DeadlineExceeded, err.Error()) - case context.Canceled, netctx.Canceled: - return status.Error(codes.Canceled, err.Error()) - } - } - return status.Error(codes.Unknown, err.Error()) -} diff --git a/vendor/google.golang.org/grpc/grpclb.go b/vendor/google.golang.org/grpc/grpclb.go deleted file mode 100644 index bc2b4452558..00000000000 --- a/vendor/google.golang.org/grpc/grpclb.go +++ /dev/null @@ -1,341 +0,0 @@ -/* - * - * Copyright 2016 gRPC 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 grpc - -import ( - "strconv" - "strings" - "sync" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/connectivity" - lbpb "google.golang.org/grpc/grpclb/grpc_lb_v1/messages" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/resolver" -) - -const ( - lbTokeyKey = "lb-token" - defaultFallbackTimeout = 10 * time.Second - grpclbName = "grpclb" -) - -func convertDuration(d *lbpb.Duration) time.Duration { - if d == nil { - return 0 - } - return time.Duration(d.Seconds)*time.Second + time.Duration(d.Nanos)*time.Nanosecond -} - -// Client API for LoadBalancer service. -// Mostly copied from generated pb.go file. -// To avoid circular dependency. -type loadBalancerClient struct { - cc *ClientConn -} - -func (c *loadBalancerClient) BalanceLoad(ctx context.Context, opts ...CallOption) (*balanceLoadClientStream, error) { - desc := &StreamDesc{ - StreamName: "BalanceLoad", - ServerStreams: true, - ClientStreams: true, - } - stream, err := c.cc.NewStream(ctx, desc, "/grpc.lb.v1.LoadBalancer/BalanceLoad", opts...) - if err != nil { - return nil, err - } - x := &balanceLoadClientStream{stream} - return x, nil -} - -type balanceLoadClientStream struct { - ClientStream -} - -func (x *balanceLoadClientStream) Send(m *lbpb.LoadBalanceRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *balanceLoadClientStream) Recv() (*lbpb.LoadBalanceResponse, error) { - m := new(lbpb.LoadBalanceResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func init() { - balancer.Register(newLBBuilder()) -} - -// newLBBuilder creates a builder for grpclb. -func newLBBuilder() balancer.Builder { - return NewLBBuilderWithFallbackTimeout(defaultFallbackTimeout) -} - -// NewLBBuilderWithFallbackTimeout creates a grpclb builder with the given -// fallbackTimeout. If no response is received from the remote balancer within -// fallbackTimeout, the backend addresses from the resolved address list will be -// used. -// -// Only call this function when a non-default fallback timeout is needed. -func NewLBBuilderWithFallbackTimeout(fallbackTimeout time.Duration) balancer.Builder { - return &lbBuilder{ - fallbackTimeout: fallbackTimeout, - } -} - -type lbBuilder struct { - fallbackTimeout time.Duration -} - -func (b *lbBuilder) Name() string { - return grpclbName -} - -func (b *lbBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions) balancer.Balancer { - // This generates a manual resolver builder with a random scheme. This - // scheme will be used to dial to remote LB, so we can send filtered address - // updates to remote LB ClientConn using this manual resolver. - scheme := "grpclb_internal_" + strconv.FormatInt(time.Now().UnixNano(), 36) - r := &lbManualResolver{scheme: scheme, ccb: cc} - - var target string - targetSplitted := strings.Split(cc.Target(), ":///") - if len(targetSplitted) < 2 { - target = cc.Target() - } else { - target = targetSplitted[1] - } - - lb := &lbBalancer{ - cc: newLBCacheClientConn(cc), - target: target, - opt: opt, - fallbackTimeout: b.fallbackTimeout, - doneCh: make(chan struct{}), - - manualResolver: r, - csEvltr: &connectivityStateEvaluator{}, - subConns: make(map[resolver.Address]balancer.SubConn), - scStates: make(map[balancer.SubConn]connectivity.State), - picker: &errPicker{err: balancer.ErrNoSubConnAvailable}, - clientStats: &rpcStats{}, - } - - return lb -} - -type lbBalancer struct { - cc *lbCacheClientConn - target string - opt balancer.BuildOptions - fallbackTimeout time.Duration - doneCh chan struct{} - - // manualResolver is used in the remote LB ClientConn inside grpclb. When - // resolved address updates are received by grpclb, filtered updates will be - // send to remote LB ClientConn through this resolver. - manualResolver *lbManualResolver - // The ClientConn to talk to the remote balancer. - ccRemoteLB *ClientConn - - // Support client side load reporting. Each picker gets a reference to this, - // and will update its content. - clientStats *rpcStats - - mu sync.Mutex // guards everything following. - // The full server list including drops, used to check if the newly received - // serverList contains anything new. Each generate picker will also have - // reference to this list to do the first layer pick. - fullServerList []*lbpb.Server - // All backends addresses, with metadata set to nil. This list contains all - // backend addresses in the same order and with the same duplicates as in - // serverlist. When generating picker, a SubConn slice with the same order - // but with only READY SCs will be gerenated. - backendAddrs []resolver.Address - // Roundrobin functionalities. - csEvltr *connectivityStateEvaluator - state connectivity.State - subConns map[resolver.Address]balancer.SubConn // Used to new/remove SubConn. - scStates map[balancer.SubConn]connectivity.State // Used to filter READY SubConns. - picker balancer.Picker - // Support fallback to resolved backend addresses if there's no response - // from remote balancer within fallbackTimeout. - fallbackTimerExpired bool - serverListReceived bool - // resolvedBackendAddrs is resolvedAddrs minus remote balancers. It's set - // when resolved address updates are received, and read in the goroutine - // handling fallback. - resolvedBackendAddrs []resolver.Address -} - -// regeneratePicker takes a snapshot of the balancer, and generates a picker from -// it. The picker -// - always returns ErrTransientFailure if the balancer is in TransientFailure, -// - does two layer roundrobin pick otherwise. -// Caller must hold lb.mu. -func (lb *lbBalancer) regeneratePicker() { - if lb.state == connectivity.TransientFailure { - lb.picker = &errPicker{err: balancer.ErrTransientFailure} - return - } - var readySCs []balancer.SubConn - for _, a := range lb.backendAddrs { - if sc, ok := lb.subConns[a]; ok { - if st, ok := lb.scStates[sc]; ok && st == connectivity.Ready { - readySCs = append(readySCs, sc) - } - } - } - - if len(lb.fullServerList) <= 0 { - if len(readySCs) <= 0 { - lb.picker = &errPicker{err: balancer.ErrNoSubConnAvailable} - return - } - lb.picker = &rrPicker{subConns: readySCs} - return - } - lb.picker = &lbPicker{ - serverList: lb.fullServerList, - subConns: readySCs, - stats: lb.clientStats, - } -} - -func (lb *lbBalancer) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { - grpclog.Infof("lbBalancer: handle SubConn state change: %p, %v", sc, s) - lb.mu.Lock() - defer lb.mu.Unlock() - - oldS, ok := lb.scStates[sc] - if !ok { - grpclog.Infof("lbBalancer: got state changes for an unknown SubConn: %p, %v", sc, s) - return - } - lb.scStates[sc] = s - switch s { - case connectivity.Idle: - sc.Connect() - case connectivity.Shutdown: - // When an address was removed by resolver, b called RemoveSubConn but - // kept the sc's state in scStates. Remove state for this sc here. - delete(lb.scStates, sc) - } - - oldAggrState := lb.state - lb.state = lb.csEvltr.recordTransition(oldS, s) - - // Regenerate picker when one of the following happens: - // - this sc became ready from not-ready - // - this sc became not-ready from ready - // - the aggregated state of balancer became TransientFailure from non-TransientFailure - // - the aggregated state of balancer became non-TransientFailure from TransientFailure - if (oldS == connectivity.Ready) != (s == connectivity.Ready) || - (lb.state == connectivity.TransientFailure) != (oldAggrState == connectivity.TransientFailure) { - lb.regeneratePicker() - } - - lb.cc.UpdateBalancerState(lb.state, lb.picker) -} - -// fallbackToBackendsAfter blocks for fallbackTimeout and falls back to use -// resolved backends (backends received from resolver, not from remote balancer) -// if no connection to remote balancers was successful. -func (lb *lbBalancer) fallbackToBackendsAfter(fallbackTimeout time.Duration) { - timer := time.NewTimer(fallbackTimeout) - defer timer.Stop() - select { - case <-timer.C: - case <-lb.doneCh: - return - } - lb.mu.Lock() - if lb.serverListReceived { - lb.mu.Unlock() - return - } - lb.fallbackTimerExpired = true - lb.refreshSubConns(lb.resolvedBackendAddrs) - lb.mu.Unlock() -} - -// HandleResolvedAddrs sends the updated remoteLB addresses to remoteLB -// clientConn. The remoteLB clientConn will handle creating/removing remoteLB -// connections. -func (lb *lbBalancer) HandleResolvedAddrs(addrs []resolver.Address, err error) { - grpclog.Infof("lbBalancer: handleResolvedResult: %+v", addrs) - if len(addrs) <= 0 { - return - } - - var remoteBalancerAddrs, backendAddrs []resolver.Address - for _, a := range addrs { - if a.Type == resolver.GRPCLB { - remoteBalancerAddrs = append(remoteBalancerAddrs, a) - } else { - backendAddrs = append(backendAddrs, a) - } - } - - if lb.ccRemoteLB == nil { - if len(remoteBalancerAddrs) <= 0 { - grpclog.Errorf("grpclb: no remote balancer address is available, should never happen") - return - } - // First time receiving resolved addresses, create a cc to remote - // balancers. - lb.dialRemoteLB(remoteBalancerAddrs[0].ServerName) - // Start the fallback goroutine. - go lb.fallbackToBackendsAfter(lb.fallbackTimeout) - } - - // cc to remote balancers uses lb.manualResolver. Send the updated remote - // balancer addresses to it through manualResolver. - lb.manualResolver.NewAddress(remoteBalancerAddrs) - - lb.mu.Lock() - lb.resolvedBackendAddrs = backendAddrs - // If serverListReceived is true, connection to remote balancer was - // successful and there's no need to do fallback anymore. - // If fallbackTimerExpired is false, fallback hasn't happened yet. - if !lb.serverListReceived && lb.fallbackTimerExpired { - // This means we received a new list of resolved backends, and we are - // still in fallback mode. Need to update the list of backends we are - // using to the new list of backends. - lb.refreshSubConns(lb.resolvedBackendAddrs) - } - lb.mu.Unlock() -} - -func (lb *lbBalancer) Close() { - select { - case <-lb.doneCh: - return - default: - } - close(lb.doneCh) - if lb.ccRemoteLB != nil { - lb.ccRemoteLB.Close() - } - lb.cc.close() -} diff --git a/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.pb.go b/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.pb.go deleted file mode 100644 index b3b32b48e86..00000000000 --- a/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.pb.go +++ /dev/null @@ -1,799 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc_lb_v1/messages/messages.proto - -package messages // import "google.golang.org/grpc/grpclb/grpc_lb_v1/messages" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// 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 - -type Duration struct { - // Signed seconds of the span of time. Must be from -315,576,000,000 - // to +315,576,000,000 inclusive. - Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"` - // Signed fractions of a second at nanosecond resolution of the span - // of time. Durations less than one second are represented with a 0 - // `seconds` field and a positive or negative `nanos` field. For durations - // of one second or more, a non-zero value for the `nanos` field must be - // of the same sign as the `seconds` field. Must be from -999,999,999 - // to +999,999,999 inclusive. - Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Duration) Reset() { *m = Duration{} } -func (m *Duration) String() string { return proto.CompactTextString(m) } -func (*Duration) ProtoMessage() {} -func (*Duration) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b81c731f0e83edbd, []int{0} -} -func (m *Duration) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Duration.Unmarshal(m, b) -} -func (m *Duration) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Duration.Marshal(b, m, deterministic) -} -func (dst *Duration) XXX_Merge(src proto.Message) { - xxx_messageInfo_Duration.Merge(dst, src) -} -func (m *Duration) XXX_Size() int { - return xxx_messageInfo_Duration.Size(m) -} -func (m *Duration) XXX_DiscardUnknown() { - xxx_messageInfo_Duration.DiscardUnknown(m) -} - -var xxx_messageInfo_Duration proto.InternalMessageInfo - -func (m *Duration) GetSeconds() int64 { - if m != nil { - return m.Seconds - } - return 0 -} - -func (m *Duration) GetNanos() int32 { - if m != nil { - return m.Nanos - } - return 0 -} - -type Timestamp struct { - // Represents seconds of UTC time since Unix epoch - // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - // 9999-12-31T23:59:59Z inclusive. - Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"` - // Non-negative fractions of a second at nanosecond resolution. Negative - // second values with fractions must still have non-negative nanos values - // that count forward in time. Must be from 0 to 999,999,999 - // inclusive. - Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Timestamp) Reset() { *m = Timestamp{} } -func (m *Timestamp) String() string { return proto.CompactTextString(m) } -func (*Timestamp) ProtoMessage() {} -func (*Timestamp) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b81c731f0e83edbd, []int{1} -} -func (m *Timestamp) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Timestamp.Unmarshal(m, b) -} -func (m *Timestamp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Timestamp.Marshal(b, m, deterministic) -} -func (dst *Timestamp) XXX_Merge(src proto.Message) { - xxx_messageInfo_Timestamp.Merge(dst, src) -} -func (m *Timestamp) XXX_Size() int { - return xxx_messageInfo_Timestamp.Size(m) -} -func (m *Timestamp) XXX_DiscardUnknown() { - xxx_messageInfo_Timestamp.DiscardUnknown(m) -} - -var xxx_messageInfo_Timestamp proto.InternalMessageInfo - -func (m *Timestamp) GetSeconds() int64 { - if m != nil { - return m.Seconds - } - return 0 -} - -func (m *Timestamp) GetNanos() int32 { - if m != nil { - return m.Nanos - } - return 0 -} - -type LoadBalanceRequest struct { - // Types that are valid to be assigned to LoadBalanceRequestType: - // *LoadBalanceRequest_InitialRequest - // *LoadBalanceRequest_ClientStats - LoadBalanceRequestType isLoadBalanceRequest_LoadBalanceRequestType `protobuf_oneof:"load_balance_request_type"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *LoadBalanceRequest) Reset() { *m = LoadBalanceRequest{} } -func (m *LoadBalanceRequest) String() string { return proto.CompactTextString(m) } -func (*LoadBalanceRequest) ProtoMessage() {} -func (*LoadBalanceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b81c731f0e83edbd, []int{2} -} -func (m *LoadBalanceRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_LoadBalanceRequest.Unmarshal(m, b) -} -func (m *LoadBalanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_LoadBalanceRequest.Marshal(b, m, deterministic) -} -func (dst *LoadBalanceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_LoadBalanceRequest.Merge(dst, src) -} -func (m *LoadBalanceRequest) XXX_Size() int { - return xxx_messageInfo_LoadBalanceRequest.Size(m) -} -func (m *LoadBalanceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_LoadBalanceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_LoadBalanceRequest proto.InternalMessageInfo - -type isLoadBalanceRequest_LoadBalanceRequestType interface { - isLoadBalanceRequest_LoadBalanceRequestType() -} - -type LoadBalanceRequest_InitialRequest struct { - InitialRequest *InitialLoadBalanceRequest `protobuf:"bytes,1,opt,name=initial_request,json=initialRequest,oneof"` -} -type LoadBalanceRequest_ClientStats struct { - ClientStats *ClientStats `protobuf:"bytes,2,opt,name=client_stats,json=clientStats,oneof"` -} - -func (*LoadBalanceRequest_InitialRequest) isLoadBalanceRequest_LoadBalanceRequestType() {} -func (*LoadBalanceRequest_ClientStats) isLoadBalanceRequest_LoadBalanceRequestType() {} - -func (m *LoadBalanceRequest) GetLoadBalanceRequestType() isLoadBalanceRequest_LoadBalanceRequestType { - if m != nil { - return m.LoadBalanceRequestType - } - return nil -} - -func (m *LoadBalanceRequest) GetInitialRequest() *InitialLoadBalanceRequest { - if x, ok := m.GetLoadBalanceRequestType().(*LoadBalanceRequest_InitialRequest); ok { - return x.InitialRequest - } - return nil -} - -func (m *LoadBalanceRequest) GetClientStats() *ClientStats { - if x, ok := m.GetLoadBalanceRequestType().(*LoadBalanceRequest_ClientStats); ok { - return x.ClientStats - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*LoadBalanceRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _LoadBalanceRequest_OneofMarshaler, _LoadBalanceRequest_OneofUnmarshaler, _LoadBalanceRequest_OneofSizer, []interface{}{ - (*LoadBalanceRequest_InitialRequest)(nil), - (*LoadBalanceRequest_ClientStats)(nil), - } -} - -func _LoadBalanceRequest_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*LoadBalanceRequest) - // load_balance_request_type - switch x := m.LoadBalanceRequestType.(type) { - case *LoadBalanceRequest_InitialRequest: - b.EncodeVarint(1<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.InitialRequest); err != nil { - return err - } - case *LoadBalanceRequest_ClientStats: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ClientStats); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("LoadBalanceRequest.LoadBalanceRequestType has unexpected type %T", x) - } - return nil -} - -func _LoadBalanceRequest_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*LoadBalanceRequest) - switch tag { - case 1: // load_balance_request_type.initial_request - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(InitialLoadBalanceRequest) - err := b.DecodeMessage(msg) - m.LoadBalanceRequestType = &LoadBalanceRequest_InitialRequest{msg} - return true, err - case 2: // load_balance_request_type.client_stats - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ClientStats) - err := b.DecodeMessage(msg) - m.LoadBalanceRequestType = &LoadBalanceRequest_ClientStats{msg} - return true, err - default: - return false, nil - } -} - -func _LoadBalanceRequest_OneofSizer(msg proto.Message) (n int) { - m := msg.(*LoadBalanceRequest) - // load_balance_request_type - switch x := m.LoadBalanceRequestType.(type) { - case *LoadBalanceRequest_InitialRequest: - s := proto.Size(x.InitialRequest) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *LoadBalanceRequest_ClientStats: - s := proto.Size(x.ClientStats) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type InitialLoadBalanceRequest struct { - // Name of load balanced service (IE, balancer.service.com) - // length should be less than 256 bytes. - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InitialLoadBalanceRequest) Reset() { *m = InitialLoadBalanceRequest{} } -func (m *InitialLoadBalanceRequest) String() string { return proto.CompactTextString(m) } -func (*InitialLoadBalanceRequest) ProtoMessage() {} -func (*InitialLoadBalanceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b81c731f0e83edbd, []int{3} -} -func (m *InitialLoadBalanceRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InitialLoadBalanceRequest.Unmarshal(m, b) -} -func (m *InitialLoadBalanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InitialLoadBalanceRequest.Marshal(b, m, deterministic) -} -func (dst *InitialLoadBalanceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_InitialLoadBalanceRequest.Merge(dst, src) -} -func (m *InitialLoadBalanceRequest) XXX_Size() int { - return xxx_messageInfo_InitialLoadBalanceRequest.Size(m) -} -func (m *InitialLoadBalanceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_InitialLoadBalanceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_InitialLoadBalanceRequest proto.InternalMessageInfo - -func (m *InitialLoadBalanceRequest) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -// Contains client level statistics that are useful to load balancing. Each -// count except the timestamp should be reset to zero after reporting the stats. -type ClientStats struct { - // The timestamp of generating the report. - Timestamp *Timestamp `protobuf:"bytes,1,opt,name=timestamp" json:"timestamp,omitempty"` - // The total number of RPCs that started. - NumCallsStarted int64 `protobuf:"varint,2,opt,name=num_calls_started,json=numCallsStarted" json:"num_calls_started,omitempty"` - // The total number of RPCs that finished. - NumCallsFinished int64 `protobuf:"varint,3,opt,name=num_calls_finished,json=numCallsFinished" json:"num_calls_finished,omitempty"` - // The total number of RPCs that were dropped by the client because of rate - // limiting. - NumCallsFinishedWithDropForRateLimiting int64 `protobuf:"varint,4,opt,name=num_calls_finished_with_drop_for_rate_limiting,json=numCallsFinishedWithDropForRateLimiting" json:"num_calls_finished_with_drop_for_rate_limiting,omitempty"` - // The total number of RPCs that were dropped by the client because of load - // balancing. - NumCallsFinishedWithDropForLoadBalancing int64 `protobuf:"varint,5,opt,name=num_calls_finished_with_drop_for_load_balancing,json=numCallsFinishedWithDropForLoadBalancing" json:"num_calls_finished_with_drop_for_load_balancing,omitempty"` - // The total number of RPCs that failed to reach a server except dropped RPCs. - NumCallsFinishedWithClientFailedToSend int64 `protobuf:"varint,6,opt,name=num_calls_finished_with_client_failed_to_send,json=numCallsFinishedWithClientFailedToSend" json:"num_calls_finished_with_client_failed_to_send,omitempty"` - // The total number of RPCs that finished and are known to have been received - // by a server. - NumCallsFinishedKnownReceived int64 `protobuf:"varint,7,opt,name=num_calls_finished_known_received,json=numCallsFinishedKnownReceived" json:"num_calls_finished_known_received,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ClientStats) Reset() { *m = ClientStats{} } -func (m *ClientStats) String() string { return proto.CompactTextString(m) } -func (*ClientStats) ProtoMessage() {} -func (*ClientStats) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b81c731f0e83edbd, []int{4} -} -func (m *ClientStats) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ClientStats.Unmarshal(m, b) -} -func (m *ClientStats) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ClientStats.Marshal(b, m, deterministic) -} -func (dst *ClientStats) XXX_Merge(src proto.Message) { - xxx_messageInfo_ClientStats.Merge(dst, src) -} -func (m *ClientStats) XXX_Size() int { - return xxx_messageInfo_ClientStats.Size(m) -} -func (m *ClientStats) XXX_DiscardUnknown() { - xxx_messageInfo_ClientStats.DiscardUnknown(m) -} - -var xxx_messageInfo_ClientStats proto.InternalMessageInfo - -func (m *ClientStats) GetTimestamp() *Timestamp { - if m != nil { - return m.Timestamp - } - return nil -} - -func (m *ClientStats) GetNumCallsStarted() int64 { - if m != nil { - return m.NumCallsStarted - } - return 0 -} - -func (m *ClientStats) GetNumCallsFinished() int64 { - if m != nil { - return m.NumCallsFinished - } - return 0 -} - -func (m *ClientStats) GetNumCallsFinishedWithDropForRateLimiting() int64 { - if m != nil { - return m.NumCallsFinishedWithDropForRateLimiting - } - return 0 -} - -func (m *ClientStats) GetNumCallsFinishedWithDropForLoadBalancing() int64 { - if m != nil { - return m.NumCallsFinishedWithDropForLoadBalancing - } - return 0 -} - -func (m *ClientStats) GetNumCallsFinishedWithClientFailedToSend() int64 { - if m != nil { - return m.NumCallsFinishedWithClientFailedToSend - } - return 0 -} - -func (m *ClientStats) GetNumCallsFinishedKnownReceived() int64 { - if m != nil { - return m.NumCallsFinishedKnownReceived - } - return 0 -} - -type LoadBalanceResponse struct { - // Types that are valid to be assigned to LoadBalanceResponseType: - // *LoadBalanceResponse_InitialResponse - // *LoadBalanceResponse_ServerList - LoadBalanceResponseType isLoadBalanceResponse_LoadBalanceResponseType `protobuf_oneof:"load_balance_response_type"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *LoadBalanceResponse) Reset() { *m = LoadBalanceResponse{} } -func (m *LoadBalanceResponse) String() string { return proto.CompactTextString(m) } -func (*LoadBalanceResponse) ProtoMessage() {} -func (*LoadBalanceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b81c731f0e83edbd, []int{5} -} -func (m *LoadBalanceResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_LoadBalanceResponse.Unmarshal(m, b) -} -func (m *LoadBalanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_LoadBalanceResponse.Marshal(b, m, deterministic) -} -func (dst *LoadBalanceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_LoadBalanceResponse.Merge(dst, src) -} -func (m *LoadBalanceResponse) XXX_Size() int { - return xxx_messageInfo_LoadBalanceResponse.Size(m) -} -func (m *LoadBalanceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_LoadBalanceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_LoadBalanceResponse proto.InternalMessageInfo - -type isLoadBalanceResponse_LoadBalanceResponseType interface { - isLoadBalanceResponse_LoadBalanceResponseType() -} - -type LoadBalanceResponse_InitialResponse struct { - InitialResponse *InitialLoadBalanceResponse `protobuf:"bytes,1,opt,name=initial_response,json=initialResponse,oneof"` -} -type LoadBalanceResponse_ServerList struct { - ServerList *ServerList `protobuf:"bytes,2,opt,name=server_list,json=serverList,oneof"` -} - -func (*LoadBalanceResponse_InitialResponse) isLoadBalanceResponse_LoadBalanceResponseType() {} -func (*LoadBalanceResponse_ServerList) isLoadBalanceResponse_LoadBalanceResponseType() {} - -func (m *LoadBalanceResponse) GetLoadBalanceResponseType() isLoadBalanceResponse_LoadBalanceResponseType { - if m != nil { - return m.LoadBalanceResponseType - } - return nil -} - -func (m *LoadBalanceResponse) GetInitialResponse() *InitialLoadBalanceResponse { - if x, ok := m.GetLoadBalanceResponseType().(*LoadBalanceResponse_InitialResponse); ok { - return x.InitialResponse - } - return nil -} - -func (m *LoadBalanceResponse) GetServerList() *ServerList { - if x, ok := m.GetLoadBalanceResponseType().(*LoadBalanceResponse_ServerList); ok { - return x.ServerList - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*LoadBalanceResponse) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _LoadBalanceResponse_OneofMarshaler, _LoadBalanceResponse_OneofUnmarshaler, _LoadBalanceResponse_OneofSizer, []interface{}{ - (*LoadBalanceResponse_InitialResponse)(nil), - (*LoadBalanceResponse_ServerList)(nil), - } -} - -func _LoadBalanceResponse_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*LoadBalanceResponse) - // load_balance_response_type - switch x := m.LoadBalanceResponseType.(type) { - case *LoadBalanceResponse_InitialResponse: - b.EncodeVarint(1<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.InitialResponse); err != nil { - return err - } - case *LoadBalanceResponse_ServerList: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ServerList); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("LoadBalanceResponse.LoadBalanceResponseType has unexpected type %T", x) - } - return nil -} - -func _LoadBalanceResponse_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*LoadBalanceResponse) - switch tag { - case 1: // load_balance_response_type.initial_response - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(InitialLoadBalanceResponse) - err := b.DecodeMessage(msg) - m.LoadBalanceResponseType = &LoadBalanceResponse_InitialResponse{msg} - return true, err - case 2: // load_balance_response_type.server_list - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ServerList) - err := b.DecodeMessage(msg) - m.LoadBalanceResponseType = &LoadBalanceResponse_ServerList{msg} - return true, err - default: - return false, nil - } -} - -func _LoadBalanceResponse_OneofSizer(msg proto.Message) (n int) { - m := msg.(*LoadBalanceResponse) - // load_balance_response_type - switch x := m.LoadBalanceResponseType.(type) { - case *LoadBalanceResponse_InitialResponse: - s := proto.Size(x.InitialResponse) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *LoadBalanceResponse_ServerList: - s := proto.Size(x.ServerList) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type InitialLoadBalanceResponse struct { - // This is an application layer redirect that indicates the client should use - // the specified server for load balancing. When this field is non-empty in - // the response, the client should open a separate connection to the - // load_balancer_delegate and call the BalanceLoad method. Its length should - // be less than 64 bytes. - LoadBalancerDelegate string `protobuf:"bytes,1,opt,name=load_balancer_delegate,json=loadBalancerDelegate" json:"load_balancer_delegate,omitempty"` - // This interval defines how often the client should send the client stats - // to the load balancer. Stats should only be reported when the duration is - // positive. - ClientStatsReportInterval *Duration `protobuf:"bytes,2,opt,name=client_stats_report_interval,json=clientStatsReportInterval" json:"client_stats_report_interval,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InitialLoadBalanceResponse) Reset() { *m = InitialLoadBalanceResponse{} } -func (m *InitialLoadBalanceResponse) String() string { return proto.CompactTextString(m) } -func (*InitialLoadBalanceResponse) ProtoMessage() {} -func (*InitialLoadBalanceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b81c731f0e83edbd, []int{6} -} -func (m *InitialLoadBalanceResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InitialLoadBalanceResponse.Unmarshal(m, b) -} -func (m *InitialLoadBalanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InitialLoadBalanceResponse.Marshal(b, m, deterministic) -} -func (dst *InitialLoadBalanceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_InitialLoadBalanceResponse.Merge(dst, src) -} -func (m *InitialLoadBalanceResponse) XXX_Size() int { - return xxx_messageInfo_InitialLoadBalanceResponse.Size(m) -} -func (m *InitialLoadBalanceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_InitialLoadBalanceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_InitialLoadBalanceResponse proto.InternalMessageInfo - -func (m *InitialLoadBalanceResponse) GetLoadBalancerDelegate() string { - if m != nil { - return m.LoadBalancerDelegate - } - return "" -} - -func (m *InitialLoadBalanceResponse) GetClientStatsReportInterval() *Duration { - if m != nil { - return m.ClientStatsReportInterval - } - return nil -} - -type ServerList struct { - // Contains a list of servers selected by the load balancer. The list will - // be updated when server resolutions change or as needed to balance load - // across more servers. The client should consume the server list in order - // unless instructed otherwise via the client_config. - Servers []*Server `protobuf:"bytes,1,rep,name=servers" json:"servers,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServerList) Reset() { *m = ServerList{} } -func (m *ServerList) String() string { return proto.CompactTextString(m) } -func (*ServerList) ProtoMessage() {} -func (*ServerList) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b81c731f0e83edbd, []int{7} -} -func (m *ServerList) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServerList.Unmarshal(m, b) -} -func (m *ServerList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServerList.Marshal(b, m, deterministic) -} -func (dst *ServerList) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServerList.Merge(dst, src) -} -func (m *ServerList) XXX_Size() int { - return xxx_messageInfo_ServerList.Size(m) -} -func (m *ServerList) XXX_DiscardUnknown() { - xxx_messageInfo_ServerList.DiscardUnknown(m) -} - -var xxx_messageInfo_ServerList proto.InternalMessageInfo - -func (m *ServerList) GetServers() []*Server { - if m != nil { - return m.Servers - } - return nil -} - -// Contains server information. When none of the [drop_for_*] fields are true, -// use the other fields. When drop_for_rate_limiting is true, ignore all other -// fields. Use drop_for_load_balancing only when it is true and -// drop_for_rate_limiting is false. -type Server struct { - // A resolved address for the server, serialized in network-byte-order. It may - // either be an IPv4 or IPv6 address. - IpAddress []byte `protobuf:"bytes,1,opt,name=ip_address,json=ipAddress,proto3" json:"ip_address,omitempty"` - // A resolved port number for the server. - Port int32 `protobuf:"varint,2,opt,name=port" json:"port,omitempty"` - // An opaque but printable token given to the frontend for each pick. All - // frontend requests for that pick must include the token in its initial - // metadata. The token is used by the backend to verify the request and to - // allow the backend to report load to the gRPC LB system. - // - // Its length is variable but less than 50 bytes. - LoadBalanceToken string `protobuf:"bytes,3,opt,name=load_balance_token,json=loadBalanceToken" json:"load_balance_token,omitempty"` - // Indicates whether this particular request should be dropped by the client - // for rate limiting. - DropForRateLimiting bool `protobuf:"varint,4,opt,name=drop_for_rate_limiting,json=dropForRateLimiting" json:"drop_for_rate_limiting,omitempty"` - // Indicates whether this particular request should be dropped by the client - // for load balancing. - DropForLoadBalancing bool `protobuf:"varint,5,opt,name=drop_for_load_balancing,json=dropForLoadBalancing" json:"drop_for_load_balancing,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Server) Reset() { *m = Server{} } -func (m *Server) String() string { return proto.CompactTextString(m) } -func (*Server) ProtoMessage() {} -func (*Server) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b81c731f0e83edbd, []int{8} -} -func (m *Server) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Server.Unmarshal(m, b) -} -func (m *Server) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Server.Marshal(b, m, deterministic) -} -func (dst *Server) XXX_Merge(src proto.Message) { - xxx_messageInfo_Server.Merge(dst, src) -} -func (m *Server) XXX_Size() int { - return xxx_messageInfo_Server.Size(m) -} -func (m *Server) XXX_DiscardUnknown() { - xxx_messageInfo_Server.DiscardUnknown(m) -} - -var xxx_messageInfo_Server proto.InternalMessageInfo - -func (m *Server) GetIpAddress() []byte { - if m != nil { - return m.IpAddress - } - return nil -} - -func (m *Server) GetPort() int32 { - if m != nil { - return m.Port - } - return 0 -} - -func (m *Server) GetLoadBalanceToken() string { - if m != nil { - return m.LoadBalanceToken - } - return "" -} - -func (m *Server) GetDropForRateLimiting() bool { - if m != nil { - return m.DropForRateLimiting - } - return false -} - -func (m *Server) GetDropForLoadBalancing() bool { - if m != nil { - return m.DropForLoadBalancing - } - return false -} - -func init() { - proto.RegisterType((*Duration)(nil), "grpc.lb.v1.Duration") - proto.RegisterType((*Timestamp)(nil), "grpc.lb.v1.Timestamp") - proto.RegisterType((*LoadBalanceRequest)(nil), "grpc.lb.v1.LoadBalanceRequest") - proto.RegisterType((*InitialLoadBalanceRequest)(nil), "grpc.lb.v1.InitialLoadBalanceRequest") - proto.RegisterType((*ClientStats)(nil), "grpc.lb.v1.ClientStats") - proto.RegisterType((*LoadBalanceResponse)(nil), "grpc.lb.v1.LoadBalanceResponse") - proto.RegisterType((*InitialLoadBalanceResponse)(nil), "grpc.lb.v1.InitialLoadBalanceResponse") - proto.RegisterType((*ServerList)(nil), "grpc.lb.v1.ServerList") - proto.RegisterType((*Server)(nil), "grpc.lb.v1.Server") -} - -func init() { - proto.RegisterFile("grpc_lb_v1/messages/messages.proto", fileDescriptor_messages_b81c731f0e83edbd) -} - -var fileDescriptor_messages_b81c731f0e83edbd = []byte{ - // 731 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x55, 0xdd, 0x4e, 0x1b, 0x39, - 0x14, 0x26, 0x9b, 0x00, 0xc9, 0x09, 0x5a, 0xb2, 0x26, 0x0b, 0x81, 0x05, 0x89, 0x1d, 0x69, 0xd9, - 0x68, 0xc5, 0x4e, 0x04, 0xd9, 0xbd, 0xe8, 0xcf, 0x45, 0x1b, 0x10, 0x0a, 0x2d, 0x17, 0x95, 0x43, - 0x55, 0xa9, 0x52, 0x65, 0x39, 0x19, 0x33, 0x58, 0x38, 0xf6, 0xd4, 0x76, 0x82, 0xfa, 0x08, 0x7d, - 0x94, 0x3e, 0x46, 0xd5, 0x67, 0xe8, 0xfb, 0x54, 0xe3, 0x99, 0xc9, 0x0c, 0x10, 0x40, 0xbd, 0x89, - 0xec, 0xe3, 0xef, 0x7c, 0xdf, 0xf1, 0x89, 0xbf, 0x33, 0xe0, 0x85, 0x3a, 0x1a, 0x11, 0x31, 0x24, - 0xd3, 0x83, 0xce, 0x98, 0x19, 0x43, 0x43, 0x66, 0x66, 0x0b, 0x3f, 0xd2, 0xca, 0x2a, 0x04, 0x31, - 0xc6, 0x17, 0x43, 0x7f, 0x7a, 0xe0, 0x3d, 0x85, 0xea, 0xf1, 0x44, 0x53, 0xcb, 0x95, 0x44, 0x2d, - 0x58, 0x36, 0x6c, 0xa4, 0x64, 0x60, 0x5a, 0xa5, 0xdd, 0x52, 0xbb, 0x8c, 0xb3, 0x2d, 0x6a, 0xc2, - 0xa2, 0xa4, 0x52, 0x99, 0xd6, 0x2f, 0xbb, 0xa5, 0xf6, 0x22, 0x4e, 0x36, 0xde, 0x33, 0xa8, 0x9d, - 0xf3, 0x31, 0x33, 0x96, 0x8e, 0xa3, 0x9f, 0x4e, 0xfe, 0x5a, 0x02, 0x74, 0xa6, 0x68, 0xd0, 0xa3, - 0x82, 0xca, 0x11, 0xc3, 0xec, 0xe3, 0x84, 0x19, 0x8b, 0xde, 0xc0, 0x2a, 0x97, 0xdc, 0x72, 0x2a, - 0x88, 0x4e, 0x42, 0x8e, 0xae, 0x7e, 0xf8, 0x97, 0x9f, 0x57, 0xed, 0x9f, 0x26, 0x90, 0xbb, 0xf9, - 0xfd, 0x05, 0xfc, 0x6b, 0x9a, 0x9f, 0x31, 0x3e, 0x87, 0x95, 0x91, 0xe0, 0x4c, 0x5a, 0x62, 0x2c, - 0xb5, 0x49, 0x15, 0xf5, 0xc3, 0x8d, 0x22, 0xdd, 0x91, 0x3b, 0x1f, 0xc4, 0xc7, 0xfd, 0x05, 0x5c, - 0x1f, 0xe5, 0xdb, 0xde, 0x1f, 0xb0, 0x29, 0x14, 0x0d, 0xc8, 0x30, 0x91, 0xc9, 0x8a, 0x22, 0xf6, - 0x53, 0xc4, 0xbc, 0x0e, 0x6c, 0xde, 0x5b, 0x09, 0x42, 0x50, 0x91, 0x74, 0xcc, 0x5c, 0xf9, 0x35, - 0xec, 0xd6, 0xde, 0xe7, 0x0a, 0xd4, 0x0b, 0x62, 0xa8, 0x0b, 0x35, 0x9b, 0x75, 0x30, 0xbd, 0xe7, - 0xef, 0xc5, 0xc2, 0x66, 0xed, 0xc5, 0x39, 0x0e, 0xfd, 0x03, 0xbf, 0xc9, 0xc9, 0x98, 0x8c, 0xa8, - 0x10, 0x26, 0xbe, 0x93, 0xb6, 0x2c, 0x70, 0xb7, 0x2a, 0xe3, 0x55, 0x39, 0x19, 0x1f, 0xc5, 0xf1, - 0x41, 0x12, 0x46, 0xfb, 0x80, 0x72, 0xec, 0x05, 0x97, 0xdc, 0x5c, 0xb2, 0xa0, 0x55, 0x76, 0xe0, - 0x46, 0x06, 0x3e, 0x49, 0xe3, 0x88, 0x80, 0x7f, 0x17, 0x4d, 0xae, 0xb9, 0xbd, 0x24, 0x81, 0x56, - 0x11, 0xb9, 0x50, 0x9a, 0x68, 0x6a, 0x19, 0x11, 0x7c, 0xcc, 0x2d, 0x97, 0x61, 0xab, 0xe2, 0x98, - 0xfe, 0xbe, 0xcd, 0xf4, 0x8e, 0xdb, 0xcb, 0x63, 0xad, 0xa2, 0x13, 0xa5, 0x31, 0xb5, 0xec, 0x2c, - 0x85, 0x23, 0x0a, 0x9d, 0x47, 0x05, 0x0a, 0xed, 0x8e, 0x15, 0x16, 0x9d, 0x42, 0xfb, 0x01, 0x85, - 0xbc, 0xf7, 0xb1, 0xc4, 0x07, 0xf8, 0xf7, 0x3e, 0x89, 0xf4, 0x19, 0x5c, 0x50, 0x2e, 0x58, 0x40, - 0xac, 0x22, 0x86, 0xc9, 0xa0, 0xb5, 0xe4, 0x04, 0xf6, 0xe6, 0x09, 0x24, 0x7f, 0xd5, 0x89, 0xc3, - 0x9f, 0xab, 0x01, 0x93, 0x01, 0xea, 0xc3, 0x9f, 0x73, 0xe8, 0xaf, 0xa4, 0xba, 0x96, 0x44, 0xb3, - 0x11, 0xe3, 0x53, 0x16, 0xb4, 0x96, 0x1d, 0xe5, 0xce, 0x6d, 0xca, 0xd7, 0x31, 0x0a, 0xa7, 0x20, - 0xef, 0x5b, 0x09, 0xd6, 0x6e, 0x3c, 0x1b, 0x13, 0x29, 0x69, 0x18, 0x1a, 0x40, 0x23, 0x77, 0x40, - 0x12, 0x4b, 0x9f, 0xc6, 0xde, 0x63, 0x16, 0x48, 0xd0, 0xfd, 0x05, 0xbc, 0x3a, 0xf3, 0x40, 0x4a, - 0xfa, 0x04, 0xea, 0x86, 0xe9, 0x29, 0xd3, 0x44, 0x70, 0x63, 0x53, 0x0f, 0xac, 0x17, 0xf9, 0x06, - 0xee, 0xf8, 0x8c, 0x3b, 0x0f, 0x81, 0x99, 0xed, 0x7a, 0xdb, 0xb0, 0x75, 0xcb, 0x01, 0x09, 0x67, - 0x62, 0x81, 0x2f, 0x25, 0xd8, 0xba, 0xbf, 0x14, 0xf4, 0x1f, 0xac, 0x17, 0x93, 0x35, 0x09, 0x98, - 0x60, 0x21, 0xb5, 0x99, 0x2d, 0x9a, 0x22, 0x4f, 0xd2, 0xc7, 0xe9, 0x19, 0x7a, 0x0b, 0xdb, 0x45, - 0xcb, 0x12, 0xcd, 0x22, 0xa5, 0x2d, 0xe1, 0xd2, 0x32, 0x3d, 0xa5, 0x22, 0x2d, 0xbf, 0x59, 0x2c, - 0x3f, 0x1b, 0x62, 0x78, 0xb3, 0xe0, 0x5e, 0xec, 0xf2, 0x4e, 0xd3, 0x34, 0xef, 0x05, 0x40, 0x7e, - 0x4b, 0xb4, 0x1f, 0x0f, 0xac, 0x78, 0x17, 0x0f, 0xac, 0x72, 0xbb, 0x7e, 0x88, 0xee, 0xb6, 0x03, - 0x67, 0x90, 0x57, 0x95, 0x6a, 0xb9, 0x51, 0xf1, 0xbe, 0x97, 0x60, 0x29, 0x39, 0x41, 0x3b, 0x00, - 0x3c, 0x22, 0x34, 0x08, 0x34, 0x33, 0xc9, 0xc8, 0x5b, 0xc1, 0x35, 0x1e, 0xbd, 0x4c, 0x02, 0xb1, - 0xfb, 0x63, 0xed, 0x74, 0xe6, 0xb9, 0x75, 0x6c, 0xc6, 0x1b, 0x9d, 0xb4, 0xea, 0x8a, 0x49, 0x67, - 0xc6, 0x1a, 0x6e, 0x14, 0x1a, 0x71, 0x1e, 0xc7, 0x51, 0x17, 0xd6, 0x1f, 0x30, 0x5d, 0x15, 0xaf, - 0x05, 0x73, 0x0c, 0xf6, 0x3f, 0x6c, 0x3c, 0x64, 0xa4, 0x2a, 0x6e, 0x06, 0x73, 0x4c, 0xd3, 0xeb, - 0xbe, 0x3f, 0x08, 0x95, 0x0a, 0x05, 0xf3, 0x43, 0x25, 0xa8, 0x0c, 0x7d, 0xa5, 0xc3, 0x4e, 0xdc, - 0x0d, 0xf7, 0x23, 0x86, 0x9d, 0x39, 0x5f, 0x95, 0xe1, 0x92, 0xfb, 0x9a, 0x74, 0x7f, 0x04, 0x00, - 0x00, 0xff, 0xff, 0x8e, 0xd0, 0x70, 0xb7, 0x73, 0x06, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/grpclb_picker.go b/vendor/google.golang.org/grpc/grpclb_picker.go deleted file mode 100644 index 872c7ccea0e..00000000000 --- a/vendor/google.golang.org/grpc/grpclb_picker.go +++ /dev/null @@ -1,159 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 grpc - -import ( - "sync" - "sync/atomic" - - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/codes" - lbpb "google.golang.org/grpc/grpclb/grpc_lb_v1/messages" - "google.golang.org/grpc/status" -) - -type rpcStats struct { - NumCallsStarted int64 - NumCallsFinished int64 - NumCallsFinishedWithDropForRateLimiting int64 - NumCallsFinishedWithDropForLoadBalancing int64 - NumCallsFinishedWithClientFailedToSend int64 - NumCallsFinishedKnownReceived int64 -} - -// toClientStats converts rpcStats to lbpb.ClientStats, and clears rpcStats. -func (s *rpcStats) toClientStats() *lbpb.ClientStats { - stats := &lbpb.ClientStats{ - NumCallsStarted: atomic.SwapInt64(&s.NumCallsStarted, 0), - NumCallsFinished: atomic.SwapInt64(&s.NumCallsFinished, 0), - NumCallsFinishedWithDropForRateLimiting: atomic.SwapInt64(&s.NumCallsFinishedWithDropForRateLimiting, 0), - NumCallsFinishedWithDropForLoadBalancing: atomic.SwapInt64(&s.NumCallsFinishedWithDropForLoadBalancing, 0), - NumCallsFinishedWithClientFailedToSend: atomic.SwapInt64(&s.NumCallsFinishedWithClientFailedToSend, 0), - NumCallsFinishedKnownReceived: atomic.SwapInt64(&s.NumCallsFinishedKnownReceived, 0), - } - return stats -} - -func (s *rpcStats) dropForRateLimiting() { - atomic.AddInt64(&s.NumCallsStarted, 1) - atomic.AddInt64(&s.NumCallsFinishedWithDropForRateLimiting, 1) - atomic.AddInt64(&s.NumCallsFinished, 1) -} - -func (s *rpcStats) dropForLoadBalancing() { - atomic.AddInt64(&s.NumCallsStarted, 1) - atomic.AddInt64(&s.NumCallsFinishedWithDropForLoadBalancing, 1) - atomic.AddInt64(&s.NumCallsFinished, 1) -} - -func (s *rpcStats) failedToSend() { - atomic.AddInt64(&s.NumCallsStarted, 1) - atomic.AddInt64(&s.NumCallsFinishedWithClientFailedToSend, 1) - atomic.AddInt64(&s.NumCallsFinished, 1) -} - -func (s *rpcStats) knownReceived() { - atomic.AddInt64(&s.NumCallsStarted, 1) - atomic.AddInt64(&s.NumCallsFinishedKnownReceived, 1) - atomic.AddInt64(&s.NumCallsFinished, 1) -} - -type errPicker struct { - // Pick always returns this err. - err error -} - -func (p *errPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { - return nil, nil, p.err -} - -// rrPicker does roundrobin on subConns. It's typically used when there's no -// response from remote balancer, and grpclb falls back to the resolved -// backends. -// -// It guaranteed that len(subConns) > 0. -type rrPicker struct { - mu sync.Mutex - subConns []balancer.SubConn // The subConns that were READY when taking the snapshot. - subConnsNext int -} - -func (p *rrPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { - p.mu.Lock() - defer p.mu.Unlock() - sc := p.subConns[p.subConnsNext] - p.subConnsNext = (p.subConnsNext + 1) % len(p.subConns) - return sc, nil, nil -} - -// lbPicker does two layers of picks: -// -// First layer: roundrobin on all servers in serverList, including drops and backends. -// - If it picks a drop, the RPC will fail as being dropped. -// - If it picks a backend, do a second layer pick to pick the real backend. -// -// Second layer: roundrobin on all READY backends. -// -// It's guaranteed that len(serverList) > 0. -type lbPicker struct { - mu sync.Mutex - serverList []*lbpb.Server - serverListNext int - subConns []balancer.SubConn // The subConns that were READY when taking the snapshot. - subConnsNext int - - stats *rpcStats -} - -func (p *lbPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { - p.mu.Lock() - defer p.mu.Unlock() - - // Layer one roundrobin on serverList. - s := p.serverList[p.serverListNext] - p.serverListNext = (p.serverListNext + 1) % len(p.serverList) - - // If it's a drop, return an error and fail the RPC. - if s.DropForRateLimiting { - p.stats.dropForRateLimiting() - return nil, nil, status.Errorf(codes.Unavailable, "request dropped by grpclb") - } - if s.DropForLoadBalancing { - p.stats.dropForLoadBalancing() - return nil, nil, status.Errorf(codes.Unavailable, "request dropped by grpclb") - } - - // If not a drop but there's no ready subConns. - if len(p.subConns) <= 0 { - return nil, nil, balancer.ErrNoSubConnAvailable - } - - // Return the next ready subConn in the list, also collect rpc stats. - sc := p.subConns[p.subConnsNext] - p.subConnsNext = (p.subConnsNext + 1) % len(p.subConns) - done := func(info balancer.DoneInfo) { - if !info.BytesSent { - p.stats.failedToSend() - } else if info.BytesReceived { - p.stats.knownReceived() - } - } - return sc, done, nil -} diff --git a/vendor/google.golang.org/grpc/grpclb_remote_balancer.go b/vendor/google.golang.org/grpc/grpclb_remote_balancer.go deleted file mode 100644 index b8dd4f18ce5..00000000000 --- a/vendor/google.golang.org/grpc/grpclb_remote_balancer.go +++ /dev/null @@ -1,266 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 grpc - -import ( - "fmt" - "net" - "reflect" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/channelz" - - "google.golang.org/grpc/connectivity" - lbpb "google.golang.org/grpc/grpclb/grpc_lb_v1/messages" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/resolver" -) - -// processServerList updates balaner's internal state, create/remove SubConns -// and regenerates picker using the received serverList. -func (lb *lbBalancer) processServerList(l *lbpb.ServerList) { - grpclog.Infof("lbBalancer: processing server list: %+v", l) - lb.mu.Lock() - defer lb.mu.Unlock() - - // Set serverListReceived to true so fallback will not take effect if it has - // not hit timeout. - lb.serverListReceived = true - - // If the new server list == old server list, do nothing. - if reflect.DeepEqual(lb.fullServerList, l.Servers) { - grpclog.Infof("lbBalancer: new serverlist same as the previous one, ignoring") - return - } - lb.fullServerList = l.Servers - - var backendAddrs []resolver.Address - for _, s := range l.Servers { - if s.DropForLoadBalancing || s.DropForRateLimiting { - continue - } - - md := metadata.Pairs(lbTokeyKey, s.LoadBalanceToken) - ip := net.IP(s.IpAddress) - ipStr := ip.String() - if ip.To4() == nil { - // Add square brackets to ipv6 addresses, otherwise net.Dial() and - // net.SplitHostPort() will return too many colons error. - ipStr = fmt.Sprintf("[%s]", ipStr) - } - addr := resolver.Address{ - Addr: fmt.Sprintf("%s:%d", ipStr, s.Port), - Metadata: &md, - } - - backendAddrs = append(backendAddrs, addr) - } - - // Call refreshSubConns to create/remove SubConns. - lb.refreshSubConns(backendAddrs) - // Regenerate and update picker no matter if there's update on backends (if - // any SubConn will be newed/removed). Because since the full serverList was - // different, there might be updates in drops or pick weights(different - // number of duplicates). We need to update picker with the fulllist. - // - // Now with cache, even if SubConn was newed/removed, there might be no - // state changes. - lb.regeneratePicker() - lb.cc.UpdateBalancerState(lb.state, lb.picker) -} - -// refreshSubConns creates/removes SubConns with backendAddrs. It returns a bool -// indicating whether the backendAddrs are different from the cached -// backendAddrs (whether any SubConn was newed/removed). -// Caller must hold lb.mu. -func (lb *lbBalancer) refreshSubConns(backendAddrs []resolver.Address) bool { - lb.backendAddrs = nil - var backendsUpdated bool - // addrsSet is the set converted from backendAddrs, it's used to quick - // lookup for an address. - addrsSet := make(map[resolver.Address]struct{}) - // Create new SubConns. - for _, addr := range backendAddrs { - addrWithoutMD := addr - addrWithoutMD.Metadata = nil - addrsSet[addrWithoutMD] = struct{}{} - lb.backendAddrs = append(lb.backendAddrs, addrWithoutMD) - - if _, ok := lb.subConns[addrWithoutMD]; !ok { - backendsUpdated = true - - // Use addrWithMD to create the SubConn. - sc, err := lb.cc.NewSubConn([]resolver.Address{addr}, balancer.NewSubConnOptions{}) - if err != nil { - grpclog.Warningf("roundrobinBalancer: failed to create new SubConn: %v", err) - continue - } - lb.subConns[addrWithoutMD] = sc // Use the addr without MD as key for the map. - if _, ok := lb.scStates[sc]; !ok { - // Only set state of new sc to IDLE. The state could already be - // READY for cached SubConns. - lb.scStates[sc] = connectivity.Idle - } - sc.Connect() - } - } - - for a, sc := range lb.subConns { - // a was removed by resolver. - if _, ok := addrsSet[a]; !ok { - backendsUpdated = true - - lb.cc.RemoveSubConn(sc) - delete(lb.subConns, a) - // Keep the state of this sc in b.scStates until sc's state becomes Shutdown. - // The entry will be deleted in HandleSubConnStateChange. - } - } - - return backendsUpdated -} - -func (lb *lbBalancer) readServerList(s *balanceLoadClientStream) error { - for { - reply, err := s.Recv() - if err != nil { - return fmt.Errorf("grpclb: failed to recv server list: %v", err) - } - if serverList := reply.GetServerList(); serverList != nil { - lb.processServerList(serverList) - } - } -} - -func (lb *lbBalancer) sendLoadReport(s *balanceLoadClientStream, interval time.Duration) { - ticker := time.NewTicker(interval) - defer ticker.Stop() - for { - select { - case <-ticker.C: - case <-s.Context().Done(): - return - } - stats := lb.clientStats.toClientStats() - t := time.Now() - stats.Timestamp = &lbpb.Timestamp{ - Seconds: t.Unix(), - Nanos: int32(t.Nanosecond()), - } - if err := s.Send(&lbpb.LoadBalanceRequest{ - LoadBalanceRequestType: &lbpb.LoadBalanceRequest_ClientStats{ - ClientStats: stats, - }, - }); err != nil { - return - } - } -} - -func (lb *lbBalancer) callRemoteBalancer() error { - lbClient := &loadBalancerClient{cc: lb.ccRemoteLB} - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - stream, err := lbClient.BalanceLoad(ctx, FailFast(false)) - if err != nil { - return fmt.Errorf("grpclb: failed to perform RPC to the remote balancer %v", err) - } - - // grpclb handshake on the stream. - initReq := &lbpb.LoadBalanceRequest{ - LoadBalanceRequestType: &lbpb.LoadBalanceRequest_InitialRequest{ - InitialRequest: &lbpb.InitialLoadBalanceRequest{ - Name: lb.target, - }, - }, - } - if err := stream.Send(initReq); err != nil { - return fmt.Errorf("grpclb: failed to send init request: %v", err) - } - reply, err := stream.Recv() - if err != nil { - return fmt.Errorf("grpclb: failed to recv init response: %v", err) - } - initResp := reply.GetInitialResponse() - if initResp == nil { - return fmt.Errorf("grpclb: reply from remote balancer did not include initial response") - } - if initResp.LoadBalancerDelegate != "" { - return fmt.Errorf("grpclb: Delegation is not supported") - } - - go func() { - if d := convertDuration(initResp.ClientStatsReportInterval); d > 0 { - lb.sendLoadReport(stream, d) - } - }() - return lb.readServerList(stream) -} - -func (lb *lbBalancer) watchRemoteBalancer() { - for { - err := lb.callRemoteBalancer() - select { - case <-lb.doneCh: - return - default: - if err != nil { - grpclog.Error(err) - } - } - - } -} - -func (lb *lbBalancer) dialRemoteLB(remoteLBName string) { - var dopts []DialOption - if creds := lb.opt.DialCreds; creds != nil { - if err := creds.OverrideServerName(remoteLBName); err == nil { - dopts = append(dopts, WithTransportCredentials(creds)) - } else { - grpclog.Warningf("grpclb: failed to override the server name in the credentials: %v, using Insecure", err) - dopts = append(dopts, WithInsecure()) - } - } else { - dopts = append(dopts, WithInsecure()) - } - if lb.opt.Dialer != nil { - // WithDialer takes a different type of function, so we instead use a - // special DialOption here. - dopts = append(dopts, withContextDialer(lb.opt.Dialer)) - } - // Explicitly set pickfirst as the balancer. - dopts = append(dopts, WithBalancerName(PickFirstBalancerName)) - dopts = append(dopts, withResolverBuilder(lb.manualResolver)) - if channelz.IsOn() { - dopts = append(dopts, WithChannelzParentID(lb.opt.ChannelzParentID)) - } - - // DialContext using manualResolver.Scheme, which is a random scheme generated - // when init grpclb. The target name is not important. - cc, err := DialContext(context.Background(), "grpclb:///grpclb.server", dopts...) - if err != nil { - grpclog.Fatalf("failed to dial: %v", err) - } - lb.ccRemoteLB = cc - go lb.watchRemoteBalancer() -} diff --git a/vendor/google.golang.org/grpc/grpclb_util.go b/vendor/google.golang.org/grpc/grpclb_util.go deleted file mode 100644 index 063ba9d8590..00000000000 --- a/vendor/google.golang.org/grpc/grpclb_util.go +++ /dev/null @@ -1,214 +0,0 @@ -/* - * - * Copyright 2016 gRPC 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 grpc - -import ( - "fmt" - "sync" - "time" - - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/resolver" -) - -// The parent ClientConn should re-resolve when grpclb loses connection to the -// remote balancer. When the ClientConn inside grpclb gets a TransientFailure, -// it calls lbManualResolver.ResolveNow(), which calls parent ClientConn's -// ResolveNow, and eventually results in re-resolve happening in parent -// ClientConn's resolver (DNS for example). -// -// parent -// ClientConn -// +-----------------------------------------------------------------+ -// | parent +---------------------------------+ | -// | DNS ClientConn | grpclb | | -// | resolver balancerWrapper | | | -// | + + | grpclb grpclb | | -// | | | | ManualResolver ClientConn | | -// | | | | + + | | -// | | | | | | Transient | | -// | | | | | | Failure | | -// | | | | | <--------- | | | -// | | | <--------------- | ResolveNow | | | -// | | <--------- | ResolveNow | | | | | -// | | ResolveNow | | | | | | -// | | | | | | | | -// | + + | + + | | -// | +---------------------------------+ | -// +-----------------------------------------------------------------+ - -// lbManualResolver is used by the ClientConn inside grpclb. It's a manual -// resolver with a special ResolveNow() function. -// -// When ResolveNow() is called, it calls ResolveNow() on the parent ClientConn, -// so when grpclb client lose contact with remote balancers, the parent -// ClientConn's resolver will re-resolve. -type lbManualResolver struct { - scheme string - ccr resolver.ClientConn - - ccb balancer.ClientConn -} - -func (r *lbManualResolver) Build(_ resolver.Target, cc resolver.ClientConn, _ resolver.BuildOption) (resolver.Resolver, error) { - r.ccr = cc - return r, nil -} - -func (r *lbManualResolver) Scheme() string { - return r.scheme -} - -// ResolveNow calls resolveNow on the parent ClientConn. -func (r *lbManualResolver) ResolveNow(o resolver.ResolveNowOption) { - r.ccb.ResolveNow(o) -} - -// Close is a noop for Resolver. -func (*lbManualResolver) Close() {} - -// NewAddress calls cc.NewAddress. -func (r *lbManualResolver) NewAddress(addrs []resolver.Address) { - r.ccr.NewAddress(addrs) -} - -// NewServiceConfig calls cc.NewServiceConfig. -func (r *lbManualResolver) NewServiceConfig(sc string) { - r.ccr.NewServiceConfig(sc) -} - -const subConnCacheTime = time.Second * 10 - -// lbCacheClientConn is a wrapper balancer.ClientConn with a SubConn cache. -// SubConns will be kept in cache for subConnCacheTime before being removed. -// -// Its new and remove methods are updated to do cache first. -type lbCacheClientConn struct { - cc balancer.ClientConn - timeout time.Duration - - mu sync.Mutex - // subConnCache only keeps subConns that are being deleted. - subConnCache map[resolver.Address]*subConnCacheEntry - subConnToAddr map[balancer.SubConn]resolver.Address -} - -type subConnCacheEntry struct { - sc balancer.SubConn - - cancel func() - abortDeleting bool -} - -func newLBCacheClientConn(cc balancer.ClientConn) *lbCacheClientConn { - return &lbCacheClientConn{ - cc: cc, - timeout: subConnCacheTime, - subConnCache: make(map[resolver.Address]*subConnCacheEntry), - subConnToAddr: make(map[balancer.SubConn]resolver.Address), - } -} - -func (ccc *lbCacheClientConn) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) { - if len(addrs) != 1 { - return nil, fmt.Errorf("grpclb calling NewSubConn with addrs of length %v", len(addrs)) - } - addrWithoutMD := addrs[0] - addrWithoutMD.Metadata = nil - - ccc.mu.Lock() - defer ccc.mu.Unlock() - if entry, ok := ccc.subConnCache[addrWithoutMD]; ok { - // If entry is in subConnCache, the SubConn was being deleted. - // cancel function will never be nil. - entry.cancel() - delete(ccc.subConnCache, addrWithoutMD) - return entry.sc, nil - } - - scNew, err := ccc.cc.NewSubConn(addrs, opts) - if err != nil { - return nil, err - } - - ccc.subConnToAddr[scNew] = addrWithoutMD - return scNew, nil -} - -func (ccc *lbCacheClientConn) RemoveSubConn(sc balancer.SubConn) { - ccc.mu.Lock() - defer ccc.mu.Unlock() - addr, ok := ccc.subConnToAddr[sc] - if !ok { - return - } - - if entry, ok := ccc.subConnCache[addr]; ok { - if entry.sc != sc { - // This could happen if NewSubConn was called multiple times for the - // same address, and those SubConns are all removed. We remove sc - // immediately here. - delete(ccc.subConnToAddr, sc) - ccc.cc.RemoveSubConn(sc) - } - return - } - - entry := &subConnCacheEntry{ - sc: sc, - } - ccc.subConnCache[addr] = entry - - timer := time.AfterFunc(ccc.timeout, func() { - ccc.mu.Lock() - if entry.abortDeleting { - return - } - ccc.cc.RemoveSubConn(sc) - delete(ccc.subConnToAddr, sc) - delete(ccc.subConnCache, addr) - ccc.mu.Unlock() - }) - entry.cancel = func() { - if !timer.Stop() { - // If stop was not successful, the timer has fired (this can only - // happen in a race). But the deleting function is blocked on ccc.mu - // because the mutex was held by the caller of this function. - // - // Set abortDeleting to true to abort the deleting function. When - // the lock is released, the deleting function will acquire the - // lock, check the value of abortDeleting and return. - entry.abortDeleting = true - } - } -} - -func (ccc *lbCacheClientConn) UpdateBalancerState(s connectivity.State, p balancer.Picker) { - ccc.cc.UpdateBalancerState(s, p) -} - -func (ccc *lbCacheClientConn) close() { - ccc.mu.Lock() - // Only cancel all existing timers. There's no need to remove SubConns. - for _, entry := range ccc.subConnCache { - entry.cancel() - } - ccc.mu.Unlock() -} diff --git a/vendor/google.golang.org/grpc/grpclog/grpclog.go b/vendor/google.golang.org/grpc/grpclog/grpclog.go deleted file mode 100644 index 1fabb11e1ba..00000000000 --- a/vendor/google.golang.org/grpc/grpclog/grpclog.go +++ /dev/null @@ -1,126 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 grpclog defines logging for grpc. -// -// All logs in transport package only go to verbose level 2. -// All logs in other packages in grpc are logged in spite of the verbosity level. -// -// In the default logger, -// severity level can be set by environment variable GRPC_GO_LOG_SEVERITY_LEVEL, -// verbosity level can be set by GRPC_GO_LOG_VERBOSITY_LEVEL. -package grpclog // import "google.golang.org/grpc/grpclog" - -import "os" - -var logger = newLoggerV2() - -// V reports whether verbosity level l is at least the requested verbose level. -func V(l int) bool { - return logger.V(l) -} - -// Info logs to the INFO log. -func Info(args ...interface{}) { - logger.Info(args...) -} - -// Infof logs to the INFO log. Arguments are handled in the manner of fmt.Printf. -func Infof(format string, args ...interface{}) { - logger.Infof(format, args...) -} - -// Infoln logs to the INFO log. Arguments are handled in the manner of fmt.Println. -func Infoln(args ...interface{}) { - logger.Infoln(args...) -} - -// Warning logs to the WARNING log. -func Warning(args ...interface{}) { - logger.Warning(args...) -} - -// Warningf logs to the WARNING log. Arguments are handled in the manner of fmt.Printf. -func Warningf(format string, args ...interface{}) { - logger.Warningf(format, args...) -} - -// Warningln logs to the WARNING log. Arguments are handled in the manner of fmt.Println. -func Warningln(args ...interface{}) { - logger.Warningln(args...) -} - -// Error logs to the ERROR log. -func Error(args ...interface{}) { - logger.Error(args...) -} - -// Errorf logs to the ERROR log. Arguments are handled in the manner of fmt.Printf. -func Errorf(format string, args ...interface{}) { - logger.Errorf(format, args...) -} - -// Errorln logs to the ERROR log. Arguments are handled in the manner of fmt.Println. -func Errorln(args ...interface{}) { - logger.Errorln(args...) -} - -// Fatal logs to the FATAL log. Arguments are handled in the manner of fmt.Print. -// It calls os.Exit() with exit code 1. -func Fatal(args ...interface{}) { - logger.Fatal(args...) - // Make sure fatal logs will exit. - os.Exit(1) -} - -// Fatalf logs to the FATAL log. Arguments are handled in the manner of fmt.Printf. -// It calles os.Exit() with exit code 1. -func Fatalf(format string, args ...interface{}) { - logger.Fatalf(format, args...) - // Make sure fatal logs will exit. - os.Exit(1) -} - -// Fatalln logs to the FATAL log. Arguments are handled in the manner of fmt.Println. -// It calle os.Exit()) with exit code 1. -func Fatalln(args ...interface{}) { - logger.Fatalln(args...) - // Make sure fatal logs will exit. - os.Exit(1) -} - -// Print prints to the logger. Arguments are handled in the manner of fmt.Print. -// -// Deprecated: use Info. -func Print(args ...interface{}) { - logger.Info(args...) -} - -// Printf prints to the logger. Arguments are handled in the manner of fmt.Printf. -// -// Deprecated: use Infof. -func Printf(format string, args ...interface{}) { - logger.Infof(format, args...) -} - -// Println prints to the logger. Arguments are handled in the manner of fmt.Println. -// -// Deprecated: use Infoln. -func Println(args ...interface{}) { - logger.Infoln(args...) -} diff --git a/vendor/google.golang.org/grpc/grpclog/logger.go b/vendor/google.golang.org/grpc/grpclog/logger.go deleted file mode 100644 index 097494f710f..00000000000 --- a/vendor/google.golang.org/grpc/grpclog/logger.go +++ /dev/null @@ -1,85 +0,0 @@ -/* - * - * Copyright 2015 gRPC 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 grpclog - -// Logger mimics golang's standard Logger as an interface. -// -// Deprecated: use LoggerV2. -type Logger interface { - Fatal(args ...interface{}) - Fatalf(format string, args ...interface{}) - Fatalln(args ...interface{}) - Print(args ...interface{}) - Printf(format string, args ...interface{}) - Println(args ...interface{}) -} - -// SetLogger sets the logger that is used in grpc. Call only from -// init() functions. -// -// Deprecated: use SetLoggerV2. -func SetLogger(l Logger) { - logger = &loggerWrapper{Logger: l} -} - -// loggerWrapper wraps Logger into a LoggerV2. -type loggerWrapper struct { - Logger -} - -func (g *loggerWrapper) Info(args ...interface{}) { - g.Logger.Print(args...) -} - -func (g *loggerWrapper) Infoln(args ...interface{}) { - g.Logger.Println(args...) -} - -func (g *loggerWrapper) Infof(format string, args ...interface{}) { - g.Logger.Printf(format, args...) -} - -func (g *loggerWrapper) Warning(args ...interface{}) { - g.Logger.Print(args...) -} - -func (g *loggerWrapper) Warningln(args ...interface{}) { - g.Logger.Println(args...) -} - -func (g *loggerWrapper) Warningf(format string, args ...interface{}) { - g.Logger.Printf(format, args...) -} - -func (g *loggerWrapper) Error(args ...interface{}) { - g.Logger.Print(args...) -} - -func (g *loggerWrapper) Errorln(args ...interface{}) { - g.Logger.Println(args...) -} - -func (g *loggerWrapper) Errorf(format string, args ...interface{}) { - g.Logger.Printf(format, args...) -} - -func (g *loggerWrapper) V(l int) bool { - // Returns true for all verbose level. - return true -} diff --git a/vendor/google.golang.org/grpc/grpclog/loggerv2.go b/vendor/google.golang.org/grpc/grpclog/loggerv2.go deleted file mode 100644 index d4932577695..00000000000 --- a/vendor/google.golang.org/grpc/grpclog/loggerv2.go +++ /dev/null @@ -1,195 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 grpclog - -import ( - "io" - "io/ioutil" - "log" - "os" - "strconv" -) - -// LoggerV2 does underlying logging work for grpclog. -type LoggerV2 interface { - // Info logs to INFO log. Arguments are handled in the manner of fmt.Print. - Info(args ...interface{}) - // Infoln logs to INFO log. Arguments are handled in the manner of fmt.Println. - Infoln(args ...interface{}) - // Infof logs to INFO log. Arguments are handled in the manner of fmt.Printf. - Infof(format string, args ...interface{}) - // Warning logs to WARNING log. Arguments are handled in the manner of fmt.Print. - Warning(args ...interface{}) - // Warningln logs to WARNING log. Arguments are handled in the manner of fmt.Println. - Warningln(args ...interface{}) - // Warningf logs to WARNING log. Arguments are handled in the manner of fmt.Printf. - Warningf(format string, args ...interface{}) - // Error logs to ERROR log. Arguments are handled in the manner of fmt.Print. - Error(args ...interface{}) - // Errorln logs to ERROR log. Arguments are handled in the manner of fmt.Println. - Errorln(args ...interface{}) - // Errorf logs to ERROR log. Arguments are handled in the manner of fmt.Printf. - Errorf(format string, args ...interface{}) - // Fatal logs to ERROR log. Arguments are handled in the manner of fmt.Print. - // gRPC ensures that all Fatal logs will exit with os.Exit(1). - // Implementations may also call os.Exit() with a non-zero exit code. - Fatal(args ...interface{}) - // Fatalln logs to ERROR log. Arguments are handled in the manner of fmt.Println. - // gRPC ensures that all Fatal logs will exit with os.Exit(1). - // Implementations may also call os.Exit() with a non-zero exit code. - Fatalln(args ...interface{}) - // Fatalf logs to ERROR log. Arguments are handled in the manner of fmt.Printf. - // gRPC ensures that all Fatal logs will exit with os.Exit(1). - // Implementations may also call os.Exit() with a non-zero exit code. - Fatalf(format string, args ...interface{}) - // V reports whether verbosity level l is at least the requested verbose level. - V(l int) bool -} - -// SetLoggerV2 sets logger that is used in grpc to a V2 logger. -// Not mutex-protected, should be called before any gRPC functions. -func SetLoggerV2(l LoggerV2) { - logger = l -} - -const ( - // infoLog indicates Info severity. - infoLog int = iota - // warningLog indicates Warning severity. - warningLog - // errorLog indicates Error severity. - errorLog - // fatalLog indicates Fatal severity. - fatalLog -) - -// severityName contains the string representation of each severity. -var severityName = []string{ - infoLog: "INFO", - warningLog: "WARNING", - errorLog: "ERROR", - fatalLog: "FATAL", -} - -// loggerT is the default logger used by grpclog. -type loggerT struct { - m []*log.Logger - v int -} - -// NewLoggerV2 creates a loggerV2 with the provided writers. -// Fatal logs will be written to errorW, warningW, infoW, followed by exit(1). -// Error logs will be written to errorW, warningW and infoW. -// Warning logs will be written to warningW and infoW. -// Info logs will be written to infoW. -func NewLoggerV2(infoW, warningW, errorW io.Writer) LoggerV2 { - return NewLoggerV2WithVerbosity(infoW, warningW, errorW, 0) -} - -// NewLoggerV2WithVerbosity creates a loggerV2 with the provided writers and -// verbosity level. -func NewLoggerV2WithVerbosity(infoW, warningW, errorW io.Writer, v int) LoggerV2 { - var m []*log.Logger - m = append(m, log.New(infoW, severityName[infoLog]+": ", log.LstdFlags)) - m = append(m, log.New(io.MultiWriter(infoW, warningW), severityName[warningLog]+": ", log.LstdFlags)) - ew := io.MultiWriter(infoW, warningW, errorW) // ew will be used for error and fatal. - m = append(m, log.New(ew, severityName[errorLog]+": ", log.LstdFlags)) - m = append(m, log.New(ew, severityName[fatalLog]+": ", log.LstdFlags)) - return &loggerT{m: m, v: v} -} - -// newLoggerV2 creates a loggerV2 to be used as default logger. -// All logs are written to stderr. -func newLoggerV2() LoggerV2 { - errorW := ioutil.Discard - warningW := ioutil.Discard - infoW := ioutil.Discard - - logLevel := os.Getenv("GRPC_GO_LOG_SEVERITY_LEVEL") - switch logLevel { - case "", "ERROR", "error": // If env is unset, set level to ERROR. - errorW = os.Stderr - case "WARNING", "warning": - warningW = os.Stderr - case "INFO", "info": - infoW = os.Stderr - } - - var v int - vLevel := os.Getenv("GRPC_GO_LOG_VERBOSITY_LEVEL") - if vl, err := strconv.Atoi(vLevel); err == nil { - v = vl - } - return NewLoggerV2WithVerbosity(infoW, warningW, errorW, v) -} - -func (g *loggerT) Info(args ...interface{}) { - g.m[infoLog].Print(args...) -} - -func (g *loggerT) Infoln(args ...interface{}) { - g.m[infoLog].Println(args...) -} - -func (g *loggerT) Infof(format string, args ...interface{}) { - g.m[infoLog].Printf(format, args...) -} - -func (g *loggerT) Warning(args ...interface{}) { - g.m[warningLog].Print(args...) -} - -func (g *loggerT) Warningln(args ...interface{}) { - g.m[warningLog].Println(args...) -} - -func (g *loggerT) Warningf(format string, args ...interface{}) { - g.m[warningLog].Printf(format, args...) -} - -func (g *loggerT) Error(args ...interface{}) { - g.m[errorLog].Print(args...) -} - -func (g *loggerT) Errorln(args ...interface{}) { - g.m[errorLog].Println(args...) -} - -func (g *loggerT) Errorf(format string, args ...interface{}) { - g.m[errorLog].Printf(format, args...) -} - -func (g *loggerT) Fatal(args ...interface{}) { - g.m[fatalLog].Fatal(args...) - // No need to call os.Exit() again because log.Logger.Fatal() calls os.Exit(). -} - -func (g *loggerT) Fatalln(args ...interface{}) { - g.m[fatalLog].Fatalln(args...) - // No need to call os.Exit() again because log.Logger.Fatal() calls os.Exit(). -} - -func (g *loggerT) Fatalf(format string, args ...interface{}) { - g.m[fatalLog].Fatalf(format, args...) - // No need to call os.Exit() again because log.Logger.Fatal() calls os.Exit(). -} - -func (g *loggerT) V(l int) bool { - return l <= g.v -} diff --git a/vendor/google.golang.org/grpc/interceptor.go b/vendor/google.golang.org/grpc/interceptor.go deleted file mode 100644 index 1f6ef678035..00000000000 --- a/vendor/google.golang.org/grpc/interceptor.go +++ /dev/null @@ -1,77 +0,0 @@ -/* - * - * Copyright 2016 gRPC 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 grpc - -import ( - "golang.org/x/net/context" -) - -// UnaryInvoker is called by UnaryClientInterceptor to complete RPCs. -type UnaryInvoker func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, opts ...CallOption) error - -// UnaryClientInterceptor intercepts the execution of a unary RPC on the client. invoker is the handler to complete the RPC -// and it is the responsibility of the interceptor to call it. -// This is an EXPERIMENTAL API. -type UnaryClientInterceptor func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error - -// Streamer is called by StreamClientInterceptor to create a ClientStream. -type Streamer func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error) - -// StreamClientInterceptor intercepts the creation of ClientStream. It may return a custom ClientStream to intercept all I/O -// operations. streamer is the handler to create a ClientStream and it is the responsibility of the interceptor to call it. -// This is an EXPERIMENTAL API. -type StreamClientInterceptor func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, streamer Streamer, opts ...CallOption) (ClientStream, error) - -// UnaryServerInfo consists of various information about a unary RPC on -// server side. All per-rpc information may be mutated by the interceptor. -type UnaryServerInfo struct { - // Server is the service implementation the user provides. This is read-only. - Server interface{} - // FullMethod is the full RPC method string, i.e., /package.service/method. - FullMethod string -} - -// UnaryHandler defines the handler invoked by UnaryServerInterceptor to complete the normal -// execution of a unary RPC. If a UnaryHandler returns an error, it should be produced by the -// status package, or else gRPC will use codes.Unknown as the status code and err.Error() as -// the status message of the RPC. -type UnaryHandler func(ctx context.Context, req interface{}) (interface{}, error) - -// UnaryServerInterceptor provides a hook to intercept the execution of a unary RPC on the server. info -// contains all the information of this RPC the interceptor can operate on. And handler is the wrapper -// of the service method implementation. It is the responsibility of the interceptor to invoke handler -// to complete the RPC. -type UnaryServerInterceptor func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (resp interface{}, err error) - -// StreamServerInfo consists of various information about a streaming RPC on -// server side. All per-rpc information may be mutated by the interceptor. -type StreamServerInfo struct { - // FullMethod is the full RPC method string, i.e., /package.service/method. - FullMethod string - // IsClientStream indicates whether the RPC is a client streaming RPC. - IsClientStream bool - // IsServerStream indicates whether the RPC is a server streaming RPC. - IsServerStream bool -} - -// StreamServerInterceptor provides a hook to intercept the execution of a streaming RPC on the server. -// info contains all the information of this RPC the interceptor can operate on. And handler is the -// service method implementation. It is the responsibility of the interceptor to invoke handler to -// complete the RPC. -type StreamServerInterceptor func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error diff --git a/vendor/google.golang.org/grpc/internal/internal.go b/vendor/google.golang.org/grpc/internal/internal.go deleted file mode 100644 index 53f1775201c..00000000000 --- a/vendor/google.golang.org/grpc/internal/internal.go +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2016 gRPC 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 internal contains gRPC-internal code for testing, to avoid polluting -// the godoc of the top-level grpc package. -package internal - -// TestingUseHandlerImpl enables the http.Handler-based server implementation. -// It must be called before Serve and requires TLS credentials. -// -// The provided grpcServer must be of type *grpc.Server. It is untyped -// for circular dependency reasons. -var TestingUseHandlerImpl func(grpcServer interface{}) diff --git a/vendor/google.golang.org/grpc/keepalive/keepalive.go b/vendor/google.golang.org/grpc/keepalive/keepalive.go deleted file mode 100644 index f8adc7e6d4f..00000000000 --- a/vendor/google.golang.org/grpc/keepalive/keepalive.go +++ /dev/null @@ -1,65 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 keepalive defines configurable parameters for point-to-point healthcheck. -package keepalive - -import ( - "time" -) - -// ClientParameters is used to set keepalive parameters on the client-side. -// These configure how the client will actively probe to notice when a connection is broken -// and send pings so intermediaries will be aware of the liveness of the connection. -// Make sure these parameters are set in coordination with the keepalive policy on the server, -// as incompatible settings can result in closing of connection. -type ClientParameters struct { - // After a duration of this time if the client doesn't see any activity it pings the server to see if the transport is still alive. - Time time.Duration // The current default value is infinity. - // After having pinged for keepalive check, the client waits for a duration of Timeout and if no activity is seen even after that - // the connection is closed. - Timeout time.Duration // The current default value is 20 seconds. - // If true, client runs keepalive checks even with no active RPCs. - PermitWithoutStream bool // false by default. -} - -// ServerParameters is used to set keepalive and max-age parameters on the server-side. -type ServerParameters struct { - // MaxConnectionIdle is a duration for the amount of time after which an idle connection would be closed by sending a GoAway. - // Idleness duration is defined since the most recent time the number of outstanding RPCs became zero or the connection establishment. - MaxConnectionIdle time.Duration // The current default value is infinity. - // MaxConnectionAge is a duration for the maximum amount of time a connection may exist before it will be closed by sending a GoAway. - // A random jitter of +/-10% will be added to MaxConnectionAge to spread out connection storms. - MaxConnectionAge time.Duration // The current default value is infinity. - // MaxConnectinoAgeGrace is an additive period after MaxConnectionAge after which the connection will be forcibly closed. - MaxConnectionAgeGrace time.Duration // The current default value is infinity. - // After a duration of this time if the server doesn't see any activity it pings the client to see if the transport is still alive. - Time time.Duration // The current default value is 2 hours. - // After having pinged for keepalive check, the server waits for a duration of Timeout and if no activity is seen even after that - // the connection is closed. - Timeout time.Duration // The current default value is 20 seconds. -} - -// EnforcementPolicy is used to set keepalive enforcement policy on the server-side. -// Server will close connection with a client that violates this policy. -type EnforcementPolicy struct { - // MinTime is the minimum amount of time a client should wait before sending a keepalive ping. - MinTime time.Duration // The current default value is 5 minutes. - // If true, server expects keepalive pings even when there are no active streams(RPCs). - PermitWithoutStream bool // false by default. -} diff --git a/vendor/google.golang.org/grpc/metadata/metadata.go b/vendor/google.golang.org/grpc/metadata/metadata.go deleted file mode 100644 index bd2eaf40837..00000000000 --- a/vendor/google.golang.org/grpc/metadata/metadata.go +++ /dev/null @@ -1,210 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 metadata define the structure of the metadata supported by gRPC library. -// Please refer to https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md -// for more information about custom-metadata. -package metadata // import "google.golang.org/grpc/metadata" - -import ( - "fmt" - "strings" - - "golang.org/x/net/context" -) - -// DecodeKeyValue returns k, v, nil. -// -// Deprecated: use k and v directly instead. -func DecodeKeyValue(k, v string) (string, string, error) { - return k, v, nil -} - -// MD is a mapping from metadata keys to values. Users should use the following -// two convenience functions New and Pairs to generate MD. -type MD map[string][]string - -// New creates an MD from a given key-value map. -// -// Only the following ASCII characters are allowed in keys: -// - digits: 0-9 -// - uppercase letters: A-Z (normalized to lower) -// - lowercase letters: a-z -// - special characters: -_. -// Uppercase letters are automatically converted to lowercase. -// -// Keys beginning with "grpc-" are reserved for grpc-internal use only and may -// result in errors if set in metadata. -func New(m map[string]string) MD { - md := MD{} - for k, val := range m { - key := strings.ToLower(k) - md[key] = append(md[key], val) - } - return md -} - -// Pairs returns an MD formed by the mapping of key, value ... -// Pairs panics if len(kv) is odd. -// -// Only the following ASCII characters are allowed in keys: -// - digits: 0-9 -// - uppercase letters: A-Z (normalized to lower) -// - lowercase letters: a-z -// - special characters: -_. -// Uppercase letters are automatically converted to lowercase. -// -// Keys beginning with "grpc-" are reserved for grpc-internal use only and may -// result in errors if set in metadata. -func Pairs(kv ...string) MD { - if len(kv)%2 == 1 { - panic(fmt.Sprintf("metadata: Pairs got the odd number of input pairs for metadata: %d", len(kv))) - } - md := MD{} - var key string - for i, s := range kv { - if i%2 == 0 { - key = strings.ToLower(s) - continue - } - md[key] = append(md[key], s) - } - return md -} - -// Len returns the number of items in md. -func (md MD) Len() int { - return len(md) -} - -// Copy returns a copy of md. -func (md MD) Copy() MD { - return Join(md) -} - -// Get obtains the values for a given key. -func (md MD) Get(k string) []string { - k = strings.ToLower(k) - return md[k] -} - -// Set sets the value of a given key with a slice of values. -func (md MD) Set(k string, vals ...string) { - if len(vals) == 0 { - return - } - k = strings.ToLower(k) - md[k] = vals -} - -// Append adds the values to key k, not overwriting what was already stored at that key. -func (md MD) Append(k string, vals ...string) { - if len(vals) == 0 { - return - } - k = strings.ToLower(k) - md[k] = append(md[k], vals...) -} - -// Join joins any number of mds into a single MD. -// The order of values for each key is determined by the order in which -// the mds containing those values are presented to Join. -func Join(mds ...MD) MD { - out := MD{} - for _, md := range mds { - for k, v := range md { - out[k] = append(out[k], v...) - } - } - return out -} - -type mdIncomingKey struct{} -type mdOutgoingKey struct{} - -// NewIncomingContext creates a new context with incoming md attached. -func NewIncomingContext(ctx context.Context, md MD) context.Context { - return context.WithValue(ctx, mdIncomingKey{}, md) -} - -// NewOutgoingContext creates a new context with outgoing md attached. If used -// in conjunction with AppendToOutgoingContext, NewOutgoingContext will -// overwrite any previously-appended metadata. -func NewOutgoingContext(ctx context.Context, md MD) context.Context { - return context.WithValue(ctx, mdOutgoingKey{}, rawMD{md: md}) -} - -// AppendToOutgoingContext returns a new context with the provided kv merged -// with any existing metadata in the context. Please refer to the -// documentation of Pairs for a description of kv. -func AppendToOutgoingContext(ctx context.Context, kv ...string) context.Context { - if len(kv)%2 == 1 { - panic(fmt.Sprintf("metadata: AppendToOutgoingContext got an odd number of input pairs for metadata: %d", len(kv))) - } - md, _ := ctx.Value(mdOutgoingKey{}).(rawMD) - added := make([][]string, len(md.added)+1) - copy(added, md.added) - added[len(added)-1] = make([]string, len(kv)) - copy(added[len(added)-1], kv) - return context.WithValue(ctx, mdOutgoingKey{}, rawMD{md: md.md, added: added}) -} - -// FromIncomingContext returns the incoming metadata in ctx if it exists. The -// returned MD should not be modified. Writing to it may cause races. -// Modification should be made to copies of the returned MD. -func FromIncomingContext(ctx context.Context) (md MD, ok bool) { - md, ok = ctx.Value(mdIncomingKey{}).(MD) - return -} - -// FromOutgoingContextRaw returns the un-merged, intermediary contents -// of rawMD. Remember to perform strings.ToLower on the keys. The returned -// MD should not be modified. Writing to it may cause races. Modification -// should be made to copies of the returned MD. -// -// This is intended for gRPC-internal use ONLY. -func FromOutgoingContextRaw(ctx context.Context) (MD, [][]string, bool) { - raw, ok := ctx.Value(mdOutgoingKey{}).(rawMD) - if !ok { - return nil, nil, false - } - - return raw.md, raw.added, true -} - -// FromOutgoingContext returns the outgoing metadata in ctx if it exists. The -// returned MD should not be modified. Writing to it may cause races. -// Modification should be made to copies of the returned MD. -func FromOutgoingContext(ctx context.Context) (MD, bool) { - raw, ok := ctx.Value(mdOutgoingKey{}).(rawMD) - if !ok { - return nil, false - } - - mds := make([]MD, 0, len(raw.added)+1) - mds = append(mds, raw.md) - for _, vv := range raw.added { - mds = append(mds, Pairs(vv...)) - } - return Join(mds...), ok -} - -type rawMD struct { - md MD - added [][]string -} diff --git a/vendor/google.golang.org/grpc/naming/dns_resolver.go b/vendor/google.golang.org/grpc/naming/dns_resolver.go deleted file mode 100644 index 0f8a908ea9c..00000000000 --- a/vendor/google.golang.org/grpc/naming/dns_resolver.go +++ /dev/null @@ -1,290 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 naming - -import ( - "errors" - "fmt" - "net" - "strconv" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/grpclog" -) - -const ( - defaultPort = "443" - defaultFreq = time.Minute * 30 -) - -var ( - errMissingAddr = errors.New("missing address") - errWatcherClose = errors.New("watcher has been closed") -) - -// NewDNSResolverWithFreq creates a DNS Resolver that can resolve DNS names, and -// create watchers that poll the DNS server using the frequency set by freq. -func NewDNSResolverWithFreq(freq time.Duration) (Resolver, error) { - return &dnsResolver{freq: freq}, nil -} - -// NewDNSResolver creates a DNS Resolver that can resolve DNS names, and create -// watchers that poll the DNS server using the default frequency defined by defaultFreq. -func NewDNSResolver() (Resolver, error) { - return NewDNSResolverWithFreq(defaultFreq) -} - -// dnsResolver handles name resolution for names following the DNS scheme -type dnsResolver struct { - // frequency of polling the DNS server that the watchers created by this resolver will use. - freq time.Duration -} - -// formatIP returns ok = false if addr is not a valid textual representation of an IP address. -// If addr is an IPv4 address, return the addr and ok = true. -// If addr is an IPv6 address, return the addr enclosed in square brackets and ok = true. -func formatIP(addr string) (addrIP string, ok bool) { - ip := net.ParseIP(addr) - if ip == nil { - return "", false - } - if ip.To4() != nil { - return addr, true - } - return "[" + addr + "]", true -} - -// parseTarget takes the user input target string, returns formatted host and port info. -// If target doesn't specify a port, set the port to be the defaultPort. -// If target is in IPv6 format and host-name is enclosed in sqarue brackets, brackets -// are strippd when setting the host. -// examples: -// target: "www.google.com" returns host: "www.google.com", port: "443" -// target: "ipv4-host:80" returns host: "ipv4-host", port: "80" -// target: "[ipv6-host]" returns host: "ipv6-host", port: "443" -// target: ":80" returns host: "localhost", port: "80" -// target: ":" returns host: "localhost", port: "443" -func parseTarget(target string) (host, port string, err error) { - if target == "" { - return "", "", errMissingAddr - } - - if ip := net.ParseIP(target); ip != nil { - // target is an IPv4 or IPv6(without brackets) address - return target, defaultPort, nil - } - if host, port, err := net.SplitHostPort(target); err == nil { - // target has port, i.e ipv4-host:port, [ipv6-host]:port, host-name:port - if host == "" { - // Keep consistent with net.Dial(): If the host is empty, as in ":80", the local system is assumed. - host = "localhost" - } - if port == "" { - // If the port field is empty(target ends with colon), e.g. "[::1]:", defaultPort is used. - port = defaultPort - } - return host, port, nil - } - if host, port, err := net.SplitHostPort(target + ":" + defaultPort); err == nil { - // target doesn't have port - return host, port, nil - } - return "", "", fmt.Errorf("invalid target address %v", target) -} - -// Resolve creates a watcher that watches the name resolution of the target. -func (r *dnsResolver) Resolve(target string) (Watcher, error) { - host, port, err := parseTarget(target) - if err != nil { - return nil, err - } - - if net.ParseIP(host) != nil { - ipWatcher := &ipWatcher{ - updateChan: make(chan *Update, 1), - } - host, _ = formatIP(host) - ipWatcher.updateChan <- &Update{Op: Add, Addr: host + ":" + port} - return ipWatcher, nil - } - - ctx, cancel := context.WithCancel(context.Background()) - return &dnsWatcher{ - r: r, - host: host, - port: port, - ctx: ctx, - cancel: cancel, - t: time.NewTimer(0), - }, nil -} - -// dnsWatcher watches for the name resolution update for a specific target -type dnsWatcher struct { - r *dnsResolver - host string - port string - // The latest resolved address set - curAddrs map[string]*Update - ctx context.Context - cancel context.CancelFunc - t *time.Timer -} - -// ipWatcher watches for the name resolution update for an IP address. -type ipWatcher struct { - updateChan chan *Update -} - -// Next returns the address resolution Update for the target. For IP address, -// the resolution is itself, thus polling name server is unnecessary. Therefore, -// Next() will return an Update the first time it is called, and will be blocked -// for all following calls as no Update exists until watcher is closed. -func (i *ipWatcher) Next() ([]*Update, error) { - u, ok := <-i.updateChan - if !ok { - return nil, errWatcherClose - } - return []*Update{u}, nil -} - -// Close closes the ipWatcher. -func (i *ipWatcher) Close() { - close(i.updateChan) -} - -// AddressType indicates the address type returned by name resolution. -type AddressType uint8 - -const ( - // Backend indicates the server is a backend server. - Backend AddressType = iota - // GRPCLB indicates the server is a grpclb load balancer. - GRPCLB -) - -// AddrMetadataGRPCLB contains the information the name resolver for grpclb should provide. The -// name resolver used by the grpclb balancer is required to provide this type of metadata in -// its address updates. -type AddrMetadataGRPCLB struct { - // AddrType is the type of server (grpc load balancer or backend). - AddrType AddressType - // ServerName is the name of the grpc load balancer. Used for authentication. - ServerName string -} - -// compileUpdate compares the old resolved addresses and newly resolved addresses, -// and generates an update list -func (w *dnsWatcher) compileUpdate(newAddrs map[string]*Update) []*Update { - var res []*Update - for a, u := range w.curAddrs { - if _, ok := newAddrs[a]; !ok { - u.Op = Delete - res = append(res, u) - } - } - for a, u := range newAddrs { - if _, ok := w.curAddrs[a]; !ok { - res = append(res, u) - } - } - return res -} - -func (w *dnsWatcher) lookupSRV() map[string]*Update { - newAddrs := make(map[string]*Update) - _, srvs, err := lookupSRV(w.ctx, "grpclb", "tcp", w.host) - if err != nil { - grpclog.Infof("grpc: failed dns SRV record lookup due to %v.\n", err) - return nil - } - for _, s := range srvs { - lbAddrs, err := lookupHost(w.ctx, s.Target) - if err != nil { - grpclog.Warningf("grpc: failed load banlacer address dns lookup due to %v.\n", err) - continue - } - for _, a := range lbAddrs { - a, ok := formatIP(a) - if !ok { - grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err) - continue - } - addr := a + ":" + strconv.Itoa(int(s.Port)) - newAddrs[addr] = &Update{Addr: addr, - Metadata: AddrMetadataGRPCLB{AddrType: GRPCLB, ServerName: s.Target}} - } - } - return newAddrs -} - -func (w *dnsWatcher) lookupHost() map[string]*Update { - newAddrs := make(map[string]*Update) - addrs, err := lookupHost(w.ctx, w.host) - if err != nil { - grpclog.Warningf("grpc: failed dns A record lookup due to %v.\n", err) - return nil - } - for _, a := range addrs { - a, ok := formatIP(a) - if !ok { - grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err) - continue - } - addr := a + ":" + w.port - newAddrs[addr] = &Update{Addr: addr} - } - return newAddrs -} - -func (w *dnsWatcher) lookup() []*Update { - newAddrs := w.lookupSRV() - if newAddrs == nil { - // If failed to get any balancer address (either no corresponding SRV for the - // target, or caused by failure during resolution/parsing of the balancer target), - // return any A record info available. - newAddrs = w.lookupHost() - } - result := w.compileUpdate(newAddrs) - w.curAddrs = newAddrs - return result -} - -// Next returns the resolved address update(delta) for the target. If there's no -// change, it will sleep for 30 mins and try to resolve again after that. -func (w *dnsWatcher) Next() ([]*Update, error) { - for { - select { - case <-w.ctx.Done(): - return nil, errWatcherClose - case <-w.t.C: - } - result := w.lookup() - // Next lookup should happen after an interval defined by w.r.freq. - w.t.Reset(w.r.freq) - if len(result) > 0 { - return result, nil - } - } -} - -func (w *dnsWatcher) Close() { - w.cancel() -} diff --git a/vendor/google.golang.org/grpc/naming/go17.go b/vendor/google.golang.org/grpc/naming/go17.go deleted file mode 100644 index 57b65d7b889..00000000000 --- a/vendor/google.golang.org/grpc/naming/go17.go +++ /dev/null @@ -1,34 +0,0 @@ -// +build go1.6,!go1.8 - -/* - * - * Copyright 2017 gRPC 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 naming - -import ( - "net" - - "golang.org/x/net/context" -) - -var ( - lookupHost = func(ctx context.Context, host string) ([]string, error) { return net.LookupHost(host) } - lookupSRV = func(ctx context.Context, service, proto, name string) (string, []*net.SRV, error) { - return net.LookupSRV(service, proto, name) - } -) diff --git a/vendor/google.golang.org/grpc/naming/go18.go b/vendor/google.golang.org/grpc/naming/go18.go deleted file mode 100644 index b5a0f842748..00000000000 --- a/vendor/google.golang.org/grpc/naming/go18.go +++ /dev/null @@ -1,28 +0,0 @@ -// +build go1.8 - -/* - * - * Copyright 2017 gRPC 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 naming - -import "net" - -var ( - lookupHost = net.DefaultResolver.LookupHost - lookupSRV = net.DefaultResolver.LookupSRV -) diff --git a/vendor/google.golang.org/grpc/naming/naming.go b/vendor/google.golang.org/grpc/naming/naming.go deleted file mode 100644 index 8cc39e93758..00000000000 --- a/vendor/google.golang.org/grpc/naming/naming.go +++ /dev/null @@ -1,69 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 naming defines the naming API and related data structures for gRPC. -// The interface is EXPERIMENTAL and may be suject to change. -// -// Deprecated: please use package resolver. -package naming - -// Operation defines the corresponding operations for a name resolution change. -// -// Deprecated: please use package resolver. -type Operation uint8 - -const ( - // Add indicates a new address is added. - Add Operation = iota - // Delete indicates an existing address is deleted. - Delete -) - -// Update defines a name resolution update. Notice that it is not valid having both -// empty string Addr and nil Metadata in an Update. -// -// Deprecated: please use package resolver. -type Update struct { - // Op indicates the operation of the update. - Op Operation - // Addr is the updated address. It is empty string if there is no address update. - Addr string - // Metadata is the updated metadata. It is nil if there is no metadata update. - // Metadata is not required for a custom naming implementation. - Metadata interface{} -} - -// Resolver creates a Watcher for a target to track its resolution changes. -// -// Deprecated: please use package resolver. -type Resolver interface { - // Resolve creates a Watcher for target. - Resolve(target string) (Watcher, error) -} - -// Watcher watches for the updates on the specified target. -// -// Deprecated: please use package resolver. -type Watcher interface { - // Next blocks until an update or error happens. It may return one or more - // updates. The first call should get the full set of the results. It should - // return an error if and only if Watcher cannot recover. - Next() ([]*Update, error) - // Close closes the Watcher. - Close() -} diff --git a/vendor/google.golang.org/grpc/peer/peer.go b/vendor/google.golang.org/grpc/peer/peer.go deleted file mode 100644 index 317b8b9d09a..00000000000 --- a/vendor/google.golang.org/grpc/peer/peer.go +++ /dev/null @@ -1,51 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 peer defines various peer information associated with RPCs and -// corresponding utils. -package peer - -import ( - "net" - - "golang.org/x/net/context" - "google.golang.org/grpc/credentials" -) - -// Peer contains the information of the peer for an RPC, such as the address -// and authentication information. -type Peer struct { - // Addr is the peer address. - Addr net.Addr - // AuthInfo is the authentication information of the transport. - // It is nil if there is no transport security being used. - AuthInfo credentials.AuthInfo -} - -type peerKey struct{} - -// NewContext creates a new context with peer information attached. -func NewContext(ctx context.Context, p *Peer) context.Context { - return context.WithValue(ctx, peerKey{}, p) -} - -// FromContext returns the peer information in ctx if it exists. -func FromContext(ctx context.Context) (p *Peer, ok bool) { - p, ok = ctx.Value(peerKey{}).(*Peer) - return -} diff --git a/vendor/google.golang.org/grpc/picker_wrapper.go b/vendor/google.golang.org/grpc/picker_wrapper.go deleted file mode 100644 index 0a984e6c8af..00000000000 --- a/vendor/google.golang.org/grpc/picker_wrapper.go +++ /dev/null @@ -1,331 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 grpc - -import ( - "io" - "sync" - "sync/atomic" - - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/channelz" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/resolver" - "google.golang.org/grpc/status" - "google.golang.org/grpc/transport" -) - -// pickerWrapper is a wrapper of balancer.Picker. It blocks on certain pick -// actions and unblock when there's a picker update. -type pickerWrapper struct { - mu sync.Mutex - done bool - blockingCh chan struct{} - picker balancer.Picker - - // The latest connection happened. - connErrMu sync.Mutex - connErr error - - stickinessMDKey atomic.Value - stickiness *stickyStore -} - -func newPickerWrapper() *pickerWrapper { - bp := &pickerWrapper{ - blockingCh: make(chan struct{}), - stickiness: newStickyStore(), - } - return bp -} - -func (bp *pickerWrapper) updateConnectionError(err error) { - bp.connErrMu.Lock() - bp.connErr = err - bp.connErrMu.Unlock() -} - -func (bp *pickerWrapper) connectionError() error { - bp.connErrMu.Lock() - err := bp.connErr - bp.connErrMu.Unlock() - return err -} - -func (bp *pickerWrapper) updateStickinessMDKey(newKey string) { - // No need to check ok because mdKey == "" if ok == false. - if oldKey, _ := bp.stickinessMDKey.Load().(string); oldKey != newKey { - bp.stickinessMDKey.Store(newKey) - bp.stickiness.reset(newKey) - } -} - -func (bp *pickerWrapper) getStickinessMDKey() string { - // No need to check ok because mdKey == "" if ok == false. - mdKey, _ := bp.stickinessMDKey.Load().(string) - return mdKey -} - -func (bp *pickerWrapper) clearStickinessState() { - if oldKey := bp.getStickinessMDKey(); oldKey != "" { - // There's no need to reset store if mdKey was "". - bp.stickiness.reset(oldKey) - } -} - -// updatePicker is called by UpdateBalancerState. It unblocks all blocked pick. -func (bp *pickerWrapper) updatePicker(p balancer.Picker) { - bp.mu.Lock() - if bp.done { - bp.mu.Unlock() - return - } - bp.picker = p - // bp.blockingCh should never be nil. - close(bp.blockingCh) - bp.blockingCh = make(chan struct{}) - bp.mu.Unlock() -} - -func doneChannelzWrapper(acw *acBalancerWrapper, done func(balancer.DoneInfo)) func(balancer.DoneInfo) { - acw.mu.Lock() - ac := acw.ac - acw.mu.Unlock() - ac.incrCallsStarted() - return func(b balancer.DoneInfo) { - if b.Err != nil && b.Err != io.EOF { - ac.incrCallsFailed() - } else { - ac.incrCallsSucceeded() - } - if done != nil { - done(b) - } - } -} - -// pick returns the transport that will be used for the RPC. -// It may block in the following cases: -// - there's no picker -// - the current picker returns ErrNoSubConnAvailable -// - the current picker returns other errors and failfast is false. -// - the subConn returned by the current picker is not READY -// When one of these situations happens, pick blocks until the picker gets updated. -func (bp *pickerWrapper) pick(ctx context.Context, failfast bool, opts balancer.PickOptions) (transport.ClientTransport, func(balancer.DoneInfo), error) { - - mdKey := bp.getStickinessMDKey() - stickyKey, isSticky := stickyKeyFromContext(ctx, mdKey) - - // Potential race here: if stickinessMDKey is updated after the above two - // lines, and this pick is a sticky pick, the following put could add an - // entry to sticky store with an outdated sticky key. - // - // The solution: keep the current md key in sticky store, and at the - // beginning of each get/put, check the mdkey against store.curMDKey. - // - Cons: one more string comparing for each get/put. - // - Pros: the string matching happens inside get/put, so the overhead for - // non-sticky RPCs will be minimal. - - if isSticky { - if t, ok := bp.stickiness.get(mdKey, stickyKey); ok { - // Done function returned is always nil. - return t, nil, nil - } - } - - var ( - p balancer.Picker - ch chan struct{} - ) - - for { - bp.mu.Lock() - if bp.done { - bp.mu.Unlock() - return nil, nil, ErrClientConnClosing - } - - if bp.picker == nil { - ch = bp.blockingCh - } - if ch == bp.blockingCh { - // This could happen when either: - // - bp.picker is nil (the previous if condition), or - // - has called pick on the current picker. - bp.mu.Unlock() - select { - case <-ctx.Done(): - return nil, nil, ctx.Err() - case <-ch: - } - continue - } - - ch = bp.blockingCh - p = bp.picker - bp.mu.Unlock() - - subConn, done, err := p.Pick(ctx, opts) - - if err != nil { - switch err { - case balancer.ErrNoSubConnAvailable: - continue - case balancer.ErrTransientFailure: - if !failfast { - continue - } - return nil, nil, status.Errorf(codes.Unavailable, "%v, latest connection error: %v", err, bp.connectionError()) - default: - // err is some other error. - return nil, nil, toRPCErr(err) - } - } - - acw, ok := subConn.(*acBalancerWrapper) - if !ok { - grpclog.Infof("subconn returned from pick is not *acBalancerWrapper") - continue - } - if t, ok := acw.getAddrConn().getReadyTransport(); ok { - if isSticky { - bp.stickiness.put(mdKey, stickyKey, acw) - } - if channelz.IsOn() { - return t, doneChannelzWrapper(acw, done), nil - } - return t, done, nil - } - grpclog.Infof("blockingPicker: the picked transport is not ready, loop back to repick") - // If ok == false, ac.state is not READY. - // A valid picker always returns READY subConn. This means the state of ac - // just changed, and picker will be updated shortly. - // continue back to the beginning of the for loop to repick. - } -} - -func (bp *pickerWrapper) close() { - bp.mu.Lock() - defer bp.mu.Unlock() - if bp.done { - return - } - bp.done = true - close(bp.blockingCh) -} - -type stickyStoreEntry struct { - acw *acBalancerWrapper - addr resolver.Address -} - -type stickyStore struct { - mu sync.Mutex - // curMDKey is check before every get/put to avoid races. The operation will - // abort immediately when the given mdKey is different from the curMDKey. - curMDKey string - store map[string]*stickyStoreEntry -} - -func newStickyStore() *stickyStore { - return &stickyStore{ - store: make(map[string]*stickyStoreEntry), - } -} - -// reset clears the map in stickyStore, and set the currentMDKey to newMDKey. -func (ss *stickyStore) reset(newMDKey string) { - ss.mu.Lock() - ss.curMDKey = newMDKey - ss.store = make(map[string]*stickyStoreEntry) - ss.mu.Unlock() -} - -// stickyKey is the key to look up in store. mdKey will be checked against -// curMDKey to avoid races. -func (ss *stickyStore) put(mdKey, stickyKey string, acw *acBalancerWrapper) { - ss.mu.Lock() - defer ss.mu.Unlock() - if mdKey != ss.curMDKey { - return - } - // TODO(stickiness): limit the total number of entries. - ss.store[stickyKey] = &stickyStoreEntry{ - acw: acw, - addr: acw.getAddrConn().getCurAddr(), - } -} - -// stickyKey is the key to look up in store. mdKey will be checked against -// curMDKey to avoid races. -func (ss *stickyStore) get(mdKey, stickyKey string) (transport.ClientTransport, bool) { - ss.mu.Lock() - defer ss.mu.Unlock() - if mdKey != ss.curMDKey { - return nil, false - } - entry, ok := ss.store[stickyKey] - if !ok { - return nil, false - } - ac := entry.acw.getAddrConn() - if ac.getCurAddr() != entry.addr { - delete(ss.store, stickyKey) - return nil, false - } - t, ok := ac.getReadyTransport() - if !ok { - delete(ss.store, stickyKey) - return nil, false - } - return t, true -} - -// Get one value from metadata in ctx with key stickinessMDKey. -// -// It returns "", false if stickinessMDKey is an empty string. -func stickyKeyFromContext(ctx context.Context, stickinessMDKey string) (string, bool) { - if stickinessMDKey == "" { - return "", false - } - - md, added, ok := metadata.FromOutgoingContextRaw(ctx) - if !ok { - return "", false - } - - if vv, ok := md[stickinessMDKey]; ok { - if len(vv) > 0 { - return vv[0], true - } - } - - for _, ss := range added { - for i := 0; i < len(ss)-1; i += 2 { - if ss[i] == stickinessMDKey { - return ss[i+1], true - } - } - } - - return "", false -} diff --git a/vendor/google.golang.org/grpc/pickfirst.go b/vendor/google.golang.org/grpc/pickfirst.go deleted file mode 100644 index bf659d49d2f..00000000000 --- a/vendor/google.golang.org/grpc/pickfirst.go +++ /dev/null @@ -1,108 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 grpc - -import ( - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/resolver" -) - -// PickFirstBalancerName is the name of the pick_first balancer. -const PickFirstBalancerName = "pick_first" - -func newPickfirstBuilder() balancer.Builder { - return &pickfirstBuilder{} -} - -type pickfirstBuilder struct{} - -func (*pickfirstBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions) balancer.Balancer { - return &pickfirstBalancer{cc: cc} -} - -func (*pickfirstBuilder) Name() string { - return PickFirstBalancerName -} - -type pickfirstBalancer struct { - cc balancer.ClientConn - sc balancer.SubConn -} - -func (b *pickfirstBalancer) HandleResolvedAddrs(addrs []resolver.Address, err error) { - if err != nil { - grpclog.Infof("pickfirstBalancer: HandleResolvedAddrs called with error %v", err) - return - } - if b.sc == nil { - b.sc, err = b.cc.NewSubConn(addrs, balancer.NewSubConnOptions{}) - if err != nil { - grpclog.Errorf("pickfirstBalancer: failed to NewSubConn: %v", err) - return - } - b.cc.UpdateBalancerState(connectivity.Idle, &picker{sc: b.sc}) - b.sc.Connect() - } else { - b.sc.UpdateAddresses(addrs) - b.sc.Connect() - } -} - -func (b *pickfirstBalancer) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { - grpclog.Infof("pickfirstBalancer: HandleSubConnStateChange: %p, %v", sc, s) - if b.sc != sc { - grpclog.Infof("pickfirstBalancer: ignored state change because sc is not recognized") - return - } - if s == connectivity.Shutdown { - b.sc = nil - return - } - - switch s { - case connectivity.Ready, connectivity.Idle: - b.cc.UpdateBalancerState(s, &picker{sc: sc}) - case connectivity.Connecting: - b.cc.UpdateBalancerState(s, &picker{err: balancer.ErrNoSubConnAvailable}) - case connectivity.TransientFailure: - b.cc.UpdateBalancerState(s, &picker{err: balancer.ErrTransientFailure}) - } -} - -func (b *pickfirstBalancer) Close() { -} - -type picker struct { - err error - sc balancer.SubConn -} - -func (p *picker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { - if p.err != nil { - return nil, nil, p.err - } - return p.sc, nil, nil -} - -func init() { - balancer.Register(newPickfirstBuilder()) -} diff --git a/vendor/google.golang.org/grpc/proxy.go b/vendor/google.golang.org/grpc/proxy.go deleted file mode 100644 index 2d40236e218..00000000000 --- a/vendor/google.golang.org/grpc/proxy.go +++ /dev/null @@ -1,130 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 grpc - -import ( - "bufio" - "errors" - "fmt" - "io" - "net" - "net/http" - "net/http/httputil" - "net/url" - - "golang.org/x/net/context" -) - -var ( - // errDisabled indicates that proxy is disabled for the address. - errDisabled = errors.New("proxy is disabled for the address") - // The following variable will be overwritten in the tests. - httpProxyFromEnvironment = http.ProxyFromEnvironment -) - -func mapAddress(ctx context.Context, address string) (string, error) { - req := &http.Request{ - URL: &url.URL{ - Scheme: "https", - Host: address, - }, - } - url, err := httpProxyFromEnvironment(req) - if err != nil { - return "", err - } - if url == nil { - return "", errDisabled - } - return url.Host, nil -} - -// To read a response from a net.Conn, http.ReadResponse() takes a bufio.Reader. -// It's possible that this reader reads more than what's need for the response and stores -// those bytes in the buffer. -// bufConn wraps the original net.Conn and the bufio.Reader to make sure we don't lose the -// bytes in the buffer. -type bufConn struct { - net.Conn - r io.Reader -} - -func (c *bufConn) Read(b []byte) (int, error) { - return c.r.Read(b) -} - -func doHTTPConnectHandshake(ctx context.Context, conn net.Conn, addr string) (_ net.Conn, err error) { - defer func() { - if err != nil { - conn.Close() - } - }() - - req := (&http.Request{ - Method: http.MethodConnect, - URL: &url.URL{Host: addr}, - Header: map[string][]string{"User-Agent": {grpcUA}}, - }) - - if err := sendHTTPRequest(ctx, req, conn); err != nil { - return nil, fmt.Errorf("failed to write the HTTP request: %v", err) - } - - r := bufio.NewReader(conn) - resp, err := http.ReadResponse(r, req) - if err != nil { - return nil, fmt.Errorf("reading server HTTP response: %v", err) - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - dump, err := httputil.DumpResponse(resp, true) - if err != nil { - return nil, fmt.Errorf("failed to do connect handshake, status code: %s", resp.Status) - } - return nil, fmt.Errorf("failed to do connect handshake, response: %q", dump) - } - - return &bufConn{Conn: conn, r: r}, nil -} - -// newProxyDialer returns a dialer that connects to proxy first if necessary. -// The returned dialer checks if a proxy is necessary, dial to the proxy with the -// provided dialer, does HTTP CONNECT handshake and returns the connection. -func newProxyDialer(dialer func(context.Context, string) (net.Conn, error)) func(context.Context, string) (net.Conn, error) { - return func(ctx context.Context, addr string) (conn net.Conn, err error) { - var skipHandshake bool - newAddr, err := mapAddress(ctx, addr) - if err != nil { - if err != errDisabled { - return nil, err - } - skipHandshake = true - newAddr = addr - } - - conn, err = dialer(ctx, newAddr) - if err != nil { - return - } - if !skipHandshake { - conn, err = doHTTPConnectHandshake(ctx, conn, addr) - } - return - } -} diff --git a/vendor/google.golang.org/grpc/resolver/dns/dns_resolver.go b/vendor/google.golang.org/grpc/resolver/dns/dns_resolver.go deleted file mode 100644 index c1cabfc995f..00000000000 --- a/vendor/google.golang.org/grpc/resolver/dns/dns_resolver.go +++ /dev/null @@ -1,379 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 dns implements a dns resolver to be installed as the default resolver -// in grpc. -package dns - -import ( - "encoding/json" - "errors" - "fmt" - "math/rand" - "net" - "os" - "strconv" - "strings" - "sync" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/resolver" -) - -func init() { - resolver.Register(NewBuilder()) -} - -const ( - defaultPort = "443" - defaultFreq = time.Minute * 30 - golang = "GO" - // In DNS, service config is encoded in a TXT record via the mechanism - // described in RFC-1464 using the attribute name grpc_config. - txtAttribute = "grpc_config=" -) - -var ( - errMissingAddr = errors.New("missing address") - randomGen = rand.New(rand.NewSource(time.Now().UnixNano())) -) - -// NewBuilder creates a dnsBuilder which is used to factory DNS resolvers. -func NewBuilder() resolver.Builder { - return &dnsBuilder{freq: defaultFreq} -} - -type dnsBuilder struct { - // frequency of polling the DNS server. - freq time.Duration -} - -// Build creates and starts a DNS resolver that watches the name resolution of the target. -func (b *dnsBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOption) (resolver.Resolver, error) { - host, port, err := parseTarget(target.Endpoint) - if err != nil { - return nil, err - } - - // IP address. - if net.ParseIP(host) != nil { - host, _ = formatIP(host) - addr := []resolver.Address{{Addr: host + ":" + port}} - i := &ipResolver{ - cc: cc, - ip: addr, - rn: make(chan struct{}, 1), - q: make(chan struct{}), - } - cc.NewAddress(addr) - go i.watcher() - return i, nil - } - - // DNS address (non-IP). - ctx, cancel := context.WithCancel(context.Background()) - d := &dnsResolver{ - freq: b.freq, - host: host, - port: port, - ctx: ctx, - cancel: cancel, - cc: cc, - t: time.NewTimer(0), - rn: make(chan struct{}, 1), - disableServiceConfig: opts.DisableServiceConfig, - } - - d.wg.Add(1) - go d.watcher() - return d, nil -} - -// Scheme returns the naming scheme of this resolver builder, which is "dns". -func (b *dnsBuilder) Scheme() string { - return "dns" -} - -// ipResolver watches for the name resolution update for an IP address. -type ipResolver struct { - cc resolver.ClientConn - ip []resolver.Address - // rn channel is used by ResolveNow() to force an immediate resolution of the target. - rn chan struct{} - q chan struct{} -} - -// ResolveNow resend the address it stores, no resolution is needed. -func (i *ipResolver) ResolveNow(opt resolver.ResolveNowOption) { - select { - case i.rn <- struct{}{}: - default: - } -} - -// Close closes the ipResolver. -func (i *ipResolver) Close() { - close(i.q) -} - -func (i *ipResolver) watcher() { - for { - select { - case <-i.rn: - i.cc.NewAddress(i.ip) - case <-i.q: - return - } - } -} - -// dnsResolver watches for the name resolution update for a non-IP target. -type dnsResolver struct { - freq time.Duration - host string - port string - ctx context.Context - cancel context.CancelFunc - cc resolver.ClientConn - // rn channel is used by ResolveNow() to force an immediate resolution of the target. - rn chan struct{} - t *time.Timer - // wg is used to enforce Close() to return after the watcher() goroutine has finished. - // Otherwise, data race will be possible. [Race Example] in dns_resolver_test we - // replace the real lookup functions with mocked ones to facilitate testing. - // If Close() doesn't wait for watcher() goroutine finishes, race detector sometimes - // will warns lookup (READ the lookup function pointers) inside watcher() goroutine - // has data race with replaceNetFunc (WRITE the lookup function pointers). - wg sync.WaitGroup - disableServiceConfig bool -} - -// ResolveNow invoke an immediate resolution of the target that this dnsResolver watches. -func (d *dnsResolver) ResolveNow(opt resolver.ResolveNowOption) { - select { - case d.rn <- struct{}{}: - default: - } -} - -// Close closes the dnsResolver. -func (d *dnsResolver) Close() { - d.cancel() - d.wg.Wait() - d.t.Stop() -} - -func (d *dnsResolver) watcher() { - defer d.wg.Done() - for { - select { - case <-d.ctx.Done(): - return - case <-d.t.C: - case <-d.rn: - } - result, sc := d.lookup() - // Next lookup should happen after an interval defined by d.freq. - d.t.Reset(d.freq) - d.cc.NewServiceConfig(sc) - d.cc.NewAddress(result) - } -} - -func (d *dnsResolver) lookupSRV() []resolver.Address { - var newAddrs []resolver.Address - _, srvs, err := lookupSRV(d.ctx, "grpclb", "tcp", d.host) - if err != nil { - grpclog.Infof("grpc: failed dns SRV record lookup due to %v.\n", err) - return nil - } - for _, s := range srvs { - lbAddrs, err := lookupHost(d.ctx, s.Target) - if err != nil { - grpclog.Infof("grpc: failed load balancer address dns lookup due to %v.\n", err) - continue - } - for _, a := range lbAddrs { - a, ok := formatIP(a) - if !ok { - grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err) - continue - } - addr := a + ":" + strconv.Itoa(int(s.Port)) - newAddrs = append(newAddrs, resolver.Address{Addr: addr, Type: resolver.GRPCLB, ServerName: s.Target}) - } - } - return newAddrs -} - -func (d *dnsResolver) lookupTXT() string { - ss, err := lookupTXT(d.ctx, d.host) - if err != nil { - grpclog.Infof("grpc: failed dns TXT record lookup due to %v.\n", err) - return "" - } - var res string - for _, s := range ss { - res += s - } - - // TXT record must have "grpc_config=" attribute in order to be used as service config. - if !strings.HasPrefix(res, txtAttribute) { - grpclog.Warningf("grpc: TXT record %v missing %v attribute", res, txtAttribute) - return "" - } - return strings.TrimPrefix(res, txtAttribute) -} - -func (d *dnsResolver) lookupHost() []resolver.Address { - var newAddrs []resolver.Address - addrs, err := lookupHost(d.ctx, d.host) - if err != nil { - grpclog.Warningf("grpc: failed dns A record lookup due to %v.\n", err) - return nil - } - for _, a := range addrs { - a, ok := formatIP(a) - if !ok { - grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err) - continue - } - addr := a + ":" + d.port - newAddrs = append(newAddrs, resolver.Address{Addr: addr}) - } - return newAddrs -} - -func (d *dnsResolver) lookup() ([]resolver.Address, string) { - newAddrs := d.lookupSRV() - // Support fallback to non-balancer address. - newAddrs = append(newAddrs, d.lookupHost()...) - if d.disableServiceConfig { - return newAddrs, "" - } - sc := d.lookupTXT() - return newAddrs, canaryingSC(sc) -} - -// formatIP returns ok = false if addr is not a valid textual representation of an IP address. -// If addr is an IPv4 address, return the addr and ok = true. -// If addr is an IPv6 address, return the addr enclosed in square brackets and ok = true. -func formatIP(addr string) (addrIP string, ok bool) { - ip := net.ParseIP(addr) - if ip == nil { - return "", false - } - if ip.To4() != nil { - return addr, true - } - return "[" + addr + "]", true -} - -// parseTarget takes the user input target string, returns formatted host and port info. -// If target doesn't specify a port, set the port to be the defaultPort. -// If target is in IPv6 format and host-name is enclosed in sqarue brackets, brackets -// are strippd when setting the host. -// examples: -// target: "www.google.com" returns host: "www.google.com", port: "443" -// target: "ipv4-host:80" returns host: "ipv4-host", port: "80" -// target: "[ipv6-host]" returns host: "ipv6-host", port: "443" -// target: ":80" returns host: "localhost", port: "80" -// target: ":" returns host: "localhost", port: "443" -func parseTarget(target string) (host, port string, err error) { - if target == "" { - return "", "", errMissingAddr - } - if ip := net.ParseIP(target); ip != nil { - // target is an IPv4 or IPv6(without brackets) address - return target, defaultPort, nil - } - if host, port, err = net.SplitHostPort(target); err == nil { - // target has port, i.e ipv4-host:port, [ipv6-host]:port, host-name:port - if host == "" { - // Keep consistent with net.Dial(): If the host is empty, as in ":80", the local system is assumed. - host = "localhost" - } - if port == "" { - // If the port field is empty(target ends with colon), e.g. "[::1]:", defaultPort is used. - port = defaultPort - } - return host, port, nil - } - if host, port, err = net.SplitHostPort(target + ":" + defaultPort); err == nil { - // target doesn't have port - return host, port, nil - } - return "", "", fmt.Errorf("invalid target address %v, error info: %v", target, err) -} - -type rawChoice struct { - ClientLanguage *[]string `json:"clientLanguage,omitempty"` - Percentage *int `json:"percentage,omitempty"` - ClientHostName *[]string `json:"clientHostName,omitempty"` - ServiceConfig *json.RawMessage `json:"serviceConfig,omitempty"` -} - -func containsString(a *[]string, b string) bool { - if a == nil { - return true - } - for _, c := range *a { - if c == b { - return true - } - } - return false -} - -func chosenByPercentage(a *int) bool { - if a == nil { - return true - } - return randomGen.Intn(100)+1 <= *a -} - -func canaryingSC(js string) string { - if js == "" { - return "" - } - var rcs []rawChoice - err := json.Unmarshal([]byte(js), &rcs) - if err != nil { - grpclog.Warningf("grpc: failed to parse service config json string due to %v.\n", err) - return "" - } - cliHostname, err := os.Hostname() - if err != nil { - grpclog.Warningf("grpc: failed to get client hostname due to %v.\n", err) - return "" - } - var sc string - for _, c := range rcs { - if !containsString(c.ClientLanguage, golang) || - !chosenByPercentage(c.Percentage) || - !containsString(c.ClientHostName, cliHostname) || - c.ServiceConfig == nil { - continue - } - sc = string(*c.ServiceConfig) - break - } - return sc -} diff --git a/vendor/google.golang.org/grpc/resolver/dns/go17.go b/vendor/google.golang.org/grpc/resolver/dns/go17.go deleted file mode 100644 index b466bc8f6d4..00000000000 --- a/vendor/google.golang.org/grpc/resolver/dns/go17.go +++ /dev/null @@ -1,35 +0,0 @@ -// +build go1.6, !go1.8 - -/* - * - * Copyright 2017 gRPC 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 dns - -import ( - "net" - - "golang.org/x/net/context" -) - -var ( - lookupHost = func(ctx context.Context, host string) ([]string, error) { return net.LookupHost(host) } - lookupSRV = func(ctx context.Context, service, proto, name string) (string, []*net.SRV, error) { - return net.LookupSRV(service, proto, name) - } - lookupTXT = func(ctx context.Context, name string) ([]string, error) { return net.LookupTXT(name) } -) diff --git a/vendor/google.golang.org/grpc/resolver/dns/go18.go b/vendor/google.golang.org/grpc/resolver/dns/go18.go deleted file mode 100644 index fa34f14cad4..00000000000 --- a/vendor/google.golang.org/grpc/resolver/dns/go18.go +++ /dev/null @@ -1,29 +0,0 @@ -// +build go1.8 - -/* - * - * Copyright 2017 gRPC 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 dns - -import "net" - -var ( - lookupHost = net.DefaultResolver.LookupHost - lookupSRV = net.DefaultResolver.LookupSRV - lookupTXT = net.DefaultResolver.LookupTXT -) diff --git a/vendor/google.golang.org/grpc/resolver/passthrough/passthrough.go b/vendor/google.golang.org/grpc/resolver/passthrough/passthrough.go deleted file mode 100644 index b76010d74d1..00000000000 --- a/vendor/google.golang.org/grpc/resolver/passthrough/passthrough.go +++ /dev/null @@ -1,57 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 passthrough implements a pass-through resolver. It sends the target -// name without scheme back to gRPC as resolved address. -package passthrough - -import "google.golang.org/grpc/resolver" - -const scheme = "passthrough" - -type passthroughBuilder struct{} - -func (*passthroughBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOption) (resolver.Resolver, error) { - r := &passthroughResolver{ - target: target, - cc: cc, - } - r.start() - return r, nil -} - -func (*passthroughBuilder) Scheme() string { - return scheme -} - -type passthroughResolver struct { - target resolver.Target - cc resolver.ClientConn -} - -func (r *passthroughResolver) start() { - r.cc.NewAddress([]resolver.Address{{Addr: r.target.Endpoint}}) -} - -func (*passthroughResolver) ResolveNow(o resolver.ResolveNowOption) {} - -func (*passthroughResolver) Close() {} - -func init() { - resolver.Register(&passthroughBuilder{}) -} diff --git a/vendor/google.golang.org/grpc/resolver/resolver.go b/vendor/google.golang.org/grpc/resolver/resolver.go deleted file mode 100644 index 506afac88ae..00000000000 --- a/vendor/google.golang.org/grpc/resolver/resolver.go +++ /dev/null @@ -1,154 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 resolver defines APIs for name resolution in gRPC. -// All APIs in this package are experimental. -package resolver - -var ( - // m is a map from scheme to resolver builder. - m = make(map[string]Builder) - // defaultScheme is the default scheme to use. - defaultScheme = "passthrough" -) - -// TODO(bar) install dns resolver in init(){}. - -// Register registers the resolver builder to the resolver map. b.Scheme will be -// used as the scheme registered with this builder. -// -// NOTE: this function must only be called during initialization time (i.e. in -// an init() function), and is not thread-safe. If multiple Resolvers are -// registered with the same name, the one registered last will take effect. -func Register(b Builder) { - m[b.Scheme()] = b -} - -// Get returns the resolver builder registered with the given scheme. -// -// If no builder is register with the scheme, nil will be returned. -func Get(scheme string) Builder { - if b, ok := m[scheme]; ok { - return b - } - return nil -} - -// SetDefaultScheme sets the default scheme that will be used. -// The default default scheme is "passthrough". -func SetDefaultScheme(scheme string) { - defaultScheme = scheme -} - -// GetDefaultScheme gets the default scheme that will be used. -func GetDefaultScheme() string { - return defaultScheme -} - -// AddressType indicates the address type returned by name resolution. -type AddressType uint8 - -const ( - // Backend indicates the address is for a backend server. - Backend AddressType = iota - // GRPCLB indicates the address is for a grpclb load balancer. - GRPCLB -) - -// Address represents a server the client connects to. -// This is the EXPERIMENTAL API and may be changed or extended in the future. -type Address struct { - // Addr is the server address on which a connection will be established. - Addr string - // Type is the type of this address. - Type AddressType - // ServerName is the name of this address. - // - // e.g. if Type is GRPCLB, ServerName should be the name of the remote load - // balancer, not the name of the backend. - ServerName string - // Metadata is the information associated with Addr, which may be used - // to make load balancing decision. - Metadata interface{} -} - -// BuildOption includes additional information for the builder to create -// the resolver. -type BuildOption struct { - // DisableServiceConfig indicates whether resolver should fetch service config data. - DisableServiceConfig bool -} - -// ClientConn contains the callbacks for resolver to notify any updates -// to the gRPC ClientConn. -// -// This interface is to be implemented by gRPC. Users should not need a -// brand new implementation of this interface. For the situations like -// testing, the new implementation should embed this interface. This allows -// gRPC to add new methods to this interface. -type ClientConn interface { - // NewAddress is called by resolver to notify ClientConn a new list - // of resolved addresses. - // The address list should be the complete list of resolved addresses. - NewAddress(addresses []Address) - // NewServiceConfig is called by resolver to notify ClientConn a new - // service config. The service config should be provided as a json string. - NewServiceConfig(serviceConfig string) -} - -// Target represents a target for gRPC, as specified in: -// https://github.com/grpc/grpc/blob/master/doc/naming.md. -type Target struct { - Scheme string - Authority string - Endpoint string -} - -// Builder creates a resolver that will be used to watch name resolution updates. -type Builder interface { - // Build creates a new resolver for the given target. - // - // gRPC dial calls Build synchronously, and fails if the returned error is - // not nil. - Build(target Target, cc ClientConn, opts BuildOption) (Resolver, error) - // Scheme returns the scheme supported by this resolver. - // Scheme is defined at https://github.com/grpc/grpc/blob/master/doc/naming.md. - Scheme() string -} - -// ResolveNowOption includes additional information for ResolveNow. -type ResolveNowOption struct{} - -// Resolver watches for the updates on the specified target. -// Updates include address updates and service config updates. -type Resolver interface { - // ResolveNow will be called by gRPC to try to resolve the target name - // again. It's just a hint, resolver can ignore this if it's not necessary. - // - // It could be called multiple times concurrently. - ResolveNow(ResolveNowOption) - // Close closes the resolver. - Close() -} - -// UnregisterForTesting removes the resolver builder with the given scheme from the -// resolver map. -// This function is for testing only. -func UnregisterForTesting(scheme string) { - delete(m, scheme) -} diff --git a/vendor/google.golang.org/grpc/resolver_conn_wrapper.go b/vendor/google.golang.org/grpc/resolver_conn_wrapper.go deleted file mode 100644 index 1b493db2e6c..00000000000 --- a/vendor/google.golang.org/grpc/resolver_conn_wrapper.go +++ /dev/null @@ -1,158 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 grpc - -import ( - "fmt" - "strings" - - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/resolver" -) - -// ccResolverWrapper is a wrapper on top of cc for resolvers. -// It implements resolver.ClientConnection interface. -type ccResolverWrapper struct { - cc *ClientConn - resolver resolver.Resolver - addrCh chan []resolver.Address - scCh chan string - done chan struct{} -} - -// split2 returns the values from strings.SplitN(s, sep, 2). -// If sep is not found, it returns ("", s, false) instead. -func split2(s, sep string) (string, string, bool) { - spl := strings.SplitN(s, sep, 2) - if len(spl) < 2 { - return "", "", false - } - return spl[0], spl[1], true -} - -// parseTarget splits target into a struct containing scheme, authority and -// endpoint. -// -// If target is not a valid scheme://authority/endpoint, it returns {Endpoint: -// target}. -func parseTarget(target string) (ret resolver.Target) { - var ok bool - ret.Scheme, ret.Endpoint, ok = split2(target, "://") - if !ok { - return resolver.Target{Endpoint: target} - } - ret.Authority, ret.Endpoint, ok = split2(ret.Endpoint, "/") - if !ok { - return resolver.Target{Endpoint: target} - } - return ret -} - -// newCCResolverWrapper parses cc.target for scheme and gets the resolver -// builder for this scheme. It then builds the resolver and starts the -// monitoring goroutine for it. -// -// If withResolverBuilder dial option is set, the specified resolver will be -// used instead. -func newCCResolverWrapper(cc *ClientConn) (*ccResolverWrapper, error) { - rb := cc.dopts.resolverBuilder - if rb == nil { - return nil, fmt.Errorf("could not get resolver for scheme: %q", cc.parsedTarget.Scheme) - } - - ccr := &ccResolverWrapper{ - cc: cc, - addrCh: make(chan []resolver.Address, 1), - scCh: make(chan string, 1), - done: make(chan struct{}), - } - - var err error - ccr.resolver, err = rb.Build(cc.parsedTarget, ccr, resolver.BuildOption{DisableServiceConfig: cc.dopts.disableServiceConfig}) - if err != nil { - return nil, err - } - return ccr, nil -} - -func (ccr *ccResolverWrapper) start() { - go ccr.watcher() -} - -// watcher processes address updates and service config updates sequentially. -// Otherwise, we need to resolve possible races between address and service -// config (e.g. they specify different balancer types). -func (ccr *ccResolverWrapper) watcher() { - for { - select { - case <-ccr.done: - return - default: - } - - select { - case addrs := <-ccr.addrCh: - select { - case <-ccr.done: - return - default: - } - grpclog.Infof("ccResolverWrapper: sending new addresses to cc: %v", addrs) - ccr.cc.handleResolvedAddrs(addrs, nil) - case sc := <-ccr.scCh: - select { - case <-ccr.done: - return - default: - } - grpclog.Infof("ccResolverWrapper: got new service config: %v", sc) - ccr.cc.handleServiceConfig(sc) - case <-ccr.done: - return - } - } -} - -func (ccr *ccResolverWrapper) resolveNow(o resolver.ResolveNowOption) { - ccr.resolver.ResolveNow(o) -} - -func (ccr *ccResolverWrapper) close() { - ccr.resolver.Close() - close(ccr.done) -} - -// NewAddress is called by the resolver implemenetion to send addresses to gRPC. -func (ccr *ccResolverWrapper) NewAddress(addrs []resolver.Address) { - select { - case <-ccr.addrCh: - default: - } - ccr.addrCh <- addrs -} - -// NewServiceConfig is called by the resolver implemenetion to send service -// configs to gPRC. -func (ccr *ccResolverWrapper) NewServiceConfig(sc string) { - select { - case <-ccr.scCh: - default: - } - ccr.scCh <- sc -} diff --git a/vendor/google.golang.org/grpc/rpc_util.go b/vendor/google.golang.org/grpc/rpc_util.go deleted file mode 100644 index 69ef3c0b595..00000000000 --- a/vendor/google.golang.org/grpc/rpc_util.go +++ /dev/null @@ -1,727 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 grpc - -import ( - "bytes" - "compress/gzip" - "encoding/binary" - "fmt" - "io" - "io/ioutil" - "math" - "net/url" - "strings" - "sync" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/encoding" - "google.golang.org/grpc/encoding/proto" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/peer" - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" - "google.golang.org/grpc/transport" -) - -// Compressor defines the interface gRPC uses to compress a message. -// -// Deprecated: use package encoding. -type Compressor interface { - // Do compresses p into w. - Do(w io.Writer, p []byte) error - // Type returns the compression algorithm the Compressor uses. - Type() string -} - -type gzipCompressor struct { - pool sync.Pool -} - -// NewGZIPCompressor creates a Compressor based on GZIP. -// -// Deprecated: use package encoding/gzip. -func NewGZIPCompressor() Compressor { - c, _ := NewGZIPCompressorWithLevel(gzip.DefaultCompression) - return c -} - -// NewGZIPCompressorWithLevel is like NewGZIPCompressor but specifies the gzip compression level instead -// of assuming DefaultCompression. -// -// The error returned will be nil if the level is valid. -// -// Deprecated: use package encoding/gzip. -func NewGZIPCompressorWithLevel(level int) (Compressor, error) { - if level < gzip.DefaultCompression || level > gzip.BestCompression { - return nil, fmt.Errorf("grpc: invalid compression level: %d", level) - } - return &gzipCompressor{ - pool: sync.Pool{ - New: func() interface{} { - w, err := gzip.NewWriterLevel(ioutil.Discard, level) - if err != nil { - panic(err) - } - return w - }, - }, - }, nil -} - -func (c *gzipCompressor) Do(w io.Writer, p []byte) error { - z := c.pool.Get().(*gzip.Writer) - defer c.pool.Put(z) - z.Reset(w) - if _, err := z.Write(p); err != nil { - return err - } - return z.Close() -} - -func (c *gzipCompressor) Type() string { - return "gzip" -} - -// Decompressor defines the interface gRPC uses to decompress a message. -// -// Deprecated: use package encoding. -type Decompressor interface { - // Do reads the data from r and uncompress them. - Do(r io.Reader) ([]byte, error) - // Type returns the compression algorithm the Decompressor uses. - Type() string -} - -type gzipDecompressor struct { - pool sync.Pool -} - -// NewGZIPDecompressor creates a Decompressor based on GZIP. -// -// Deprecated: use package encoding/gzip. -func NewGZIPDecompressor() Decompressor { - return &gzipDecompressor{} -} - -func (d *gzipDecompressor) Do(r io.Reader) ([]byte, error) { - var z *gzip.Reader - switch maybeZ := d.pool.Get().(type) { - case nil: - newZ, err := gzip.NewReader(r) - if err != nil { - return nil, err - } - z = newZ - case *gzip.Reader: - z = maybeZ - if err := z.Reset(r); err != nil { - d.pool.Put(z) - return nil, err - } - } - - defer func() { - z.Close() - d.pool.Put(z) - }() - return ioutil.ReadAll(z) -} - -func (d *gzipDecompressor) Type() string { - return "gzip" -} - -// callInfo contains all related configuration and information about an RPC. -type callInfo struct { - compressorType string - failFast bool - stream *clientStream - traceInfo traceInfo // in trace.go - maxReceiveMessageSize *int - maxSendMessageSize *int - creds credentials.PerRPCCredentials - contentSubtype string - codec baseCodec -} - -func defaultCallInfo() *callInfo { - return &callInfo{failFast: true} -} - -// CallOption configures a Call before it starts or extracts information from -// a Call after it completes. -type CallOption interface { - // before is called before the call is sent to any server. If before - // returns a non-nil error, the RPC fails with that error. - before(*callInfo) error - - // after is called after the call has completed. after cannot return an - // error, so any failures should be reported via output parameters. - after(*callInfo) -} - -// EmptyCallOption does not alter the Call configuration. -// It can be embedded in another structure to carry satellite data for use -// by interceptors. -type EmptyCallOption struct{} - -func (EmptyCallOption) before(*callInfo) error { return nil } -func (EmptyCallOption) after(*callInfo) {} - -// Header returns a CallOptions that retrieves the header metadata -// for a unary RPC. -func Header(md *metadata.MD) CallOption { - return HeaderCallOption{HeaderAddr: md} -} - -// HeaderCallOption is a CallOption for collecting response header metadata. -// The metadata field will be populated *after* the RPC completes. -// This is an EXPERIMENTAL API. -type HeaderCallOption struct { - HeaderAddr *metadata.MD -} - -func (o HeaderCallOption) before(c *callInfo) error { return nil } -func (o HeaderCallOption) after(c *callInfo) { - if c.stream != nil { - *o.HeaderAddr, _ = c.stream.Header() - } -} - -// Trailer returns a CallOptions that retrieves the trailer metadata -// for a unary RPC. -func Trailer(md *metadata.MD) CallOption { - return TrailerCallOption{TrailerAddr: md} -} - -// TrailerCallOption is a CallOption for collecting response trailer metadata. -// The metadata field will be populated *after* the RPC completes. -// This is an EXPERIMENTAL API. -type TrailerCallOption struct { - TrailerAddr *metadata.MD -} - -func (o TrailerCallOption) before(c *callInfo) error { return nil } -func (o TrailerCallOption) after(c *callInfo) { - if c.stream != nil { - *o.TrailerAddr = c.stream.Trailer() - } -} - -// Peer returns a CallOption that retrieves peer information for a unary RPC. -// The peer field will be populated *after* the RPC completes. -func Peer(p *peer.Peer) CallOption { - return PeerCallOption{PeerAddr: p} -} - -// PeerCallOption is a CallOption for collecting the identity of the remote -// peer. The peer field will be populated *after* the RPC completes. -// This is an EXPERIMENTAL API. -type PeerCallOption struct { - PeerAddr *peer.Peer -} - -func (o PeerCallOption) before(c *callInfo) error { return nil } -func (o PeerCallOption) after(c *callInfo) { - if c.stream != nil { - if x, ok := peer.FromContext(c.stream.Context()); ok { - *o.PeerAddr = *x - } - } -} - -// FailFast configures the action to take when an RPC is attempted on broken -// connections or unreachable servers. If failFast is true, the RPC will fail -// immediately. Otherwise, the RPC client will block the call until a -// connection is available (or the call is canceled or times out) and will -// retry the call if it fails due to a transient error. gRPC will not retry if -// data was written to the wire unless the server indicates it did not process -// the data. Please refer to -// https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md. -// -// By default, RPCs are "Fail Fast". -func FailFast(failFast bool) CallOption { - return FailFastCallOption{FailFast: failFast} -} - -// FailFastCallOption is a CallOption for indicating whether an RPC should fail -// fast or not. -// This is an EXPERIMENTAL API. -type FailFastCallOption struct { - FailFast bool -} - -func (o FailFastCallOption) before(c *callInfo) error { - c.failFast = o.FailFast - return nil -} -func (o FailFastCallOption) after(c *callInfo) {} - -// MaxCallRecvMsgSize returns a CallOption which sets the maximum message size the client can receive. -func MaxCallRecvMsgSize(s int) CallOption { - return MaxRecvMsgSizeCallOption{MaxRecvMsgSize: s} -} - -// MaxRecvMsgSizeCallOption is a CallOption that indicates the maximum message -// size the client can receive. -// This is an EXPERIMENTAL API. -type MaxRecvMsgSizeCallOption struct { - MaxRecvMsgSize int -} - -func (o MaxRecvMsgSizeCallOption) before(c *callInfo) error { - c.maxReceiveMessageSize = &o.MaxRecvMsgSize - return nil -} -func (o MaxRecvMsgSizeCallOption) after(c *callInfo) {} - -// MaxCallSendMsgSize returns a CallOption which sets the maximum message size the client can send. -func MaxCallSendMsgSize(s int) CallOption { - return MaxSendMsgSizeCallOption{MaxSendMsgSize: s} -} - -// MaxSendMsgSizeCallOption is a CallOption that indicates the maximum message -// size the client can send. -// This is an EXPERIMENTAL API. -type MaxSendMsgSizeCallOption struct { - MaxSendMsgSize int -} - -func (o MaxSendMsgSizeCallOption) before(c *callInfo) error { - c.maxSendMessageSize = &o.MaxSendMsgSize - return nil -} -func (o MaxSendMsgSizeCallOption) after(c *callInfo) {} - -// PerRPCCredentials returns a CallOption that sets credentials.PerRPCCredentials -// for a call. -func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption { - return PerRPCCredsCallOption{Creds: creds} -} - -// PerRPCCredsCallOption is a CallOption that indicates the per-RPC -// credentials to use for the call. -// This is an EXPERIMENTAL API. -type PerRPCCredsCallOption struct { - Creds credentials.PerRPCCredentials -} - -func (o PerRPCCredsCallOption) before(c *callInfo) error { - c.creds = o.Creds - return nil -} -func (o PerRPCCredsCallOption) after(c *callInfo) {} - -// UseCompressor returns a CallOption which sets the compressor used when -// sending the request. If WithCompressor is also set, UseCompressor has -// higher priority. -// -// This API is EXPERIMENTAL. -func UseCompressor(name string) CallOption { - return CompressorCallOption{CompressorType: name} -} - -// CompressorCallOption is a CallOption that indicates the compressor to use. -// This is an EXPERIMENTAL API. -type CompressorCallOption struct { - CompressorType string -} - -func (o CompressorCallOption) before(c *callInfo) error { - c.compressorType = o.CompressorType - return nil -} -func (o CompressorCallOption) after(c *callInfo) {} - -// CallContentSubtype returns a CallOption that will set the content-subtype -// for a call. For example, if content-subtype is "json", the Content-Type over -// the wire will be "application/grpc+json". The content-subtype is converted -// to lowercase before being included in Content-Type. See Content-Type on -// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for -// more details. -// -// If CallCustomCodec is not also used, the content-subtype will be used to -// look up the Codec to use in the registry controlled by RegisterCodec. See -// the documentation on RegisterCodec for details on registration. The lookup -// of content-subtype is case-insensitive. If no such Codec is found, the call -// will result in an error with code codes.Internal. -// -// If CallCustomCodec is also used, that Codec will be used for all request and -// response messages, with the content-subtype set to the given contentSubtype -// here for requests. -func CallContentSubtype(contentSubtype string) CallOption { - return ContentSubtypeCallOption{ContentSubtype: strings.ToLower(contentSubtype)} -} - -// ContentSubtypeCallOption is a CallOption that indicates the content-subtype -// used for marshaling messages. -// This is an EXPERIMENTAL API. -type ContentSubtypeCallOption struct { - ContentSubtype string -} - -func (o ContentSubtypeCallOption) before(c *callInfo) error { - c.contentSubtype = o.ContentSubtype - return nil -} -func (o ContentSubtypeCallOption) after(c *callInfo) {} - -// CallCustomCodec returns a CallOption that will set the given Codec to be -// used for all request and response messages for a call. The result of calling -// String() will be used as the content-subtype in a case-insensitive manner. -// -// See Content-Type on -// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for -// more details. Also see the documentation on RegisterCodec and -// CallContentSubtype for more details on the interaction between Codec and -// content-subtype. -// -// This function is provided for advanced users; prefer to use only -// CallContentSubtype to select a registered codec instead. -func CallCustomCodec(codec Codec) CallOption { - return CustomCodecCallOption{Codec: codec} -} - -// CustomCodecCallOption is a CallOption that indicates the codec used for -// marshaling messages. -// This is an EXPERIMENTAL API. -type CustomCodecCallOption struct { - Codec Codec -} - -func (o CustomCodecCallOption) before(c *callInfo) error { - c.codec = o.Codec - return nil -} -func (o CustomCodecCallOption) after(c *callInfo) {} - -// The format of the payload: compressed or not? -type payloadFormat uint8 - -const ( - compressionNone payloadFormat = iota // no compression - compressionMade -) - -// parser reads complete gRPC messages from the underlying reader. -type parser struct { - // r is the underlying reader. - // See the comment on recvMsg for the permissible - // error types. - r io.Reader - - // The header of a gRPC message. Find more detail at - // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md - header [5]byte -} - -// recvMsg reads a complete gRPC message from the stream. -// -// It returns the message and its payload (compression/encoding) -// format. The caller owns the returned msg memory. -// -// If there is an error, possible values are: -// * io.EOF, when no messages remain -// * io.ErrUnexpectedEOF -// * of type transport.ConnectionError -// * of type transport.StreamError -// No other error values or types must be returned, which also means -// that the underlying io.Reader must not return an incompatible -// error. -func (p *parser) recvMsg(maxReceiveMessageSize int) (pf payloadFormat, msg []byte, err error) { - if _, err := p.r.Read(p.header[:]); err != nil { - return 0, nil, err - } - - pf = payloadFormat(p.header[0]) - length := binary.BigEndian.Uint32(p.header[1:]) - - if length == 0 { - return pf, nil, nil - } - if int64(length) > int64(maxInt) { - return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max length allowed on current machine (%d vs. %d)", length, maxInt) - } - if int(length) > maxReceiveMessageSize { - return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", length, maxReceiveMessageSize) - } - // TODO(bradfitz,zhaoq): garbage. reuse buffer after proto decoding instead - // of making it for each message: - msg = make([]byte, int(length)) - if _, err := p.r.Read(msg); err != nil { - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - return 0, nil, err - } - return pf, msg, nil -} - -// encode serializes msg and returns a buffer of message header and a buffer of msg. -// If msg is nil, it generates the message header and an empty msg buffer. -// TODO(ddyihai): eliminate extra Compressor parameter. -func encode(c baseCodec, msg interface{}, cp Compressor, outPayload *stats.OutPayload, compressor encoding.Compressor) ([]byte, []byte, error) { - var ( - b []byte - cbuf *bytes.Buffer - ) - const ( - payloadLen = 1 - sizeLen = 4 - ) - if msg != nil { - var err error - b, err = c.Marshal(msg) - if err != nil { - return nil, nil, status.Errorf(codes.Internal, "grpc: error while marshaling: %v", err.Error()) - } - if outPayload != nil { - outPayload.Payload = msg - // TODO truncate large payload. - outPayload.Data = b - outPayload.Length = len(b) - } - if compressor != nil || cp != nil { - cbuf = new(bytes.Buffer) - // Has compressor, check Compressor is set by UseCompressor first. - if compressor != nil { - z, _ := compressor.Compress(cbuf) - if _, err := z.Write(b); err != nil { - return nil, nil, status.Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error()) - } - z.Close() - } else { - // If Compressor is not set by UseCompressor, use default Compressor - if err := cp.Do(cbuf, b); err != nil { - return nil, nil, status.Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error()) - } - } - b = cbuf.Bytes() - } - } - if uint(len(b)) > math.MaxUint32 { - return nil, nil, status.Errorf(codes.ResourceExhausted, "grpc: message too large (%d bytes)", len(b)) - } - - bufHeader := make([]byte, payloadLen+sizeLen) - if compressor != nil || cp != nil { - bufHeader[0] = byte(compressionMade) - } else { - bufHeader[0] = byte(compressionNone) - } - - // Write length of b into buf - binary.BigEndian.PutUint32(bufHeader[payloadLen:], uint32(len(b))) - if outPayload != nil { - outPayload.WireLength = payloadLen + sizeLen + len(b) - } - return bufHeader, b, nil -} - -func checkRecvPayload(pf payloadFormat, recvCompress string, haveCompressor bool) *status.Status { - switch pf { - case compressionNone: - case compressionMade: - if recvCompress == "" || recvCompress == encoding.Identity { - return status.New(codes.Internal, "grpc: compressed flag set with identity or empty encoding") - } - if !haveCompressor { - return status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress) - } - default: - return status.Newf(codes.Internal, "grpc: received unexpected payload format %d", pf) - } - return nil -} - -// For the two compressor parameters, both should not be set, but if they are, -// dc takes precedence over compressor. -// TODO(dfawley): wrap the old compressor/decompressor using the new API? -func recv(p *parser, c baseCodec, s *transport.Stream, dc Decompressor, m interface{}, maxReceiveMessageSize int, inPayload *stats.InPayload, compressor encoding.Compressor) error { - pf, d, err := p.recvMsg(maxReceiveMessageSize) - if err != nil { - return err - } - if inPayload != nil { - inPayload.WireLength = len(d) - } - - if st := checkRecvPayload(pf, s.RecvCompress(), compressor != nil || dc != nil); st != nil { - return st.Err() - } - - if pf == compressionMade { - // To match legacy behavior, if the decompressor is set by WithDecompressor or RPCDecompressor, - // use this decompressor as the default. - if dc != nil { - d, err = dc.Do(bytes.NewReader(d)) - if err != nil { - return status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) - } - } else { - dcReader, err := compressor.Decompress(bytes.NewReader(d)) - if err != nil { - return status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) - } - d, err = ioutil.ReadAll(dcReader) - if err != nil { - return status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) - } - } - } - if len(d) > maxReceiveMessageSize { - // TODO: Revisit the error code. Currently keep it consistent with java - // implementation. - return status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", len(d), maxReceiveMessageSize) - } - if err := c.Unmarshal(d, m); err != nil { - return status.Errorf(codes.Internal, "grpc: failed to unmarshal the received message %v", err) - } - if inPayload != nil { - inPayload.RecvTime = time.Now() - inPayload.Payload = m - // TODO truncate large payload. - inPayload.Data = d - inPayload.Length = len(d) - } - return nil -} - -type rpcInfo struct { - failfast bool -} - -type rpcInfoContextKey struct{} - -func newContextWithRPCInfo(ctx context.Context, failfast bool) context.Context { - return context.WithValue(ctx, rpcInfoContextKey{}, &rpcInfo{failfast: failfast}) -} - -func rpcInfoFromContext(ctx context.Context) (s *rpcInfo, ok bool) { - s, ok = ctx.Value(rpcInfoContextKey{}).(*rpcInfo) - return -} - -// Code returns the error code for err if it was produced by the rpc system. -// Otherwise, it returns codes.Unknown. -// -// Deprecated: use status.FromError and Code method instead. -func Code(err error) codes.Code { - if s, ok := status.FromError(err); ok { - return s.Code() - } - return codes.Unknown -} - -// ErrorDesc returns the error description of err if it was produced by the rpc system. -// Otherwise, it returns err.Error() or empty string when err is nil. -// -// Deprecated: use status.FromError and Message method instead. -func ErrorDesc(err error) string { - if s, ok := status.FromError(err); ok { - return s.Message() - } - return err.Error() -} - -// Errorf returns an error containing an error code and a description; -// Errorf returns nil if c is OK. -// -// Deprecated: use status.Errorf instead. -func Errorf(c codes.Code, format string, a ...interface{}) error { - return status.Errorf(c, format, a...) -} - -// setCallInfoCodec should only be called after CallOptions have been applied. -func setCallInfoCodec(c *callInfo) error { - if c.codec != nil { - // codec was already set by a CallOption; use it. - return nil - } - - if c.contentSubtype == "" { - // No codec specified in CallOptions; use proto by default. - c.codec = encoding.GetCodec(proto.Name) - return nil - } - - // c.contentSubtype is already lowercased in CallContentSubtype - c.codec = encoding.GetCodec(c.contentSubtype) - if c.codec == nil { - return status.Errorf(codes.Internal, "no codec registered for content-subtype %s", c.contentSubtype) - } - return nil -} - -// parseDialTarget returns the network and address to pass to dialer -func parseDialTarget(target string) (net string, addr string) { - net = "tcp" - - m1 := strings.Index(target, ":") - m2 := strings.Index(target, ":/") - - // handle unix:addr which will fail with url.Parse - if m1 >= 0 && m2 < 0 { - if n := target[0:m1]; n == "unix" { - net = n - addr = target[m1+1:] - return net, addr - } - } - if m2 >= 0 { - t, err := url.Parse(target) - if err != nil { - return net, target - } - scheme := t.Scheme - addr = t.Path - if scheme == "unix" { - net = scheme - if addr == "" { - addr = t.Host - } - return net, addr - } - } - - return net, target -} - -// The SupportPackageIsVersion variables are referenced from generated protocol -// buffer files to ensure compatibility with the gRPC version used. The latest -// support package version is 5. -// -// Older versions are kept for compatibility. They may be removed if -// compatibility cannot be maintained. -// -// These constants should not be referenced from any other code. -const ( - SupportPackageIsVersion3 = true - SupportPackageIsVersion4 = true - SupportPackageIsVersion5 = true -) - -// Version is the current grpc version. -const Version = "1.12.0" - -const grpcUA = "grpc-go/" + Version diff --git a/vendor/google.golang.org/grpc/server.go b/vendor/google.golang.org/grpc/server.go deleted file mode 100644 index 4969331cb3d..00000000000 --- a/vendor/google.golang.org/grpc/server.go +++ /dev/null @@ -1,1486 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 grpc - -import ( - "bytes" - "errors" - "fmt" - "io" - "math" - "net" - "net/http" - "reflect" - "runtime" - "strings" - "sync" - "time" - - "io/ioutil" - - "golang.org/x/net/context" - "golang.org/x/net/http2" - "golang.org/x/net/trace" - - "google.golang.org/grpc/channelz" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/encoding" - "google.golang.org/grpc/encoding/proto" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/internal" - "google.golang.org/grpc/keepalive" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" - "google.golang.org/grpc/tap" - "google.golang.org/grpc/transport" -) - -const ( - defaultServerMaxReceiveMessageSize = 1024 * 1024 * 4 - defaultServerMaxSendMessageSize = math.MaxInt32 -) - -type methodHandler func(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor UnaryServerInterceptor) (interface{}, error) - -// MethodDesc represents an RPC service's method specification. -type MethodDesc struct { - MethodName string - Handler methodHandler -} - -// ServiceDesc represents an RPC service's specification. -type ServiceDesc struct { - ServiceName string - // The pointer to the service interface. Used to check whether the user - // provided implementation satisfies the interface requirements. - HandlerType interface{} - Methods []MethodDesc - Streams []StreamDesc - Metadata interface{} -} - -// service consists of the information of the server serving this service and -// the methods in this service. -type service struct { - server interface{} // the server for service methods - md map[string]*MethodDesc - sd map[string]*StreamDesc - mdata interface{} -} - -// Server is a gRPC server to serve RPC requests. -type Server struct { - opts options - - mu sync.Mutex // guards following - lis map[net.Listener]bool - conns map[io.Closer]bool - serve bool - drain bool - cv *sync.Cond // signaled when connections close for GracefulStop - m map[string]*service // service name -> service info - events trace.EventLog - - quit chan struct{} - done chan struct{} - quitOnce sync.Once - doneOnce sync.Once - channelzRemoveOnce sync.Once - serveWG sync.WaitGroup // counts active Serve goroutines for GracefulStop - - channelzID int64 // channelz unique identification number - czmu sync.RWMutex - callsStarted int64 - callsFailed int64 - callsSucceeded int64 - lastCallStartedTime time.Time -} - -type options struct { - creds credentials.TransportCredentials - codec baseCodec - cp Compressor - dc Decompressor - unaryInt UnaryServerInterceptor - streamInt StreamServerInterceptor - inTapHandle tap.ServerInHandle - statsHandler stats.Handler - maxConcurrentStreams uint32 - maxReceiveMessageSize int - maxSendMessageSize int - useHandlerImpl bool // use http.Handler-based server - unknownStreamDesc *StreamDesc - keepaliveParams keepalive.ServerParameters - keepalivePolicy keepalive.EnforcementPolicy - initialWindowSize int32 - initialConnWindowSize int32 - writeBufferSize int - readBufferSize int - connectionTimeout time.Duration -} - -var defaultServerOptions = options{ - maxReceiveMessageSize: defaultServerMaxReceiveMessageSize, - maxSendMessageSize: defaultServerMaxSendMessageSize, - connectionTimeout: 120 * time.Second, -} - -// A ServerOption sets options such as credentials, codec and keepalive parameters, etc. -type ServerOption func(*options) - -// WriteBufferSize lets you set the size of write buffer, this determines how much data can be batched -// before doing a write on the wire. -func WriteBufferSize(s int) ServerOption { - return func(o *options) { - o.writeBufferSize = s - } -} - -// ReadBufferSize lets you set the size of read buffer, this determines how much data can be read at most -// for one read syscall. -func ReadBufferSize(s int) ServerOption { - return func(o *options) { - o.readBufferSize = s - } -} - -// InitialWindowSize returns a ServerOption that sets window size for stream. -// The lower bound for window size is 64K and any value smaller than that will be ignored. -func InitialWindowSize(s int32) ServerOption { - return func(o *options) { - o.initialWindowSize = s - } -} - -// InitialConnWindowSize returns a ServerOption that sets window size for a connection. -// The lower bound for window size is 64K and any value smaller than that will be ignored. -func InitialConnWindowSize(s int32) ServerOption { - return func(o *options) { - o.initialConnWindowSize = s - } -} - -// KeepaliveParams returns a ServerOption that sets keepalive and max-age parameters for the server. -func KeepaliveParams(kp keepalive.ServerParameters) ServerOption { - return func(o *options) { - o.keepaliveParams = kp - } -} - -// KeepaliveEnforcementPolicy returns a ServerOption that sets keepalive enforcement policy for the server. -func KeepaliveEnforcementPolicy(kep keepalive.EnforcementPolicy) ServerOption { - return func(o *options) { - o.keepalivePolicy = kep - } -} - -// CustomCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling. -// -// This will override any lookups by content-subtype for Codecs registered with RegisterCodec. -func CustomCodec(codec Codec) ServerOption { - return func(o *options) { - o.codec = codec - } -} - -// RPCCompressor returns a ServerOption that sets a compressor for outbound -// messages. For backward compatibility, all outbound messages will be sent -// using this compressor, regardless of incoming message compression. By -// default, server messages will be sent using the same compressor with which -// request messages were sent. -// -// Deprecated: use encoding.RegisterCompressor instead. -func RPCCompressor(cp Compressor) ServerOption { - return func(o *options) { - o.cp = cp - } -} - -// RPCDecompressor returns a ServerOption that sets a decompressor for inbound -// messages. It has higher priority than decompressors registered via -// encoding.RegisterCompressor. -// -// Deprecated: use encoding.RegisterCompressor instead. -func RPCDecompressor(dc Decompressor) ServerOption { - return func(o *options) { - o.dc = dc - } -} - -// MaxMsgSize returns a ServerOption to set the max message size in bytes the server can receive. -// If this is not set, gRPC uses the default limit. -// -// Deprecated: use MaxRecvMsgSize instead. -func MaxMsgSize(m int) ServerOption { - return MaxRecvMsgSize(m) -} - -// MaxRecvMsgSize returns a ServerOption to set the max message size in bytes the server can receive. -// If this is not set, gRPC uses the default 4MB. -func MaxRecvMsgSize(m int) ServerOption { - return func(o *options) { - o.maxReceiveMessageSize = m - } -} - -// MaxSendMsgSize returns a ServerOption to set the max message size in bytes the server can send. -// If this is not set, gRPC uses the default 4MB. -func MaxSendMsgSize(m int) ServerOption { - return func(o *options) { - o.maxSendMessageSize = m - } -} - -// MaxConcurrentStreams returns a ServerOption that will apply a limit on the number -// of concurrent streams to each ServerTransport. -func MaxConcurrentStreams(n uint32) ServerOption { - return func(o *options) { - o.maxConcurrentStreams = n - } -} - -// Creds returns a ServerOption that sets credentials for server connections. -func Creds(c credentials.TransportCredentials) ServerOption { - return func(o *options) { - o.creds = c - } -} - -// UnaryInterceptor returns a ServerOption that sets the UnaryServerInterceptor for the -// server. Only one unary interceptor can be installed. The construction of multiple -// interceptors (e.g., chaining) can be implemented at the caller. -func UnaryInterceptor(i UnaryServerInterceptor) ServerOption { - return func(o *options) { - if o.unaryInt != nil { - panic("The unary server interceptor was already set and may not be reset.") - } - o.unaryInt = i - } -} - -// StreamInterceptor returns a ServerOption that sets the StreamServerInterceptor for the -// server. Only one stream interceptor can be installed. -func StreamInterceptor(i StreamServerInterceptor) ServerOption { - return func(o *options) { - if o.streamInt != nil { - panic("The stream server interceptor was already set and may not be reset.") - } - o.streamInt = i - } -} - -// InTapHandle returns a ServerOption that sets the tap handle for all the server -// transport to be created. Only one can be installed. -func InTapHandle(h tap.ServerInHandle) ServerOption { - return func(o *options) { - if o.inTapHandle != nil { - panic("The tap handle was already set and may not be reset.") - } - o.inTapHandle = h - } -} - -// StatsHandler returns a ServerOption that sets the stats handler for the server. -func StatsHandler(h stats.Handler) ServerOption { - return func(o *options) { - o.statsHandler = h - } -} - -// UnknownServiceHandler returns a ServerOption that allows for adding a custom -// unknown service handler. The provided method is a bidi-streaming RPC service -// handler that will be invoked instead of returning the "unimplemented" gRPC -// error whenever a request is received for an unregistered service or method. -// The handling function has full access to the Context of the request and the -// stream, and the invocation bypasses interceptors. -func UnknownServiceHandler(streamHandler StreamHandler) ServerOption { - return func(o *options) { - o.unknownStreamDesc = &StreamDesc{ - StreamName: "unknown_service_handler", - Handler: streamHandler, - // We need to assume that the users of the streamHandler will want to use both. - ClientStreams: true, - ServerStreams: true, - } - } -} - -// ConnectionTimeout returns a ServerOption that sets the timeout for -// connection establishment (up to and including HTTP/2 handshaking) for all -// new connections. If this is not set, the default is 120 seconds. A zero or -// negative value will result in an immediate timeout. -// -// This API is EXPERIMENTAL. -func ConnectionTimeout(d time.Duration) ServerOption { - return func(o *options) { - o.connectionTimeout = d - } -} - -// NewServer creates a gRPC server which has no service registered and has not -// started to accept requests yet. -func NewServer(opt ...ServerOption) *Server { - opts := defaultServerOptions - for _, o := range opt { - o(&opts) - } - s := &Server{ - lis: make(map[net.Listener]bool), - opts: opts, - conns: make(map[io.Closer]bool), - m: make(map[string]*service), - quit: make(chan struct{}), - done: make(chan struct{}), - } - s.cv = sync.NewCond(&s.mu) - if EnableTracing { - _, file, line, _ := runtime.Caller(1) - s.events = trace.NewEventLog("grpc.Server", fmt.Sprintf("%s:%d", file, line)) - } - - if channelz.IsOn() { - s.channelzID = channelz.RegisterServer(s, "") - } - return s -} - -// printf records an event in s's event log, unless s has been stopped. -// REQUIRES s.mu is held. -func (s *Server) printf(format string, a ...interface{}) { - if s.events != nil { - s.events.Printf(format, a...) - } -} - -// errorf records an error in s's event log, unless s has been stopped. -// REQUIRES s.mu is held. -func (s *Server) errorf(format string, a ...interface{}) { - if s.events != nil { - s.events.Errorf(format, a...) - } -} - -// RegisterService registers a service and its implementation to the gRPC -// server. It is called from the IDL generated code. This must be called before -// invoking Serve. -func (s *Server) RegisterService(sd *ServiceDesc, ss interface{}) { - ht := reflect.TypeOf(sd.HandlerType).Elem() - st := reflect.TypeOf(ss) - if !st.Implements(ht) { - grpclog.Fatalf("grpc: Server.RegisterService found the handler of type %v that does not satisfy %v", st, ht) - } - s.register(sd, ss) -} - -func (s *Server) register(sd *ServiceDesc, ss interface{}) { - s.mu.Lock() - defer s.mu.Unlock() - s.printf("RegisterService(%q)", sd.ServiceName) - if s.serve { - grpclog.Fatalf("grpc: Server.RegisterService after Server.Serve for %q", sd.ServiceName) - } - if _, ok := s.m[sd.ServiceName]; ok { - grpclog.Fatalf("grpc: Server.RegisterService found duplicate service registration for %q", sd.ServiceName) - } - srv := &service{ - server: ss, - md: make(map[string]*MethodDesc), - sd: make(map[string]*StreamDesc), - mdata: sd.Metadata, - } - for i := range sd.Methods { - d := &sd.Methods[i] - srv.md[d.MethodName] = d - } - for i := range sd.Streams { - d := &sd.Streams[i] - srv.sd[d.StreamName] = d - } - s.m[sd.ServiceName] = srv -} - -// MethodInfo contains the information of an RPC including its method name and type. -type MethodInfo struct { - // Name is the method name only, without the service name or package name. - Name string - // IsClientStream indicates whether the RPC is a client streaming RPC. - IsClientStream bool - // IsServerStream indicates whether the RPC is a server streaming RPC. - IsServerStream bool -} - -// ServiceInfo contains unary RPC method info, streaming RPC method info and metadata for a service. -type ServiceInfo struct { - Methods []MethodInfo - // Metadata is the metadata specified in ServiceDesc when registering service. - Metadata interface{} -} - -// GetServiceInfo returns a map from service names to ServiceInfo. -// Service names include the package names, in the form of .. -func (s *Server) GetServiceInfo() map[string]ServiceInfo { - ret := make(map[string]ServiceInfo) - for n, srv := range s.m { - methods := make([]MethodInfo, 0, len(srv.md)+len(srv.sd)) - for m := range srv.md { - methods = append(methods, MethodInfo{ - Name: m, - IsClientStream: false, - IsServerStream: false, - }) - } - for m, d := range srv.sd { - methods = append(methods, MethodInfo{ - Name: m, - IsClientStream: d.ClientStreams, - IsServerStream: d.ServerStreams, - }) - } - - ret[n] = ServiceInfo{ - Methods: methods, - Metadata: srv.mdata, - } - } - return ret -} - -// ErrServerStopped indicates that the operation is now illegal because of -// the server being stopped. -var ErrServerStopped = errors.New("grpc: the server has been stopped") - -func (s *Server) useTransportAuthenticator(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - if s.opts.creds == nil { - return rawConn, nil, nil - } - return s.opts.creds.ServerHandshake(rawConn) -} - -type listenSocket struct { - net.Listener - channelzID int64 -} - -func (l *listenSocket) ChannelzMetric() *channelz.SocketInternalMetric { - return &channelz.SocketInternalMetric{ - LocalAddr: l.Listener.Addr(), - } -} - -func (l *listenSocket) Close() error { - err := l.Listener.Close() - if channelz.IsOn() { - channelz.RemoveEntry(l.channelzID) - } - return err -} - -// Serve accepts incoming connections on the listener lis, creating a new -// ServerTransport and service goroutine for each. The service goroutines -// read gRPC requests and then call the registered handlers to reply to them. -// Serve returns when lis.Accept fails with fatal errors. lis will be closed when -// this method returns. -// Serve will return a non-nil error unless Stop or GracefulStop is called. -func (s *Server) Serve(lis net.Listener) error { - s.mu.Lock() - s.printf("serving") - s.serve = true - if s.lis == nil { - // Serve called after Stop or GracefulStop. - s.mu.Unlock() - lis.Close() - return ErrServerStopped - } - - s.serveWG.Add(1) - defer func() { - s.serveWG.Done() - select { - // Stop or GracefulStop called; block until done and return nil. - case <-s.quit: - <-s.done - default: - } - }() - - ls := &listenSocket{Listener: lis} - s.lis[ls] = true - - if channelz.IsOn() { - ls.channelzID = channelz.RegisterListenSocket(ls, s.channelzID, "") - } - s.mu.Unlock() - - defer func() { - s.mu.Lock() - if s.lis != nil && s.lis[ls] { - ls.Close() - delete(s.lis, ls) - } - s.mu.Unlock() - }() - - var tempDelay time.Duration // how long to sleep on accept failure - - for { - rawConn, err := lis.Accept() - if err != nil { - if ne, ok := err.(interface { - Temporary() bool - }); ok && ne.Temporary() { - if tempDelay == 0 { - tempDelay = 5 * time.Millisecond - } else { - tempDelay *= 2 - } - if max := 1 * time.Second; tempDelay > max { - tempDelay = max - } - s.mu.Lock() - s.printf("Accept error: %v; retrying in %v", err, tempDelay) - s.mu.Unlock() - timer := time.NewTimer(tempDelay) - select { - case <-timer.C: - case <-s.quit: - timer.Stop() - return nil - } - continue - } - s.mu.Lock() - s.printf("done serving; Accept = %v", err) - s.mu.Unlock() - - select { - case <-s.quit: - return nil - default: - } - return err - } - tempDelay = 0 - // Start a new goroutine to deal with rawConn so we don't stall this Accept - // loop goroutine. - // - // Make sure we account for the goroutine so GracefulStop doesn't nil out - // s.conns before this conn can be added. - s.serveWG.Add(1) - go func() { - s.handleRawConn(rawConn) - s.serveWG.Done() - }() - } -} - -// handleRawConn forks a goroutine to handle a just-accepted connection that -// has not had any I/O performed on it yet. -func (s *Server) handleRawConn(rawConn net.Conn) { - rawConn.SetDeadline(time.Now().Add(s.opts.connectionTimeout)) - conn, authInfo, err := s.useTransportAuthenticator(rawConn) - if err != nil { - s.mu.Lock() - s.errorf("ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err) - s.mu.Unlock() - grpclog.Warningf("grpc: Server.Serve failed to complete security handshake from %q: %v", rawConn.RemoteAddr(), err) - // If serverHandshake returns ErrConnDispatched, keep rawConn open. - if err != credentials.ErrConnDispatched { - rawConn.Close() - } - rawConn.SetDeadline(time.Time{}) - return - } - - s.mu.Lock() - if s.conns == nil { - s.mu.Unlock() - conn.Close() - return - } - s.mu.Unlock() - - var serve func() - c := conn.(io.Closer) - if s.opts.useHandlerImpl { - serve = func() { s.serveUsingHandler(conn) } - } else { - // Finish handshaking (HTTP2) - st := s.newHTTP2Transport(conn, authInfo) - if st == nil { - return - } - c = st - serve = func() { s.serveStreams(st) } - } - - rawConn.SetDeadline(time.Time{}) - if !s.addConn(c) { - return - } - go func() { - serve() - s.removeConn(c) - }() -} - -// newHTTP2Transport sets up a http/2 transport (using the -// gRPC http2 server transport in transport/http2_server.go). -func (s *Server) newHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) transport.ServerTransport { - config := &transport.ServerConfig{ - MaxStreams: s.opts.maxConcurrentStreams, - AuthInfo: authInfo, - InTapHandle: s.opts.inTapHandle, - StatsHandler: s.opts.statsHandler, - KeepaliveParams: s.opts.keepaliveParams, - KeepalivePolicy: s.opts.keepalivePolicy, - InitialWindowSize: s.opts.initialWindowSize, - InitialConnWindowSize: s.opts.initialConnWindowSize, - WriteBufferSize: s.opts.writeBufferSize, - ReadBufferSize: s.opts.readBufferSize, - ChannelzParentID: s.channelzID, - } - st, err := transport.NewServerTransport("http2", c, config) - if err != nil { - s.mu.Lock() - s.errorf("NewServerTransport(%q) failed: %v", c.RemoteAddr(), err) - s.mu.Unlock() - c.Close() - grpclog.Warningln("grpc: Server.Serve failed to create ServerTransport: ", err) - return nil - } - - return st -} - -func (s *Server) serveStreams(st transport.ServerTransport) { - defer st.Close() - var wg sync.WaitGroup - st.HandleStreams(func(stream *transport.Stream) { - wg.Add(1) - go func() { - defer wg.Done() - s.handleStream(st, stream, s.traceInfo(st, stream)) - }() - }, func(ctx context.Context, method string) context.Context { - if !EnableTracing { - return ctx - } - tr := trace.New("grpc.Recv."+methodFamily(method), method) - return trace.NewContext(ctx, tr) - }) - wg.Wait() -} - -var _ http.Handler = (*Server)(nil) - -// serveUsingHandler is called from handleRawConn when s is configured -// to handle requests via the http.Handler interface. It sets up a -// net/http.Server to handle the just-accepted conn. The http.Server -// is configured to route all incoming requests (all HTTP/2 streams) -// to ServeHTTP, which creates a new ServerTransport for each stream. -// serveUsingHandler blocks until conn closes. -// -// This codepath is only used when Server.TestingUseHandlerImpl has -// been configured. This lets the end2end tests exercise the ServeHTTP -// method as one of the environment types. -// -// conn is the *tls.Conn that's already been authenticated. -func (s *Server) serveUsingHandler(conn net.Conn) { - h2s := &http2.Server{ - MaxConcurrentStreams: s.opts.maxConcurrentStreams, - } - h2s.ServeConn(conn, &http2.ServeConnOpts{ - Handler: s, - }) -} - -// ServeHTTP implements the Go standard library's http.Handler -// interface by responding to the gRPC request r, by looking up -// the requested gRPC method in the gRPC server s. -// -// The provided HTTP request must have arrived on an HTTP/2 -// connection. When using the Go standard library's server, -// practically this means that the Request must also have arrived -// over TLS. -// -// To share one port (such as 443 for https) between gRPC and an -// existing http.Handler, use a root http.Handler such as: -// -// if r.ProtoMajor == 2 && strings.HasPrefix( -// r.Header.Get("Content-Type"), "application/grpc") { -// grpcServer.ServeHTTP(w, r) -// } else { -// yourMux.ServeHTTP(w, r) -// } -// -// Note that ServeHTTP uses Go's HTTP/2 server implementation which is totally -// separate from grpc-go's HTTP/2 server. Performance and features may vary -// between the two paths. ServeHTTP does not support some gRPC features -// available through grpc-go's HTTP/2 server, and it is currently EXPERIMENTAL -// and subject to change. -func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { - st, err := transport.NewServerHandlerTransport(w, r, s.opts.statsHandler) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - if !s.addConn(st) { - return - } - defer s.removeConn(st) - s.serveStreams(st) -} - -// traceInfo returns a traceInfo and associates it with stream, if tracing is enabled. -// If tracing is not enabled, it returns nil. -func (s *Server) traceInfo(st transport.ServerTransport, stream *transport.Stream) (trInfo *traceInfo) { - tr, ok := trace.FromContext(stream.Context()) - if !ok { - return nil - } - - trInfo = &traceInfo{ - tr: tr, - } - trInfo.firstLine.client = false - trInfo.firstLine.remoteAddr = st.RemoteAddr() - - if dl, ok := stream.Context().Deadline(); ok { - trInfo.firstLine.deadline = dl.Sub(time.Now()) - } - return trInfo -} - -func (s *Server) addConn(c io.Closer) bool { - s.mu.Lock() - defer s.mu.Unlock() - if s.conns == nil { - c.Close() - return false - } - if s.drain { - // Transport added after we drained our existing conns: drain it - // immediately. - c.(transport.ServerTransport).Drain() - } - s.conns[c] = true - return true -} - -func (s *Server) removeConn(c io.Closer) { - s.mu.Lock() - defer s.mu.Unlock() - if s.conns != nil { - delete(s.conns, c) - s.cv.Broadcast() - } -} - -// ChannelzMetric returns ServerInternalMetric of current server. -// This is an EXPERIMENTAL API. -func (s *Server) ChannelzMetric() *channelz.ServerInternalMetric { - s.czmu.RLock() - defer s.czmu.RUnlock() - return &channelz.ServerInternalMetric{ - CallsStarted: s.callsStarted, - CallsSucceeded: s.callsSucceeded, - CallsFailed: s.callsFailed, - LastCallStartedTimestamp: s.lastCallStartedTime, - } -} - -func (s *Server) incrCallsStarted() { - s.czmu.Lock() - s.callsStarted++ - s.lastCallStartedTime = time.Now() - s.czmu.Unlock() -} - -func (s *Server) incrCallsSucceeded() { - s.czmu.Lock() - s.callsSucceeded++ - s.czmu.Unlock() -} - -func (s *Server) incrCallsFailed() { - s.czmu.Lock() - s.callsFailed++ - s.czmu.Unlock() -} - -func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg interface{}, cp Compressor, opts *transport.Options, comp encoding.Compressor) error { - var ( - outPayload *stats.OutPayload - ) - if s.opts.statsHandler != nil { - outPayload = &stats.OutPayload{} - } - hdr, data, err := encode(s.getCodec(stream.ContentSubtype()), msg, cp, outPayload, comp) - if err != nil { - grpclog.Errorln("grpc: server failed to encode response: ", err) - return err - } - if len(data) > s.opts.maxSendMessageSize { - return status.Errorf(codes.ResourceExhausted, "grpc: trying to send message larger than max (%d vs. %d)", len(data), s.opts.maxSendMessageSize) - } - err = t.Write(stream, hdr, data, opts) - if err == nil && outPayload != nil { - outPayload.SentTime = time.Now() - s.opts.statsHandler.HandleRPC(stream.Context(), outPayload) - } - return err -} - -func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, md *MethodDesc, trInfo *traceInfo) (err error) { - if channelz.IsOn() { - s.incrCallsStarted() - defer func() { - if err != nil && err != io.EOF { - s.incrCallsFailed() - } else { - s.incrCallsSucceeded() - } - }() - } - sh := s.opts.statsHandler - if sh != nil { - beginTime := time.Now() - begin := &stats.Begin{ - BeginTime: beginTime, - } - sh.HandleRPC(stream.Context(), begin) - defer func() { - end := &stats.End{ - BeginTime: beginTime, - EndTime: time.Now(), - } - if err != nil && err != io.EOF { - end.Error = toRPCErr(err) - } - sh.HandleRPC(stream.Context(), end) - }() - } - if trInfo != nil { - defer trInfo.tr.Finish() - trInfo.firstLine.client = false - trInfo.tr.LazyLog(&trInfo.firstLine, false) - defer func() { - if err != nil && err != io.EOF { - trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) - trInfo.tr.SetError() - } - }() - } - - // comp and cp are used for compression. decomp and dc are used for - // decompression. If comp and decomp are both set, they are the same; - // however they are kept separate to ensure that at most one of the - // compressor/decompressor variable pairs are set for use later. - var comp, decomp encoding.Compressor - var cp Compressor - var dc Decompressor - - // If dc is set and matches the stream's compression, use it. Otherwise, try - // to find a matching registered compressor for decomp. - if rc := stream.RecvCompress(); s.opts.dc != nil && s.opts.dc.Type() == rc { - dc = s.opts.dc - } else if rc != "" && rc != encoding.Identity { - decomp = encoding.GetCompressor(rc) - if decomp == nil { - st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc) - t.WriteStatus(stream, st) - return st.Err() - } - } - - // If cp is set, use it. Otherwise, attempt to compress the response using - // the incoming message compression method. - // - // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686. - if s.opts.cp != nil { - cp = s.opts.cp - stream.SetSendCompress(cp.Type()) - } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity { - // Legacy compressor not specified; attempt to respond with same encoding. - comp = encoding.GetCompressor(rc) - if comp != nil { - stream.SetSendCompress(rc) - } - } - - p := &parser{r: stream} - pf, req, err := p.recvMsg(s.opts.maxReceiveMessageSize) - if err == io.EOF { - // The entire stream is done (for unary RPC only). - return err - } - if err == io.ErrUnexpectedEOF { - err = status.Errorf(codes.Internal, io.ErrUnexpectedEOF.Error()) - } - if err != nil { - if st, ok := status.FromError(err); ok { - if e := t.WriteStatus(stream, st); e != nil { - grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status %v", e) - } - } else { - switch st := err.(type) { - case transport.ConnectionError: - // Nothing to do here. - case transport.StreamError: - if e := t.WriteStatus(stream, status.New(st.Code, st.Desc)); e != nil { - grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status %v", e) - } - default: - panic(fmt.Sprintf("grpc: Unexpected error (%T) from recvMsg: %v", st, st)) - } - } - return err - } - if channelz.IsOn() { - t.IncrMsgRecv() - } - if st := checkRecvPayload(pf, stream.RecvCompress(), dc != nil || decomp != nil); st != nil { - if e := t.WriteStatus(stream, st); e != nil { - grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status %v", e) - } - return st.Err() - } - var inPayload *stats.InPayload - if sh != nil { - inPayload = &stats.InPayload{ - RecvTime: time.Now(), - } - } - df := func(v interface{}) error { - if inPayload != nil { - inPayload.WireLength = len(req) - } - if pf == compressionMade { - var err error - if dc != nil { - req, err = dc.Do(bytes.NewReader(req)) - if err != nil { - return status.Errorf(codes.Internal, err.Error()) - } - } else { - tmp, _ := decomp.Decompress(bytes.NewReader(req)) - req, err = ioutil.ReadAll(tmp) - if err != nil { - return status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) - } - } - } - if len(req) > s.opts.maxReceiveMessageSize { - // TODO: Revisit the error code. Currently keep it consistent with - // java implementation. - return status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", len(req), s.opts.maxReceiveMessageSize) - } - if err := s.getCodec(stream.ContentSubtype()).Unmarshal(req, v); err != nil { - return status.Errorf(codes.Internal, "grpc: error unmarshalling request: %v", err) - } - if inPayload != nil { - inPayload.Payload = v - inPayload.Data = req - inPayload.Length = len(req) - sh.HandleRPC(stream.Context(), inPayload) - } - if trInfo != nil { - trInfo.tr.LazyLog(&payload{sent: false, msg: v}, true) - } - return nil - } - ctx := NewContextWithServerTransportStream(stream.Context(), stream) - reply, appErr := md.Handler(srv.server, ctx, df, s.opts.unaryInt) - if appErr != nil { - appStatus, ok := status.FromError(appErr) - if !ok { - // Convert appErr if it is not a grpc status error. - appErr = status.Error(codes.Unknown, appErr.Error()) - appStatus, _ = status.FromError(appErr) - } - if trInfo != nil { - trInfo.tr.LazyLog(stringer(appStatus.Message()), true) - trInfo.tr.SetError() - } - if e := t.WriteStatus(stream, appStatus); e != nil { - grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status: %v", e) - } - return appErr - } - if trInfo != nil { - trInfo.tr.LazyLog(stringer("OK"), false) - } - opts := &transport.Options{ - Last: true, - Delay: false, - } - - if err := s.sendResponse(t, stream, reply, cp, opts, comp); err != nil { - if err == io.EOF { - // The entire stream is done (for unary RPC only). - return err - } - if s, ok := status.FromError(err); ok { - if e := t.WriteStatus(stream, s); e != nil { - grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status: %v", e) - } - } else { - switch st := err.(type) { - case transport.ConnectionError: - // Nothing to do here. - case transport.StreamError: - if e := t.WriteStatus(stream, status.New(st.Code, st.Desc)); e != nil { - grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status %v", e) - } - default: - panic(fmt.Sprintf("grpc: Unexpected error (%T) from sendResponse: %v", st, st)) - } - } - return err - } - if channelz.IsOn() { - t.IncrMsgSent() - } - if trInfo != nil { - trInfo.tr.LazyLog(&payload{sent: true, msg: reply}, true) - } - // TODO: Should we be logging if writing status failed here, like above? - // Should the logging be in WriteStatus? Should we ignore the WriteStatus - // error or allow the stats handler to see it? - return t.WriteStatus(stream, status.New(codes.OK, "")) -} - -func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, sd *StreamDesc, trInfo *traceInfo) (err error) { - if channelz.IsOn() { - s.incrCallsStarted() - defer func() { - if err != nil && err != io.EOF { - s.incrCallsFailed() - } else { - s.incrCallsSucceeded() - } - }() - } - sh := s.opts.statsHandler - if sh != nil { - beginTime := time.Now() - begin := &stats.Begin{ - BeginTime: beginTime, - } - sh.HandleRPC(stream.Context(), begin) - defer func() { - end := &stats.End{ - BeginTime: beginTime, - EndTime: time.Now(), - } - if err != nil && err != io.EOF { - end.Error = toRPCErr(err) - } - sh.HandleRPC(stream.Context(), end) - }() - } - ctx := NewContextWithServerTransportStream(stream.Context(), stream) - ss := &serverStream{ - ctx: ctx, - t: t, - s: stream, - p: &parser{r: stream}, - codec: s.getCodec(stream.ContentSubtype()), - maxReceiveMessageSize: s.opts.maxReceiveMessageSize, - maxSendMessageSize: s.opts.maxSendMessageSize, - trInfo: trInfo, - statsHandler: sh, - } - - // If dc is set and matches the stream's compression, use it. Otherwise, try - // to find a matching registered compressor for decomp. - if rc := stream.RecvCompress(); s.opts.dc != nil && s.opts.dc.Type() == rc { - ss.dc = s.opts.dc - } else if rc != "" && rc != encoding.Identity { - ss.decomp = encoding.GetCompressor(rc) - if ss.decomp == nil { - st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc) - t.WriteStatus(ss.s, st) - return st.Err() - } - } - - // If cp is set, use it. Otherwise, attempt to compress the response using - // the incoming message compression method. - // - // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686. - if s.opts.cp != nil { - ss.cp = s.opts.cp - stream.SetSendCompress(s.opts.cp.Type()) - } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity { - // Legacy compressor not specified; attempt to respond with same encoding. - ss.comp = encoding.GetCompressor(rc) - if ss.comp != nil { - stream.SetSendCompress(rc) - } - } - - if trInfo != nil { - trInfo.tr.LazyLog(&trInfo.firstLine, false) - defer func() { - ss.mu.Lock() - if err != nil && err != io.EOF { - ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) - ss.trInfo.tr.SetError() - } - ss.trInfo.tr.Finish() - ss.trInfo.tr = nil - ss.mu.Unlock() - }() - } - var appErr error - var server interface{} - if srv != nil { - server = srv.server - } - if s.opts.streamInt == nil { - appErr = sd.Handler(server, ss) - } else { - info := &StreamServerInfo{ - FullMethod: stream.Method(), - IsClientStream: sd.ClientStreams, - IsServerStream: sd.ServerStreams, - } - appErr = s.opts.streamInt(server, ss, info, sd.Handler) - } - if appErr != nil { - appStatus, ok := status.FromError(appErr) - if !ok { - switch err := appErr.(type) { - case transport.StreamError: - appStatus = status.New(err.Code, err.Desc) - default: - appStatus = status.New(codes.Unknown, appErr.Error()) - } - appErr = appStatus.Err() - } - if trInfo != nil { - ss.mu.Lock() - ss.trInfo.tr.LazyLog(stringer(appStatus.Message()), true) - ss.trInfo.tr.SetError() - ss.mu.Unlock() - } - t.WriteStatus(ss.s, appStatus) - // TODO: Should we log an error from WriteStatus here and below? - return appErr - } - if trInfo != nil { - ss.mu.Lock() - ss.trInfo.tr.LazyLog(stringer("OK"), false) - ss.mu.Unlock() - } - return t.WriteStatus(ss.s, status.New(codes.OK, "")) -} - -func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Stream, trInfo *traceInfo) { - sm := stream.Method() - if sm != "" && sm[0] == '/' { - sm = sm[1:] - } - pos := strings.LastIndex(sm, "/") - if pos == -1 { - if trInfo != nil { - trInfo.tr.LazyLog(&fmtStringer{"Malformed method name %q", []interface{}{sm}}, true) - trInfo.tr.SetError() - } - errDesc := fmt.Sprintf("malformed method name: %q", stream.Method()) - if err := t.WriteStatus(stream, status.New(codes.ResourceExhausted, errDesc)); err != nil { - if trInfo != nil { - trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) - trInfo.tr.SetError() - } - grpclog.Warningf("grpc: Server.handleStream failed to write status: %v", err) - } - if trInfo != nil { - trInfo.tr.Finish() - } - return - } - service := sm[:pos] - method := sm[pos+1:] - srv, ok := s.m[service] - if !ok { - if unknownDesc := s.opts.unknownStreamDesc; unknownDesc != nil { - s.processStreamingRPC(t, stream, nil, unknownDesc, trInfo) - return - } - if trInfo != nil { - trInfo.tr.LazyLog(&fmtStringer{"Unknown service %v", []interface{}{service}}, true) - trInfo.tr.SetError() - } - errDesc := fmt.Sprintf("unknown service %v", service) - if err := t.WriteStatus(stream, status.New(codes.Unimplemented, errDesc)); err != nil { - if trInfo != nil { - trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) - trInfo.tr.SetError() - } - grpclog.Warningf("grpc: Server.handleStream failed to write status: %v", err) - } - if trInfo != nil { - trInfo.tr.Finish() - } - return - } - // Unary RPC or Streaming RPC? - if md, ok := srv.md[method]; ok { - s.processUnaryRPC(t, stream, srv, md, trInfo) - return - } - if sd, ok := srv.sd[method]; ok { - s.processStreamingRPC(t, stream, srv, sd, trInfo) - return - } - if trInfo != nil { - trInfo.tr.LazyLog(&fmtStringer{"Unknown method %v", []interface{}{method}}, true) - trInfo.tr.SetError() - } - if unknownDesc := s.opts.unknownStreamDesc; unknownDesc != nil { - s.processStreamingRPC(t, stream, nil, unknownDesc, trInfo) - return - } - errDesc := fmt.Sprintf("unknown method %v", method) - if err := t.WriteStatus(stream, status.New(codes.Unimplemented, errDesc)); err != nil { - if trInfo != nil { - trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) - trInfo.tr.SetError() - } - grpclog.Warningf("grpc: Server.handleStream failed to write status: %v", err) - } - if trInfo != nil { - trInfo.tr.Finish() - } -} - -// The key to save ServerTransportStream in the context. -type streamKey struct{} - -// NewContextWithServerTransportStream creates a new context from ctx and -// attaches stream to it. -// -// This API is EXPERIMENTAL. -func NewContextWithServerTransportStream(ctx context.Context, stream ServerTransportStream) context.Context { - return context.WithValue(ctx, streamKey{}, stream) -} - -// ServerTransportStream is a minimal interface that a transport stream must -// implement. This can be used to mock an actual transport stream for tests of -// handler code that use, for example, grpc.SetHeader (which requires some -// stream to be in context). -// -// See also NewContextWithServerTransportStream. -// -// This API is EXPERIMENTAL. -type ServerTransportStream interface { - Method() string - SetHeader(md metadata.MD) error - SendHeader(md metadata.MD) error - SetTrailer(md metadata.MD) error -} - -// ServerTransportStreamFromContext returns the ServerTransportStream saved in -// ctx. Returns nil if the given context has no stream associated with it -// (which implies it is not an RPC invocation context). -// -// This API is EXPERIMENTAL. -func ServerTransportStreamFromContext(ctx context.Context) ServerTransportStream { - s, _ := ctx.Value(streamKey{}).(ServerTransportStream) - return s -} - -// Stop stops the gRPC server. It immediately closes all open -// connections and listeners. -// It cancels all active RPCs on the server side and the corresponding -// pending RPCs on the client side will get notified by connection -// errors. -func (s *Server) Stop() { - s.quitOnce.Do(func() { - close(s.quit) - }) - - defer func() { - s.serveWG.Wait() - s.doneOnce.Do(func() { - close(s.done) - }) - }() - - s.channelzRemoveOnce.Do(func() { - if channelz.IsOn() { - channelz.RemoveEntry(s.channelzID) - } - }) - - s.mu.Lock() - listeners := s.lis - s.lis = nil - st := s.conns - s.conns = nil - // interrupt GracefulStop if Stop and GracefulStop are called concurrently. - s.cv.Broadcast() - s.mu.Unlock() - - for lis := range listeners { - lis.Close() - } - for c := range st { - c.Close() - } - - s.mu.Lock() - if s.events != nil { - s.events.Finish() - s.events = nil - } - s.mu.Unlock() -} - -// GracefulStop stops the gRPC server gracefully. It stops the server from -// accepting new connections and RPCs and blocks until all the pending RPCs are -// finished. -func (s *Server) GracefulStop() { - s.quitOnce.Do(func() { - close(s.quit) - }) - - defer func() { - s.doneOnce.Do(func() { - close(s.done) - }) - }() - - s.channelzRemoveOnce.Do(func() { - if channelz.IsOn() { - channelz.RemoveEntry(s.channelzID) - } - }) - s.mu.Lock() - if s.conns == nil { - s.mu.Unlock() - return - } - - for lis := range s.lis { - lis.Close() - } - s.lis = nil - if !s.drain { - for c := range s.conns { - c.(transport.ServerTransport).Drain() - } - s.drain = true - } - - // Wait for serving threads to be ready to exit. Only then can we be sure no - // new conns will be created. - s.mu.Unlock() - s.serveWG.Wait() - s.mu.Lock() - - for len(s.conns) != 0 { - s.cv.Wait() - } - s.conns = nil - if s.events != nil { - s.events.Finish() - s.events = nil - } - s.mu.Unlock() -} - -func init() { - internal.TestingUseHandlerImpl = func(arg interface{}) { - arg.(*Server).opts.useHandlerImpl = true - } -} - -// contentSubtype must be lowercase -// cannot return nil -func (s *Server) getCodec(contentSubtype string) baseCodec { - if s.opts.codec != nil { - return s.opts.codec - } - if contentSubtype == "" { - return encoding.GetCodec(proto.Name) - } - codec := encoding.GetCodec(contentSubtype) - if codec == nil { - return encoding.GetCodec(proto.Name) - } - return codec -} - -// SetHeader sets the header metadata. -// When called multiple times, all the provided metadata will be merged. -// All the metadata will be sent out when one of the following happens: -// - grpc.SendHeader() is called; -// - The first response is sent out; -// - An RPC status is sent out (error or success). -func SetHeader(ctx context.Context, md metadata.MD) error { - if md.Len() == 0 { - return nil - } - stream := ServerTransportStreamFromContext(ctx) - if stream == nil { - return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx) - } - return stream.SetHeader(md) -} - -// SendHeader sends header metadata. It may be called at most once. -// The provided md and headers set by SetHeader() will be sent. -func SendHeader(ctx context.Context, md metadata.MD) error { - stream := ServerTransportStreamFromContext(ctx) - if stream == nil { - return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx) - } - if err := stream.SendHeader(md); err != nil { - return toRPCErr(err) - } - return nil -} - -// SetTrailer sets the trailer metadata that will be sent when an RPC returns. -// When called more than once, all the provided metadata will be merged. -func SetTrailer(ctx context.Context, md metadata.MD) error { - if md.Len() == 0 { - return nil - } - stream := ServerTransportStreamFromContext(ctx) - if stream == nil { - return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx) - } - return stream.SetTrailer(md) -} - -// Method returns the method string for the server context. The returned -// string is in the format of "/service/method". -func Method(ctx context.Context) (string, bool) { - s := ServerTransportStreamFromContext(ctx) - if s == nil { - return "", false - } - return s.Method(), true -} diff --git a/vendor/google.golang.org/grpc/service_config.go b/vendor/google.golang.org/grpc/service_config.go deleted file mode 100644 index 015631d8d38..00000000000 --- a/vendor/google.golang.org/grpc/service_config.go +++ /dev/null @@ -1,233 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 grpc - -import ( - "encoding/json" - "fmt" - "strconv" - "strings" - "time" - - "google.golang.org/grpc/grpclog" -) - -const maxInt = int(^uint(0) >> 1) - -// MethodConfig defines the configuration recommended by the service providers for a -// particular method. -// -// Deprecated: Users should not use this struct. Service config should be received -// through name resolver, as specified here -// https://github.com/grpc/grpc/blob/master/doc/service_config.md -type MethodConfig struct { - // WaitForReady indicates whether RPCs sent to this method should wait until - // the connection is ready by default (!failfast). The value specified via the - // gRPC client API will override the value set here. - WaitForReady *bool - // Timeout is the default timeout for RPCs sent to this method. The actual - // deadline used will be the minimum of the value specified here and the value - // set by the application via the gRPC client API. If either one is not set, - // then the other will be used. If neither is set, then the RPC has no deadline. - Timeout *time.Duration - // MaxReqSize is the maximum allowed payload size for an individual request in a - // stream (client->server) in bytes. The size which is measured is the serialized - // payload after per-message compression (but before stream compression) in bytes. - // The actual value used is the minimum of the value specified here and the value set - // by the application via the gRPC client API. If either one is not set, then the other - // will be used. If neither is set, then the built-in default is used. - MaxReqSize *int - // MaxRespSize is the maximum allowed payload size for an individual response in a - // stream (server->client) in bytes. - MaxRespSize *int -} - -// ServiceConfig is provided by the service provider and contains parameters for how -// clients that connect to the service should behave. -// -// Deprecated: Users should not use this struct. Service config should be received -// through name resolver, as specified here -// https://github.com/grpc/grpc/blob/master/doc/service_config.md -type ServiceConfig struct { - // LB is the load balancer the service providers recommends. The balancer specified - // via grpc.WithBalancer will override this. - LB *string - // Methods contains a map for the methods in this service. - // If there is an exact match for a method (i.e. /service/method) in the map, use the corresponding MethodConfig. - // If there's no exact match, look for the default config for the service (/service/) and use the corresponding MethodConfig if it exists. - // Otherwise, the method has no MethodConfig to use. - Methods map[string]MethodConfig - - stickinessMetadataKey *string -} - -func parseDuration(s *string) (*time.Duration, error) { - if s == nil { - return nil, nil - } - if !strings.HasSuffix(*s, "s") { - return nil, fmt.Errorf("malformed duration %q", *s) - } - ss := strings.SplitN((*s)[:len(*s)-1], ".", 3) - if len(ss) > 2 { - return nil, fmt.Errorf("malformed duration %q", *s) - } - // hasDigits is set if either the whole or fractional part of the number is - // present, since both are optional but one is required. - hasDigits := false - var d time.Duration - if len(ss[0]) > 0 { - i, err := strconv.ParseInt(ss[0], 10, 32) - if err != nil { - return nil, fmt.Errorf("malformed duration %q: %v", *s, err) - } - d = time.Duration(i) * time.Second - hasDigits = true - } - if len(ss) == 2 && len(ss[1]) > 0 { - if len(ss[1]) > 9 { - return nil, fmt.Errorf("malformed duration %q", *s) - } - f, err := strconv.ParseInt(ss[1], 10, 64) - if err != nil { - return nil, fmt.Errorf("malformed duration %q: %v", *s, err) - } - for i := 9; i > len(ss[1]); i-- { - f *= 10 - } - d += time.Duration(f) - hasDigits = true - } - if !hasDigits { - return nil, fmt.Errorf("malformed duration %q", *s) - } - - return &d, nil -} - -type jsonName struct { - Service *string - Method *string -} - -func (j jsonName) generatePath() (string, bool) { - if j.Service == nil { - return "", false - } - res := "/" + *j.Service + "/" - if j.Method != nil { - res += *j.Method - } - return res, true -} - -// TODO(lyuxuan): delete this struct after cleaning up old service config implementation. -type jsonMC struct { - Name *[]jsonName - WaitForReady *bool - Timeout *string - MaxRequestMessageBytes *int64 - MaxResponseMessageBytes *int64 -} - -// TODO(lyuxuan): delete this struct after cleaning up old service config implementation. -type jsonSC struct { - LoadBalancingPolicy *string - StickinessMetadataKey *string - MethodConfig *[]jsonMC -} - -func parseServiceConfig(js string) (ServiceConfig, error) { - var rsc jsonSC - err := json.Unmarshal([]byte(js), &rsc) - if err != nil { - grpclog.Warningf("grpc: parseServiceConfig error unmarshaling %s due to %v", js, err) - return ServiceConfig{}, err - } - sc := ServiceConfig{ - LB: rsc.LoadBalancingPolicy, - Methods: make(map[string]MethodConfig), - - stickinessMetadataKey: rsc.StickinessMetadataKey, - } - if rsc.MethodConfig == nil { - return sc, nil - } - - for _, m := range *rsc.MethodConfig { - if m.Name == nil { - continue - } - d, err := parseDuration(m.Timeout) - if err != nil { - grpclog.Warningf("grpc: parseServiceConfig error unmarshaling %s due to %v", js, err) - return ServiceConfig{}, err - } - - mc := MethodConfig{ - WaitForReady: m.WaitForReady, - Timeout: d, - } - if m.MaxRequestMessageBytes != nil { - if *m.MaxRequestMessageBytes > int64(maxInt) { - mc.MaxReqSize = newInt(maxInt) - } else { - mc.MaxReqSize = newInt(int(*m.MaxRequestMessageBytes)) - } - } - if m.MaxResponseMessageBytes != nil { - if *m.MaxResponseMessageBytes > int64(maxInt) { - mc.MaxRespSize = newInt(maxInt) - } else { - mc.MaxRespSize = newInt(int(*m.MaxResponseMessageBytes)) - } - } - for _, n := range *m.Name { - if path, valid := n.generatePath(); valid { - sc.Methods[path] = mc - } - } - } - - return sc, nil -} - -func min(a, b *int) *int { - if *a < *b { - return a - } - return b -} - -func getMaxSize(mcMax, doptMax *int, defaultVal int) *int { - if mcMax == nil && doptMax == nil { - return &defaultVal - } - if mcMax != nil && doptMax != nil { - return min(mcMax, doptMax) - } - if mcMax != nil { - return mcMax - } - return doptMax -} - -func newInt(b int) *int { - return &b -} diff --git a/vendor/google.golang.org/grpc/stats/handlers.go b/vendor/google.golang.org/grpc/stats/handlers.go deleted file mode 100644 index 05b384c6931..00000000000 --- a/vendor/google.golang.org/grpc/stats/handlers.go +++ /dev/null @@ -1,64 +0,0 @@ -/* - * - * Copyright 2016 gRPC 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 stats - -import ( - "net" - - "golang.org/x/net/context" -) - -// ConnTagInfo defines the relevant information needed by connection context tagger. -type ConnTagInfo struct { - // RemoteAddr is the remote address of the corresponding connection. - RemoteAddr net.Addr - // LocalAddr is the local address of the corresponding connection. - LocalAddr net.Addr -} - -// RPCTagInfo defines the relevant information needed by RPC context tagger. -type RPCTagInfo struct { - // FullMethodName is the RPC method in the format of /package.service/method. - FullMethodName string - // FailFast indicates if this RPC is failfast. - // This field is only valid on client side, it's always false on server side. - FailFast bool -} - -// Handler defines the interface for the related stats handling (e.g., RPCs, connections). -type Handler interface { - // TagRPC can attach some information to the given context. - // The context used for the rest lifetime of the RPC will be derived from - // the returned context. - TagRPC(context.Context, *RPCTagInfo) context.Context - // HandleRPC processes the RPC stats. - HandleRPC(context.Context, RPCStats) - - // TagConn can attach some information to the given context. - // The returned context will be used for stats handling. - // For conn stats handling, the context used in HandleConn for this - // connection will be derived from the context returned. - // For RPC stats handling, - // - On server side, the context used in HandleRPC for all RPCs on this - // connection will be derived from the context returned. - // - On client side, the context is not derived from the context returned. - TagConn(context.Context, *ConnTagInfo) context.Context - // HandleConn processes the Conn stats. - HandleConn(context.Context, ConnStats) -} diff --git a/vendor/google.golang.org/grpc/stats/stats.go b/vendor/google.golang.org/grpc/stats/stats.go deleted file mode 100644 index 3f13190a0ac..00000000000 --- a/vendor/google.golang.org/grpc/stats/stats.go +++ /dev/null @@ -1,296 +0,0 @@ -/* - * - * Copyright 2016 gRPC 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. - * - */ - -//go:generate protoc --go_out=plugins=grpc:. grpc_testing/test.proto - -// Package stats is for collecting and reporting various network and RPC stats. -// This package is for monitoring purpose only. All fields are read-only. -// All APIs are experimental. -package stats // import "google.golang.org/grpc/stats" - -import ( - "net" - "time" - - "golang.org/x/net/context" -) - -// RPCStats contains stats information about RPCs. -type RPCStats interface { - isRPCStats() - // IsClient returns true if this RPCStats is from client side. - IsClient() bool -} - -// Begin contains stats when an RPC begins. -// FailFast is only valid if this Begin is from client side. -type Begin struct { - // Client is true if this Begin is from client side. - Client bool - // BeginTime is the time when the RPC begins. - BeginTime time.Time - // FailFast indicates if this RPC is failfast. - FailFast bool -} - -// IsClient indicates if the stats information is from client side. -func (s *Begin) IsClient() bool { return s.Client } - -func (s *Begin) isRPCStats() {} - -// InPayload contains the information for an incoming payload. -type InPayload struct { - // Client is true if this InPayload is from client side. - Client bool - // Payload is the payload with original type. - Payload interface{} - // Data is the serialized message payload. - Data []byte - // Length is the length of uncompressed data. - Length int - // WireLength is the length of data on wire (compressed, signed, encrypted). - WireLength int - // RecvTime is the time when the payload is received. - RecvTime time.Time -} - -// IsClient indicates if the stats information is from client side. -func (s *InPayload) IsClient() bool { return s.Client } - -func (s *InPayload) isRPCStats() {} - -// InHeader contains stats when a header is received. -type InHeader struct { - // Client is true if this InHeader is from client side. - Client bool - // WireLength is the wire length of header. - WireLength int - - // The following fields are valid only if Client is false. - // FullMethod is the full RPC method string, i.e., /package.service/method. - FullMethod string - // RemoteAddr is the remote address of the corresponding connection. - RemoteAddr net.Addr - // LocalAddr is the local address of the corresponding connection. - LocalAddr net.Addr - // Compression is the compression algorithm used for the RPC. - Compression string -} - -// IsClient indicates if the stats information is from client side. -func (s *InHeader) IsClient() bool { return s.Client } - -func (s *InHeader) isRPCStats() {} - -// InTrailer contains stats when a trailer is received. -type InTrailer struct { - // Client is true if this InTrailer is from client side. - Client bool - // WireLength is the wire length of trailer. - WireLength int -} - -// IsClient indicates if the stats information is from client side. -func (s *InTrailer) IsClient() bool { return s.Client } - -func (s *InTrailer) isRPCStats() {} - -// OutPayload contains the information for an outgoing payload. -type OutPayload struct { - // Client is true if this OutPayload is from client side. - Client bool - // Payload is the payload with original type. - Payload interface{} - // Data is the serialized message payload. - Data []byte - // Length is the length of uncompressed data. - Length int - // WireLength is the length of data on wire (compressed, signed, encrypted). - WireLength int - // SentTime is the time when the payload is sent. - SentTime time.Time -} - -// IsClient indicates if this stats information is from client side. -func (s *OutPayload) IsClient() bool { return s.Client } - -func (s *OutPayload) isRPCStats() {} - -// OutHeader contains stats when a header is sent. -type OutHeader struct { - // Client is true if this OutHeader is from client side. - Client bool - - // The following fields are valid only if Client is true. - // FullMethod is the full RPC method string, i.e., /package.service/method. - FullMethod string - // RemoteAddr is the remote address of the corresponding connection. - RemoteAddr net.Addr - // LocalAddr is the local address of the corresponding connection. - LocalAddr net.Addr - // Compression is the compression algorithm used for the RPC. - Compression string -} - -// IsClient indicates if this stats information is from client side. -func (s *OutHeader) IsClient() bool { return s.Client } - -func (s *OutHeader) isRPCStats() {} - -// OutTrailer contains stats when a trailer is sent. -type OutTrailer struct { - // Client is true if this OutTrailer is from client side. - Client bool - // WireLength is the wire length of trailer. - WireLength int -} - -// IsClient indicates if this stats information is from client side. -func (s *OutTrailer) IsClient() bool { return s.Client } - -func (s *OutTrailer) isRPCStats() {} - -// End contains stats when an RPC ends. -type End struct { - // Client is true if this End is from client side. - Client bool - // BeginTime is the time when the RPC began. - BeginTime time.Time - // EndTime is the time when the RPC ends. - EndTime time.Time - // Error is the error the RPC ended with. It is an error generated from - // status.Status and can be converted back to status.Status using - // status.FromError if non-nil. - Error error -} - -// IsClient indicates if this is from client side. -func (s *End) IsClient() bool { return s.Client } - -func (s *End) isRPCStats() {} - -// ConnStats contains stats information about connections. -type ConnStats interface { - isConnStats() - // IsClient returns true if this ConnStats is from client side. - IsClient() bool -} - -// ConnBegin contains the stats of a connection when it is established. -type ConnBegin struct { - // Client is true if this ConnBegin is from client side. - Client bool -} - -// IsClient indicates if this is from client side. -func (s *ConnBegin) IsClient() bool { return s.Client } - -func (s *ConnBegin) isConnStats() {} - -// ConnEnd contains the stats of a connection when it ends. -type ConnEnd struct { - // Client is true if this ConnEnd is from client side. - Client bool -} - -// IsClient indicates if this is from client side. -func (s *ConnEnd) IsClient() bool { return s.Client } - -func (s *ConnEnd) isConnStats() {} - -type incomingTagsKey struct{} -type outgoingTagsKey struct{} - -// SetTags attaches stats tagging data to the context, which will be sent in -// the outgoing RPC with the header grpc-tags-bin. Subsequent calls to -// SetTags will overwrite the values from earlier calls. -// -// NOTE: this is provided only for backward compatibility with existing clients -// and will likely be removed in an upcoming release. New uses should transmit -// this type of data using metadata with a different, non-reserved (i.e. does -// not begin with "grpc-") header name. -func SetTags(ctx context.Context, b []byte) context.Context { - return context.WithValue(ctx, outgoingTagsKey{}, b) -} - -// Tags returns the tags from the context for the inbound RPC. -// -// NOTE: this is provided only for backward compatibility with existing clients -// and will likely be removed in an upcoming release. New uses should transmit -// this type of data using metadata with a different, non-reserved (i.e. does -// not begin with "grpc-") header name. -func Tags(ctx context.Context) []byte { - b, _ := ctx.Value(incomingTagsKey{}).([]byte) - return b -} - -// SetIncomingTags attaches stats tagging data to the context, to be read by -// the application (not sent in outgoing RPCs). -// -// This is intended for gRPC-internal use ONLY. -func SetIncomingTags(ctx context.Context, b []byte) context.Context { - return context.WithValue(ctx, incomingTagsKey{}, b) -} - -// OutgoingTags returns the tags from the context for the outbound RPC. -// -// This is intended for gRPC-internal use ONLY. -func OutgoingTags(ctx context.Context) []byte { - b, _ := ctx.Value(outgoingTagsKey{}).([]byte) - return b -} - -type incomingTraceKey struct{} -type outgoingTraceKey struct{} - -// SetTrace attaches stats tagging data to the context, which will be sent in -// the outgoing RPC with the header grpc-trace-bin. Subsequent calls to -// SetTrace will overwrite the values from earlier calls. -// -// NOTE: this is provided only for backward compatibility with existing clients -// and will likely be removed in an upcoming release. New uses should transmit -// this type of data using metadata with a different, non-reserved (i.e. does -// not begin with "grpc-") header name. -func SetTrace(ctx context.Context, b []byte) context.Context { - return context.WithValue(ctx, outgoingTraceKey{}, b) -} - -// Trace returns the trace from the context for the inbound RPC. -// -// NOTE: this is provided only for backward compatibility with existing clients -// and will likely be removed in an upcoming release. New uses should transmit -// this type of data using metadata with a different, non-reserved (i.e. does -// not begin with "grpc-") header name. -func Trace(ctx context.Context) []byte { - b, _ := ctx.Value(incomingTraceKey{}).([]byte) - return b -} - -// SetIncomingTrace attaches stats tagging data to the context, to be read by -// the application (not sent in outgoing RPCs). It is intended for -// gRPC-internal use. -func SetIncomingTrace(ctx context.Context, b []byte) context.Context { - return context.WithValue(ctx, incomingTraceKey{}, b) -} - -// OutgoingTrace returns the trace from the context for the outbound RPC. It is -// intended for gRPC-internal use. -func OutgoingTrace(ctx context.Context) []byte { - b, _ := ctx.Value(outgoingTraceKey{}).([]byte) - return b -} diff --git a/vendor/google.golang.org/grpc/status/status.go b/vendor/google.golang.org/grpc/status/status.go deleted file mode 100644 index 9c61b094508..00000000000 --- a/vendor/google.golang.org/grpc/status/status.go +++ /dev/null @@ -1,189 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 status implements errors returned by gRPC. These errors are -// serialized and transmitted on the wire between server and client, and allow -// for additional data to be transmitted via the Details field in the status -// proto. gRPC service handlers should return an error created by this -// package, and gRPC clients should expect a corresponding error to be -// returned from the RPC call. -// -// This package upholds the invariants that a non-nil error may not -// contain an OK code, and an OK code must result in a nil error. -package status - -import ( - "errors" - "fmt" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes" - spb "google.golang.org/genproto/googleapis/rpc/status" - "google.golang.org/grpc/codes" -) - -// statusError is an alias of a status proto. It implements error and Status, -// and a nil statusError should never be returned by this package. -type statusError spb.Status - -func (se *statusError) Error() string { - p := (*spb.Status)(se) - return fmt.Sprintf("rpc error: code = %s desc = %s", codes.Code(p.GetCode()), p.GetMessage()) -} - -func (se *statusError) GRPCStatus() *Status { - return &Status{s: (*spb.Status)(se)} -} - -// Status represents an RPC status code, message, and details. It is immutable -// and should be created with New, Newf, or FromProto. -type Status struct { - s *spb.Status -} - -// Code returns the status code contained in s. -func (s *Status) Code() codes.Code { - if s == nil || s.s == nil { - return codes.OK - } - return codes.Code(s.s.Code) -} - -// Message returns the message contained in s. -func (s *Status) Message() string { - if s == nil || s.s == nil { - return "" - } - return s.s.Message -} - -// Proto returns s's status as an spb.Status proto message. -func (s *Status) Proto() *spb.Status { - if s == nil { - return nil - } - return proto.Clone(s.s).(*spb.Status) -} - -// Err returns an immutable error representing s; returns nil if s.Code() is -// OK. -func (s *Status) Err() error { - if s.Code() == codes.OK { - return nil - } - return (*statusError)(s.s) -} - -// New returns a Status representing c and msg. -func New(c codes.Code, msg string) *Status { - return &Status{s: &spb.Status{Code: int32(c), Message: msg}} -} - -// Newf returns New(c, fmt.Sprintf(format, a...)). -func Newf(c codes.Code, format string, a ...interface{}) *Status { - return New(c, fmt.Sprintf(format, a...)) -} - -// Error returns an error representing c and msg. If c is OK, returns nil. -func Error(c codes.Code, msg string) error { - return New(c, msg).Err() -} - -// Errorf returns Error(c, fmt.Sprintf(format, a...)). -func Errorf(c codes.Code, format string, a ...interface{}) error { - return Error(c, fmt.Sprintf(format, a...)) -} - -// ErrorProto returns an error representing s. If s.Code is OK, returns nil. -func ErrorProto(s *spb.Status) error { - return FromProto(s).Err() -} - -// FromProto returns a Status representing s. -func FromProto(s *spb.Status) *Status { - return &Status{s: proto.Clone(s).(*spb.Status)} -} - -// FromError returns a Status representing err if it was produced from this -// package or has a method `GRPCStatus() *Status`. Otherwise, ok is false and a -// Status is returned with codes.Unknown and the original error message. -func FromError(err error) (s *Status, ok bool) { - if err == nil { - return &Status{s: &spb.Status{Code: int32(codes.OK)}}, true - } - if se, ok := err.(interface{ GRPCStatus() *Status }); ok { - return se.GRPCStatus(), true - } - return New(codes.Unknown, err.Error()), false -} - -// Convert is a convenience function which removes the need to handle the -// boolean return value from FromError. -func Convert(err error) *Status { - s, _ := FromError(err) - return s -} - -// WithDetails returns a new status with the provided details messages appended to the status. -// If any errors are encountered, it returns nil and the first error encountered. -func (s *Status) WithDetails(details ...proto.Message) (*Status, error) { - if s.Code() == codes.OK { - return nil, errors.New("no error details for status with code OK") - } - // s.Code() != OK implies that s.Proto() != nil. - p := s.Proto() - for _, detail := range details { - any, err := ptypes.MarshalAny(detail) - if err != nil { - return nil, err - } - p.Details = append(p.Details, any) - } - return &Status{s: p}, nil -} - -// Details returns a slice of details messages attached to the status. -// If a detail cannot be decoded, the error is returned in place of the detail. -func (s *Status) Details() []interface{} { - if s == nil || s.s == nil { - return nil - } - details := make([]interface{}, 0, len(s.s.Details)) - for _, any := range s.s.Details { - detail := &ptypes.DynamicAny{} - if err := ptypes.UnmarshalAny(any, detail); err != nil { - details = append(details, err) - continue - } - details = append(details, detail.Message) - } - return details -} - -// Code returns the Code of the error if it is a Status error, codes.OK if err -// is nil, or codes.Unknown otherwise. -func Code(err error) codes.Code { - // Don't use FromError to avoid allocation of OK status. - if err == nil { - return codes.OK - } - if se, ok := err.(interface{ GRPCStatus() *Status }); ok { - return se.GRPCStatus().Code() - } - return codes.Unknown -} diff --git a/vendor/google.golang.org/grpc/stream.go b/vendor/google.golang.org/grpc/stream.go deleted file mode 100644 index 82921a15a3a..00000000000 --- a/vendor/google.golang.org/grpc/stream.go +++ /dev/null @@ -1,765 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 grpc - -import ( - "errors" - "io" - "sync" - "time" - - "golang.org/x/net/context" - "golang.org/x/net/trace" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/channelz" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/encoding" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" - "google.golang.org/grpc/transport" -) - -// StreamHandler defines the handler called by gRPC server to complete the -// execution of a streaming RPC. If a StreamHandler returns an error, it -// should be produced by the status package, or else gRPC will use -// codes.Unknown as the status code and err.Error() as the status message -// of the RPC. -type StreamHandler func(srv interface{}, stream ServerStream) error - -// StreamDesc represents a streaming RPC service's method specification. -type StreamDesc struct { - StreamName string - Handler StreamHandler - - // At least one of these is true. - ServerStreams bool - ClientStreams bool -} - -// Stream defines the common interface a client or server stream has to satisfy. -// -// All errors returned from Stream are compatible with the status package. -type Stream interface { - // Context returns the context for this stream. - Context() context.Context - // SendMsg blocks until it sends m, the stream is done or the stream - // breaks. - // On error, it aborts the stream and returns an RPC status on client - // side. On server side, it simply returns the error to the caller. - // SendMsg is called by generated code. Also Users can call SendMsg - // directly when it is really needed in their use cases. - // It's safe to have a goroutine calling SendMsg and another goroutine calling - // recvMsg on the same stream at the same time. - // But it is not safe to call SendMsg on the same stream in different goroutines. - SendMsg(m interface{}) error - // RecvMsg blocks until it receives a message or the stream is - // done. On client side, it returns io.EOF when the stream is done. On - // any other error, it aborts the stream and returns an RPC status. On - // server side, it simply returns the error to the caller. - // It's safe to have a goroutine calling SendMsg and another goroutine calling - // recvMsg on the same stream at the same time. - // But it is not safe to call RecvMsg on the same stream in different goroutines. - RecvMsg(m interface{}) error -} - -// ClientStream defines the interface a client stream has to satisfy. -type ClientStream interface { - // Header returns the header metadata received from the server if there - // is any. It blocks if the metadata is not ready to read. - Header() (metadata.MD, error) - // Trailer returns the trailer metadata from the server, if there is any. - // It must only be called after stream.CloseAndRecv has returned, or - // stream.Recv has returned a non-nil error (including io.EOF). - Trailer() metadata.MD - // CloseSend closes the send direction of the stream. It closes the stream - // when non-nil error is met. - CloseSend() error - // Stream.SendMsg() may return a non-nil error when something wrong happens sending - // the request. The returned error indicates the status of this sending, not the final - // status of the RPC. - // - // Always call Stream.RecvMsg() to drain the stream and get the final - // status, otherwise there could be leaked resources. - Stream -} - -// NewStream creates a new Stream for the client side. This is typically -// called by generated code. -func (cc *ClientConn) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error) { - // allow interceptor to see all applicable call options, which means those - // configured as defaults from dial option as well as per-call options - opts = combine(cc.dopts.callOptions, opts) - - if cc.dopts.streamInt != nil { - return cc.dopts.streamInt(ctx, desc, cc, method, newClientStream, opts...) - } - return newClientStream(ctx, desc, cc, method, opts...) -} - -// NewClientStream creates a new Stream for the client side. This is typically -// called by generated code. -// -// DEPRECATED: Use ClientConn.NewStream instead. -func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error) { - return cc.NewStream(ctx, desc, method, opts...) -} - -func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) { - if channelz.IsOn() { - cc.incrCallsStarted() - defer func() { - if err != nil { - cc.incrCallsFailed() - } - }() - } - c := defaultCallInfo() - mc := cc.GetMethodConfig(method) - if mc.WaitForReady != nil { - c.failFast = !*mc.WaitForReady - } - - // Possible context leak: - // The cancel function for the child context we create will only be called - // when RecvMsg returns a non-nil error, if the ClientConn is closed, or if - // an error is generated by SendMsg. - // https://github.com/grpc/grpc-go/issues/1818. - var cancel context.CancelFunc - if mc.Timeout != nil && *mc.Timeout >= 0 { - ctx, cancel = context.WithTimeout(ctx, *mc.Timeout) - } else { - ctx, cancel = context.WithCancel(ctx) - } - defer func() { - if err != nil { - cancel() - } - }() - - for _, o := range opts { - if err := o.before(c); err != nil { - return nil, toRPCErr(err) - } - } - c.maxSendMessageSize = getMaxSize(mc.MaxReqSize, c.maxSendMessageSize, defaultClientMaxSendMessageSize) - c.maxReceiveMessageSize = getMaxSize(mc.MaxRespSize, c.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize) - if err := setCallInfoCodec(c); err != nil { - return nil, err - } - - callHdr := &transport.CallHdr{ - Host: cc.authority, - Method: method, - // If it's not client streaming, we should already have the request to be sent, - // so we don't flush the header. - // If it's client streaming, the user may never send a request or send it any - // time soon, so we ask the transport to flush the header. - Flush: desc.ClientStreams, - ContentSubtype: c.contentSubtype, - } - - // Set our outgoing compression according to the UseCompressor CallOption, if - // set. In that case, also find the compressor from the encoding package. - // Otherwise, use the compressor configured by the WithCompressor DialOption, - // if set. - var cp Compressor - var comp encoding.Compressor - if ct := c.compressorType; ct != "" { - callHdr.SendCompress = ct - if ct != encoding.Identity { - comp = encoding.GetCompressor(ct) - if comp == nil { - return nil, status.Errorf(codes.Internal, "grpc: Compressor is not installed for requested grpc-encoding %q", ct) - } - } - } else if cc.dopts.cp != nil { - callHdr.SendCompress = cc.dopts.cp.Type() - cp = cc.dopts.cp - } - if c.creds != nil { - callHdr.Creds = c.creds - } - var trInfo traceInfo - if EnableTracing { - trInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method) - trInfo.firstLine.client = true - if deadline, ok := ctx.Deadline(); ok { - trInfo.firstLine.deadline = deadline.Sub(time.Now()) - } - trInfo.tr.LazyLog(&trInfo.firstLine, false) - ctx = trace.NewContext(ctx, trInfo.tr) - defer func() { - if err != nil { - // Need to call tr.finish() if error is returned. - // Because tr will not be returned to caller. - trInfo.tr.LazyPrintf("RPC: [%v]", err) - trInfo.tr.SetError() - trInfo.tr.Finish() - } - }() - } - ctx = newContextWithRPCInfo(ctx, c.failFast) - sh := cc.dopts.copts.StatsHandler - var beginTime time.Time - if sh != nil { - ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method, FailFast: c.failFast}) - beginTime = time.Now() - begin := &stats.Begin{ - Client: true, - BeginTime: beginTime, - FailFast: c.failFast, - } - sh.HandleRPC(ctx, begin) - defer func() { - if err != nil { - // Only handle end stats if err != nil. - end := &stats.End{ - Client: true, - Error: err, - BeginTime: beginTime, - EndTime: time.Now(), - } - sh.HandleRPC(ctx, end) - } - }() - } - - var ( - t transport.ClientTransport - s *transport.Stream - done func(balancer.DoneInfo) - ) - for { - // Check to make sure the context has expired. This will prevent us from - // looping forever if an error occurs for wait-for-ready RPCs where no data - // is sent on the wire. - select { - case <-ctx.Done(): - return nil, toRPCErr(ctx.Err()) - default: - } - - t, done, err = cc.getTransport(ctx, c.failFast) - if err != nil { - return nil, err - } - - s, err = t.NewStream(ctx, callHdr) - if err != nil { - if done != nil { - done(balancer.DoneInfo{Err: err}) - done = nil - } - // In the event of any error from NewStream, we never attempted to write - // anything to the wire, so we can retry indefinitely for non-fail-fast - // RPCs. - if !c.failFast { - continue - } - return nil, toRPCErr(err) - } - break - } - - cs := &clientStream{ - opts: opts, - c: c, - cc: cc, - desc: desc, - codec: c.codec, - cp: cp, - comp: comp, - cancel: cancel, - attempt: &csAttempt{ - t: t, - s: s, - p: &parser{r: s}, - done: done, - dc: cc.dopts.dc, - ctx: ctx, - trInfo: trInfo, - statsHandler: sh, - beginTime: beginTime, - }, - } - cs.c.stream = cs - cs.attempt.cs = cs - if desc != unaryStreamDesc { - // Listen on cc and stream contexts to cleanup when the user closes the - // ClientConn or cancels the stream context. In all other cases, an error - // should already be injected into the recv buffer by the transport, which - // the client will eventually receive, and then we will cancel the stream's - // context in clientStream.finish. - go func() { - select { - case <-cc.ctx.Done(): - cs.finish(ErrClientConnClosing) - case <-ctx.Done(): - cs.finish(toRPCErr(ctx.Err())) - } - }() - } - return cs, nil -} - -// clientStream implements a client side Stream. -type clientStream struct { - opts []CallOption - c *callInfo - cc *ClientConn - desc *StreamDesc - - codec baseCodec - cp Compressor - comp encoding.Compressor - - cancel context.CancelFunc // cancels all attempts - - sentLast bool // sent an end stream - - mu sync.Mutex // guards finished - finished bool // TODO: replace with atomic cmpxchg or sync.Once? - - attempt *csAttempt // the active client stream attempt - // TODO(hedging): hedging will have multiple attempts simultaneously. -} - -// csAttempt implements a single transport stream attempt within a -// clientStream. -type csAttempt struct { - cs *clientStream - t transport.ClientTransport - s *transport.Stream - p *parser - done func(balancer.DoneInfo) - - dc Decompressor - decomp encoding.Compressor - decompSet bool - - ctx context.Context // the application's context, wrapped by stats/tracing - - mu sync.Mutex // guards trInfo.tr - // trInfo.tr is set when created (if EnableTracing is true), - // and cleared when the finish method is called. - trInfo traceInfo - - statsHandler stats.Handler - beginTime time.Time -} - -func (cs *clientStream) Context() context.Context { - // TODO(retry): commit the current attempt (the context has peer-aware data). - return cs.attempt.context() -} - -func (cs *clientStream) Header() (metadata.MD, error) { - m, err := cs.attempt.header() - if err != nil { - // TODO(retry): maybe retry on error or commit attempt on success. - err = toRPCErr(err) - cs.finish(err) - } - return m, err -} - -func (cs *clientStream) Trailer() metadata.MD { - // TODO(retry): on error, maybe retry (trailers-only). - return cs.attempt.trailer() -} - -func (cs *clientStream) SendMsg(m interface{}) (err error) { - // TODO(retry): buffer message for replaying if not committed. - return cs.attempt.sendMsg(m) -} - -func (cs *clientStream) RecvMsg(m interface{}) (err error) { - // TODO(retry): maybe retry on error or commit attempt on success. - return cs.attempt.recvMsg(m) -} - -func (cs *clientStream) CloseSend() error { - cs.attempt.closeSend() - return nil -} - -func (cs *clientStream) finish(err error) { - if err == io.EOF { - // Ending a stream with EOF indicates a success. - err = nil - } - cs.mu.Lock() - if cs.finished { - cs.mu.Unlock() - return - } - cs.finished = true - cs.mu.Unlock() - if channelz.IsOn() { - if err != nil { - cs.cc.incrCallsFailed() - } else { - cs.cc.incrCallsSucceeded() - } - } - // TODO(retry): commit current attempt if necessary. - cs.attempt.finish(err) - for _, o := range cs.opts { - o.after(cs.c) - } - cs.cancel() -} - -func (a *csAttempt) context() context.Context { - return a.s.Context() -} - -func (a *csAttempt) header() (metadata.MD, error) { - return a.s.Header() -} - -func (a *csAttempt) trailer() metadata.MD { - return a.s.Trailer() -} - -func (a *csAttempt) sendMsg(m interface{}) (err error) { - // TODO Investigate how to signal the stats handling party. - // generate error stats if err != nil && err != io.EOF? - cs := a.cs - defer func() { - // For non-client-streaming RPCs, we return nil instead of EOF on success - // because the generated code requires it. finish is not called; RecvMsg() - // will call it with the stream's status independently. - if err == io.EOF && !cs.desc.ClientStreams { - err = nil - } - if err != nil && err != io.EOF { - // Call finish on the client stream for errors generated by this SendMsg - // call, as these indicate problems created by this client. (Transport - // errors are converted to an io.EOF error below; the real error will be - // returned from RecvMsg eventually in that case, or be retried.) - cs.finish(err) - } - }() - // TODO: Check cs.sentLast and error if we already ended the stream. - if EnableTracing { - a.mu.Lock() - if a.trInfo.tr != nil { - a.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true) - } - a.mu.Unlock() - } - var outPayload *stats.OutPayload - if a.statsHandler != nil { - outPayload = &stats.OutPayload{ - Client: true, - } - } - hdr, data, err := encode(cs.codec, m, cs.cp, outPayload, cs.comp) - if err != nil { - return err - } - if len(data) > *cs.c.maxSendMessageSize { - return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(data), *cs.c.maxSendMessageSize) - } - if !cs.desc.ClientStreams { - cs.sentLast = true - } - err = a.t.Write(a.s, hdr, data, &transport.Options{Last: !cs.desc.ClientStreams}) - if err == nil { - if outPayload != nil { - outPayload.SentTime = time.Now() - a.statsHandler.HandleRPC(a.ctx, outPayload) - } - if channelz.IsOn() { - a.t.IncrMsgSent() - } - return nil - } - return io.EOF -} - -func (a *csAttempt) recvMsg(m interface{}) (err error) { - cs := a.cs - defer func() { - if err != nil || !cs.desc.ServerStreams { - // err != nil or non-server-streaming indicates end of stream. - cs.finish(err) - } - }() - var inPayload *stats.InPayload - if a.statsHandler != nil { - inPayload = &stats.InPayload{ - Client: true, - } - } - if !a.decompSet { - // Block until we receive headers containing received message encoding. - if ct := a.s.RecvCompress(); ct != "" && ct != encoding.Identity { - if a.dc == nil || a.dc.Type() != ct { - // No configured decompressor, or it does not match the incoming - // message encoding; attempt to find a registered compressor that does. - a.dc = nil - a.decomp = encoding.GetCompressor(ct) - } - } else { - // No compression is used; disable our decompressor. - a.dc = nil - } - // Only initialize this state once per stream. - a.decompSet = true - } - err = recv(a.p, cs.codec, a.s, a.dc, m, *cs.c.maxReceiveMessageSize, inPayload, a.decomp) - if err != nil { - if err == io.EOF { - if statusErr := a.s.Status().Err(); statusErr != nil { - return statusErr - } - return io.EOF // indicates successful end of stream. - } - return toRPCErr(err) - } - if EnableTracing { - a.mu.Lock() - if a.trInfo.tr != nil { - a.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true) - } - a.mu.Unlock() - } - if inPayload != nil { - a.statsHandler.HandleRPC(a.ctx, inPayload) - } - if channelz.IsOn() { - a.t.IncrMsgRecv() - } - if cs.desc.ServerStreams { - // Subsequent messages should be received by subsequent RecvMsg calls. - return nil - } - - // Special handling for non-server-stream rpcs. - // This recv expects EOF or errors, so we don't collect inPayload. - err = recv(a.p, cs.codec, a.s, a.dc, m, *cs.c.maxReceiveMessageSize, nil, a.decomp) - if err == nil { - return toRPCErr(errors.New("grpc: client streaming protocol violation: get , want ")) - } - if err == io.EOF { - return a.s.Status().Err() // non-server streaming Recv returns nil on success - } - return toRPCErr(err) -} - -func (a *csAttempt) closeSend() { - cs := a.cs - if cs.sentLast { - return - } - cs.sentLast = true - cs.attempt.t.Write(cs.attempt.s, nil, nil, &transport.Options{Last: true}) - // We ignore errors from Write. Any error it would return would also be - // returned by a subsequent RecvMsg call, and the user is supposed to always - // finish the stream by calling RecvMsg until it returns err != nil. -} - -func (a *csAttempt) finish(err error) { - a.mu.Lock() - a.t.CloseStream(a.s, err) - - if a.done != nil { - a.done(balancer.DoneInfo{ - Err: err, - BytesSent: true, - BytesReceived: a.s.BytesReceived(), - }) - } - if a.statsHandler != nil { - end := &stats.End{ - Client: true, - BeginTime: a.beginTime, - EndTime: time.Now(), - Error: err, - } - a.statsHandler.HandleRPC(a.ctx, end) - } - if a.trInfo.tr != nil { - if err == nil { - a.trInfo.tr.LazyPrintf("RPC: [OK]") - } else { - a.trInfo.tr.LazyPrintf("RPC: [%v]", err) - a.trInfo.tr.SetError() - } - a.trInfo.tr.Finish() - a.trInfo.tr = nil - } - a.mu.Unlock() -} - -// ServerStream defines the interface a server stream has to satisfy. -type ServerStream interface { - // SetHeader sets the header metadata. It may be called multiple times. - // When call multiple times, all the provided metadata will be merged. - // All the metadata will be sent out when one of the following happens: - // - ServerStream.SendHeader() is called; - // - The first response is sent out; - // - An RPC status is sent out (error or success). - SetHeader(metadata.MD) error - // SendHeader sends the header metadata. - // The provided md and headers set by SetHeader() will be sent. - // It fails if called multiple times. - SendHeader(metadata.MD) error - // SetTrailer sets the trailer metadata which will be sent with the RPC status. - // When called more than once, all the provided metadata will be merged. - SetTrailer(metadata.MD) - Stream -} - -// serverStream implements a server side Stream. -type serverStream struct { - ctx context.Context - t transport.ServerTransport - s *transport.Stream - p *parser - codec baseCodec - - cp Compressor - dc Decompressor - comp encoding.Compressor - decomp encoding.Compressor - - maxReceiveMessageSize int - maxSendMessageSize int - trInfo *traceInfo - - statsHandler stats.Handler - - mu sync.Mutex // protects trInfo.tr after the service handler runs. -} - -func (ss *serverStream) Context() context.Context { - return ss.ctx -} - -func (ss *serverStream) SetHeader(md metadata.MD) error { - if md.Len() == 0 { - return nil - } - return ss.s.SetHeader(md) -} - -func (ss *serverStream) SendHeader(md metadata.MD) error { - return ss.t.WriteHeader(ss.s, md) -} - -func (ss *serverStream) SetTrailer(md metadata.MD) { - if md.Len() == 0 { - return - } - ss.s.SetTrailer(md) -} - -func (ss *serverStream) SendMsg(m interface{}) (err error) { - defer func() { - if ss.trInfo != nil { - ss.mu.Lock() - if ss.trInfo.tr != nil { - if err == nil { - ss.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true) - } else { - ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) - ss.trInfo.tr.SetError() - } - } - ss.mu.Unlock() - } - if err != nil && err != io.EOF { - st, _ := status.FromError(toRPCErr(err)) - ss.t.WriteStatus(ss.s, st) - } - if channelz.IsOn() && err == nil { - ss.t.IncrMsgSent() - } - }() - var outPayload *stats.OutPayload - if ss.statsHandler != nil { - outPayload = &stats.OutPayload{} - } - hdr, data, err := encode(ss.codec, m, ss.cp, outPayload, ss.comp) - if err != nil { - return err - } - if len(data) > ss.maxSendMessageSize { - return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(data), ss.maxSendMessageSize) - } - if err := ss.t.Write(ss.s, hdr, data, &transport.Options{Last: false}); err != nil { - return toRPCErr(err) - } - if outPayload != nil { - outPayload.SentTime = time.Now() - ss.statsHandler.HandleRPC(ss.s.Context(), outPayload) - } - return nil -} - -func (ss *serverStream) RecvMsg(m interface{}) (err error) { - defer func() { - if ss.trInfo != nil { - ss.mu.Lock() - if ss.trInfo.tr != nil { - if err == nil { - ss.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true) - } else if err != io.EOF { - ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) - ss.trInfo.tr.SetError() - } - } - ss.mu.Unlock() - } - if err != nil && err != io.EOF { - st, _ := status.FromError(toRPCErr(err)) - ss.t.WriteStatus(ss.s, st) - } - if channelz.IsOn() && err == nil { - ss.t.IncrMsgRecv() - } - }() - var inPayload *stats.InPayload - if ss.statsHandler != nil { - inPayload = &stats.InPayload{} - } - if err := recv(ss.p, ss.codec, ss.s, ss.dc, m, ss.maxReceiveMessageSize, inPayload, ss.decomp); err != nil { - if err == io.EOF { - return err - } - if err == io.ErrUnexpectedEOF { - err = status.Errorf(codes.Internal, io.ErrUnexpectedEOF.Error()) - } - return toRPCErr(err) - } - if inPayload != nil { - ss.statsHandler.HandleRPC(ss.s.Context(), inPayload) - } - return nil -} - -// MethodFromServerStream returns the method string for the input stream. -// The returned string is in the format of "/service/method". -func MethodFromServerStream(stream ServerStream) (string, bool) { - return Method(stream.Context()) -} diff --git a/vendor/google.golang.org/grpc/tap/tap.go b/vendor/google.golang.org/grpc/tap/tap.go deleted file mode 100644 index 22b8fb50dea..00000000000 --- a/vendor/google.golang.org/grpc/tap/tap.go +++ /dev/null @@ -1,51 +0,0 @@ -/* - * - * Copyright 2016 gRPC 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 tap defines the function handles which are executed on the transport -// layer of gRPC-Go and related information. Everything here is EXPERIMENTAL. -package tap - -import ( - "golang.org/x/net/context" -) - -// Info defines the relevant information needed by the handles. -type Info struct { - // FullMethodName is the string of grpc method (in the format of - // /package.service/method). - FullMethodName string - // TODO: More to be added. -} - -// ServerInHandle defines the function which runs before a new stream is created -// on the server side. If it returns a non-nil error, the stream will not be -// created and a RST_STREAM will be sent back to the client with REFUSED_STREAM. -// The client will receive an RPC error "code = Unavailable, desc = stream -// terminated by RST_STREAM with error code: REFUSED_STREAM". -// -// It's intended to be used in situations where you don't want to waste the -// resources to accept the new stream (e.g. rate-limiting). And the content of -// the error will be ignored and won't be sent back to the client. For other -// general usages, please use interceptors. -// -// Note that it is executed in the per-connection I/O goroutine(s) instead of -// per-RPC goroutine. Therefore, users should NOT have any -// blocking/time-consuming work in this handle. Otherwise all the RPCs would -// slow down. Also, for the same reason, this handle won't be called -// concurrently by gRPC. -type ServerInHandle func(ctx context.Context, info *Info) (context.Context, error) diff --git a/vendor/google.golang.org/grpc/trace.go b/vendor/google.golang.org/grpc/trace.go deleted file mode 100644 index c1c96dedcb7..00000000000 --- a/vendor/google.golang.org/grpc/trace.go +++ /dev/null @@ -1,113 +0,0 @@ -/* - * - * Copyright 2015 gRPC 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 grpc - -import ( - "bytes" - "fmt" - "io" - "net" - "strings" - "time" - - "golang.org/x/net/trace" -) - -// EnableTracing controls whether to trace RPCs using the golang.org/x/net/trace package. -// This should only be set before any RPCs are sent or received by this program. -var EnableTracing bool - -// methodFamily returns the trace family for the given method. -// It turns "/pkg.Service/GetFoo" into "pkg.Service". -func methodFamily(m string) string { - m = strings.TrimPrefix(m, "/") // remove leading slash - if i := strings.Index(m, "/"); i >= 0 { - m = m[:i] // remove everything from second slash - } - if i := strings.LastIndex(m, "."); i >= 0 { - m = m[i+1:] // cut down to last dotted component - } - return m -} - -// traceInfo contains tracing information for an RPC. -type traceInfo struct { - tr trace.Trace - firstLine firstLine -} - -// firstLine is the first line of an RPC trace. -type firstLine struct { - client bool // whether this is a client (outgoing) RPC - remoteAddr net.Addr - deadline time.Duration // may be zero -} - -func (f *firstLine) String() string { - var line bytes.Buffer - io.WriteString(&line, "RPC: ") - if f.client { - io.WriteString(&line, "to") - } else { - io.WriteString(&line, "from") - } - fmt.Fprintf(&line, " %v deadline:", f.remoteAddr) - if f.deadline != 0 { - fmt.Fprint(&line, f.deadline) - } else { - io.WriteString(&line, "none") - } - return line.String() -} - -const truncateSize = 100 - -func truncate(x string, l int) string { - if l > len(x) { - return x - } - return x[:l] -} - -// payload represents an RPC request or response payload. -type payload struct { - sent bool // whether this is an outgoing payload - msg interface{} // e.g. a proto.Message - // TODO(dsymonds): add stringifying info to codec, and limit how much we hold here? -} - -func (p payload) String() string { - if p.sent { - return truncate(fmt.Sprintf("sent: %v", p.msg), truncateSize) - } - return truncate(fmt.Sprintf("recv: %v", p.msg), truncateSize) -} - -type fmtStringer struct { - format string - a []interface{} -} - -func (f *fmtStringer) String() string { - return fmt.Sprintf(f.format, f.a...) -} - -type stringer string - -func (s stringer) String() string { return string(s) } diff --git a/vendor/google.golang.org/grpc/transport/bdp_estimator.go b/vendor/google.golang.org/grpc/transport/bdp_estimator.go deleted file mode 100644 index 63cd2627c87..00000000000 --- a/vendor/google.golang.org/grpc/transport/bdp_estimator.go +++ /dev/null @@ -1,140 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 transport - -import ( - "sync" - "time" -) - -const ( - // bdpLimit is the maximum value the flow control windows - // will be increased to. - bdpLimit = (1 << 20) * 4 - // alpha is a constant factor used to keep a moving average - // of RTTs. - alpha = 0.9 - // If the current bdp sample is greater than or equal to - // our beta * our estimated bdp and the current bandwidth - // sample is the maximum bandwidth observed so far, we - // increase our bbp estimate by a factor of gamma. - beta = 0.66 - // To put our bdp to be smaller than or equal to twice the real BDP, - // we should multiply our current sample with 4/3, however to round things out - // we use 2 as the multiplication factor. - gamma = 2 -) - -// Adding arbitrary data to ping so that its ack can be identified. -// Easter-egg: what does the ping message say? -var bdpPing = &ping{data: [8]byte{2, 4, 16, 16, 9, 14, 7, 7}} - -type bdpEstimator struct { - // sentAt is the time when the ping was sent. - sentAt time.Time - - mu sync.Mutex - // bdp is the current bdp estimate. - bdp uint32 - // sample is the number of bytes received in one measurement cycle. - sample uint32 - // bwMax is the maximum bandwidth noted so far (bytes/sec). - bwMax float64 - // bool to keep track of the beginning of a new measurement cycle. - isSent bool - // Callback to update the window sizes. - updateFlowControl func(n uint32) - // sampleCount is the number of samples taken so far. - sampleCount uint64 - // round trip time (seconds) - rtt float64 -} - -// timesnap registers the time bdp ping was sent out so that -// network rtt can be calculated when its ack is received. -// It is called (by controller) when the bdpPing is -// being written on the wire. -func (b *bdpEstimator) timesnap(d [8]byte) { - if bdpPing.data != d { - return - } - b.sentAt = time.Now() -} - -// add adds bytes to the current sample for calculating bdp. -// It returns true only if a ping must be sent. This can be used -// by the caller (handleData) to make decision about batching -// a window update with it. -func (b *bdpEstimator) add(n uint32) bool { - b.mu.Lock() - defer b.mu.Unlock() - if b.bdp == bdpLimit { - return false - } - if !b.isSent { - b.isSent = true - b.sample = n - b.sentAt = time.Time{} - b.sampleCount++ - return true - } - b.sample += n - return false -} - -// calculate is called when an ack for a bdp ping is received. -// Here we calculate the current bdp and bandwidth sample and -// decide if the flow control windows should go up. -func (b *bdpEstimator) calculate(d [8]byte) { - // Check if the ping acked for was the bdp ping. - if bdpPing.data != d { - return - } - b.mu.Lock() - rttSample := time.Since(b.sentAt).Seconds() - if b.sampleCount < 10 { - // Bootstrap rtt with an average of first 10 rtt samples. - b.rtt += (rttSample - b.rtt) / float64(b.sampleCount) - } else { - // Heed to the recent past more. - b.rtt += (rttSample - b.rtt) * float64(alpha) - } - b.isSent = false - // The number of bytes accumulated so far in the sample is smaller - // than or equal to 1.5 times the real BDP on a saturated connection. - bwCurrent := float64(b.sample) / (b.rtt * float64(1.5)) - if bwCurrent > b.bwMax { - b.bwMax = bwCurrent - } - // If the current sample (which is smaller than or equal to the 1.5 times the real BDP) is - // greater than or equal to 2/3rd our perceived bdp AND this is the maximum bandwidth seen so far, we - // should update our perception of the network BDP. - if float64(b.sample) >= beta*float64(b.bdp) && bwCurrent == b.bwMax && b.bdp != bdpLimit { - sampleFloat := float64(b.sample) - b.bdp = uint32(gamma * sampleFloat) - if b.bdp > bdpLimit { - b.bdp = bdpLimit - } - bdp := b.bdp - b.mu.Unlock() - b.updateFlowControl(bdp) - return - } - b.mu.Unlock() -} diff --git a/vendor/google.golang.org/grpc/transport/controlbuf.go b/vendor/google.golang.org/grpc/transport/controlbuf.go deleted file mode 100644 index e147cd51bf1..00000000000 --- a/vendor/google.golang.org/grpc/transport/controlbuf.go +++ /dev/null @@ -1,769 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 transport - -import ( - "bytes" - "fmt" - "runtime" - "sync" - - "golang.org/x/net/http2" - "golang.org/x/net/http2/hpack" -) - -type itemNode struct { - it interface{} - next *itemNode -} - -type itemList struct { - head *itemNode - tail *itemNode -} - -func (il *itemList) enqueue(i interface{}) { - n := &itemNode{it: i} - if il.tail == nil { - il.head, il.tail = n, n - return - } - il.tail.next = n - il.tail = n -} - -// peek returns the first item in the list without removing it from the -// list. -func (il *itemList) peek() interface{} { - return il.head.it -} - -func (il *itemList) dequeue() interface{} { - if il.head == nil { - return nil - } - i := il.head.it - il.head = il.head.next - if il.head == nil { - il.tail = nil - } - return i -} - -func (il *itemList) dequeueAll() *itemNode { - h := il.head - il.head, il.tail = nil, nil - return h -} - -func (il *itemList) isEmpty() bool { - return il.head == nil -} - -// The following defines various control items which could flow through -// the control buffer of transport. They represent different aspects of -// control tasks, e.g., flow control, settings, streaming resetting, etc. - -type headerFrame struct { - streamID uint32 - hf []hpack.HeaderField - endStream bool // Valid on server side. - initStream func(uint32) (bool, error) // Used only on the client side. - onWrite func() - wq *writeQuota // write quota for the stream created. - cleanup *cleanupStream // Valid on the server side. - onOrphaned func(error) // Valid on client-side -} - -type cleanupStream struct { - streamID uint32 - idPtr *uint32 - rst bool - rstCode http2.ErrCode - onWrite func() -} - -type dataFrame struct { - streamID uint32 - endStream bool - h []byte - d []byte - // onEachWrite is called every time - // a part of d is written out. - onEachWrite func() -} - -type incomingWindowUpdate struct { - streamID uint32 - increment uint32 -} - -type outgoingWindowUpdate struct { - streamID uint32 - increment uint32 -} - -type incomingSettings struct { - ss []http2.Setting -} - -type outgoingSettings struct { - ss []http2.Setting -} - -type settingsAck struct { -} - -type incomingGoAway struct { -} - -type goAway struct { - code http2.ErrCode - debugData []byte - headsUp bool - closeConn bool -} - -type ping struct { - ack bool - data [8]byte -} - -type outFlowControlSizeRequest struct { - resp chan uint32 -} - -type outStreamState int - -const ( - active outStreamState = iota - empty - waitingOnStreamQuota -) - -type outStream struct { - id uint32 - state outStreamState - itl *itemList - bytesOutStanding int - wq *writeQuota - - next *outStream - prev *outStream -} - -func (s *outStream) deleteSelf() { - if s.prev != nil { - s.prev.next = s.next - } - if s.next != nil { - s.next.prev = s.prev - } - s.next, s.prev = nil, nil -} - -type outStreamList struct { - // Following are sentinel objects that mark the - // beginning and end of the list. They do not - // contain any item lists. All valid objects are - // inserted in between them. - // This is needed so that an outStream object can - // deleteSelf() in O(1) time without knowing which - // list it belongs to. - head *outStream - tail *outStream -} - -func newOutStreamList() *outStreamList { - head, tail := new(outStream), new(outStream) - head.next = tail - tail.prev = head - return &outStreamList{ - head: head, - tail: tail, - } -} - -func (l *outStreamList) enqueue(s *outStream) { - e := l.tail.prev - e.next = s - s.prev = e - s.next = l.tail - l.tail.prev = s -} - -// remove from the beginning of the list. -func (l *outStreamList) dequeue() *outStream { - b := l.head.next - if b == l.tail { - return nil - } - b.deleteSelf() - return b -} - -type controlBuffer struct { - ch chan struct{} - done <-chan struct{} - mu sync.Mutex - consumerWaiting bool - list *itemList - err error -} - -func newControlBuffer(done <-chan struct{}) *controlBuffer { - return &controlBuffer{ - ch: make(chan struct{}, 1), - list: &itemList{}, - done: done, - } -} - -func (c *controlBuffer) put(it interface{}) error { - _, err := c.executeAndPut(nil, it) - return err -} - -func (c *controlBuffer) executeAndPut(f func(it interface{}) bool, it interface{}) (bool, error) { - var wakeUp bool - c.mu.Lock() - if c.err != nil { - c.mu.Unlock() - return false, c.err - } - if f != nil { - if !f(it) { // f wasn't successful - c.mu.Unlock() - return false, nil - } - } - if c.consumerWaiting { - wakeUp = true - c.consumerWaiting = false - } - c.list.enqueue(it) - c.mu.Unlock() - if wakeUp { - select { - case c.ch <- struct{}{}: - default: - } - } - return true, nil -} - -func (c *controlBuffer) get(block bool) (interface{}, error) { - for { - c.mu.Lock() - if c.err != nil { - c.mu.Unlock() - return nil, c.err - } - if !c.list.isEmpty() { - h := c.list.dequeue() - c.mu.Unlock() - return h, nil - } - if !block { - c.mu.Unlock() - return nil, nil - } - c.consumerWaiting = true - c.mu.Unlock() - select { - case <-c.ch: - case <-c.done: - c.finish() - return nil, ErrConnClosing - } - } -} - -func (c *controlBuffer) finish() { - c.mu.Lock() - if c.err != nil { - c.mu.Unlock() - return - } - c.err = ErrConnClosing - // There may be headers for streams in the control buffer. - // These streams need to be cleaned out since the transport - // is still not aware of these yet. - for head := c.list.dequeueAll(); head != nil; head = head.next { - hdr, ok := head.it.(*headerFrame) - if !ok { - continue - } - if hdr.onOrphaned != nil { // It will be nil on the server-side. - hdr.onOrphaned(ErrConnClosing) - } - } - c.mu.Unlock() -} - -type side int - -const ( - clientSide side = iota - serverSide -) - -type loopyWriter struct { - side side - cbuf *controlBuffer - sendQuota uint32 - oiws uint32 // outbound initial window size. - estdStreams map[uint32]*outStream // Established streams. - activeStreams *outStreamList // Streams that are sending data. - framer *framer - hBuf *bytes.Buffer // The buffer for HPACK encoding. - hEnc *hpack.Encoder // HPACK encoder. - bdpEst *bdpEstimator - draining bool - - // Side-specific handlers - ssGoAwayHandler func(*goAway) (bool, error) -} - -func newLoopyWriter(s side, fr *framer, cbuf *controlBuffer, bdpEst *bdpEstimator) *loopyWriter { - var buf bytes.Buffer - l := &loopyWriter{ - side: s, - cbuf: cbuf, - sendQuota: defaultWindowSize, - oiws: defaultWindowSize, - estdStreams: make(map[uint32]*outStream), - activeStreams: newOutStreamList(), - framer: fr, - hBuf: &buf, - hEnc: hpack.NewEncoder(&buf), - bdpEst: bdpEst, - } - return l -} - -const minBatchSize = 1000 - -// run should be run in a separate goroutine. -func (l *loopyWriter) run() { - var ( - it interface{} - err error - isEmpty bool - ) - defer func() { - errorf("transport: loopyWriter.run returning. Err: %v", err) - }() - for { - it, err = l.cbuf.get(true) - if err != nil { - return - } - if err = l.handle(it); err != nil { - return - } - if _, err = l.processData(); err != nil { - return - } - gosched := true - hasdata: - for { - it, err = l.cbuf.get(false) - if err != nil { - return - } - if it != nil { - if err = l.handle(it); err != nil { - return - } - if _, err = l.processData(); err != nil { - return - } - continue hasdata - } - if isEmpty, err = l.processData(); err != nil { - return - } - if !isEmpty { - continue hasdata - } - if gosched { - gosched = false - if l.framer.writer.offset < minBatchSize { - runtime.Gosched() - continue hasdata - } - } - l.framer.writer.Flush() - break hasdata - - } - } -} - -func (l *loopyWriter) outgoingWindowUpdateHandler(w *outgoingWindowUpdate) error { - return l.framer.fr.WriteWindowUpdate(w.streamID, w.increment) -} - -func (l *loopyWriter) incomingWindowUpdateHandler(w *incomingWindowUpdate) error { - // Otherwise update the quota. - if w.streamID == 0 { - l.sendQuota += w.increment - return nil - } - // Find the stream and update it. - if str, ok := l.estdStreams[w.streamID]; ok { - str.bytesOutStanding -= int(w.increment) - if strQuota := int(l.oiws) - str.bytesOutStanding; strQuota > 0 && str.state == waitingOnStreamQuota { - str.state = active - l.activeStreams.enqueue(str) - return nil - } - } - return nil -} - -func (l *loopyWriter) outgoingSettingsHandler(s *outgoingSettings) error { - return l.framer.fr.WriteSettings(s.ss...) -} - -func (l *loopyWriter) incomingSettingsHandler(s *incomingSettings) error { - if err := l.applySettings(s.ss); err != nil { - return err - } - return l.framer.fr.WriteSettingsAck() -} - -func (l *loopyWriter) headerHandler(h *headerFrame) error { - if l.side == serverSide { - if h.endStream { // Case 1.A: Server wants to close stream. - // Make sure it's not a trailers only response. - if str, ok := l.estdStreams[h.streamID]; ok { - if str.state != empty { // either active or waiting on stream quota. - // add it str's list of items. - str.itl.enqueue(h) - return nil - } - } - if err := l.writeHeader(h.streamID, h.endStream, h.hf, h.onWrite); err != nil { - return err - } - return l.cleanupStreamHandler(h.cleanup) - } - // Case 1.B: Server is responding back with headers. - str := &outStream{ - state: empty, - itl: &itemList{}, - wq: h.wq, - } - l.estdStreams[h.streamID] = str - return l.writeHeader(h.streamID, h.endStream, h.hf, h.onWrite) - } - // Case 2: Client wants to originate stream. - str := &outStream{ - id: h.streamID, - state: empty, - itl: &itemList{}, - wq: h.wq, - } - str.itl.enqueue(h) - return l.originateStream(str) -} - -func (l *loopyWriter) originateStream(str *outStream) error { - hdr := str.itl.dequeue().(*headerFrame) - sendPing, err := hdr.initStream(str.id) - if err != nil { - if err == ErrConnClosing { - return err - } - // Other errors(errStreamDrain) need not close transport. - return nil - } - if err = l.writeHeader(str.id, hdr.endStream, hdr.hf, hdr.onWrite); err != nil { - return err - } - l.estdStreams[str.id] = str - if sendPing { - return l.pingHandler(&ping{data: [8]byte{}}) - } - return nil -} - -func (l *loopyWriter) writeHeader(streamID uint32, endStream bool, hf []hpack.HeaderField, onWrite func()) error { - if onWrite != nil { - onWrite() - } - l.hBuf.Reset() - for _, f := range hf { - if err := l.hEnc.WriteField(f); err != nil { - warningf("transport: loopyWriter.writeHeader encountered error while encoding headers:", err) - } - } - var ( - err error - endHeaders, first bool - ) - first = true - for !endHeaders { - size := l.hBuf.Len() - if size > http2MaxFrameLen { - size = http2MaxFrameLen - } else { - endHeaders = true - } - if first { - first = false - err = l.framer.fr.WriteHeaders(http2.HeadersFrameParam{ - StreamID: streamID, - BlockFragment: l.hBuf.Next(size), - EndStream: endStream, - EndHeaders: endHeaders, - }) - } else { - err = l.framer.fr.WriteContinuation( - streamID, - endHeaders, - l.hBuf.Next(size), - ) - } - if err != nil { - return err - } - } - return nil -} - -func (l *loopyWriter) preprocessData(df *dataFrame) error { - str, ok := l.estdStreams[df.streamID] - if !ok { - return nil - } - // If we got data for a stream it means that - // stream was originated and the headers were sent out. - str.itl.enqueue(df) - if str.state == empty { - str.state = active - l.activeStreams.enqueue(str) - } - return nil -} - -func (l *loopyWriter) pingHandler(p *ping) error { - if !p.ack { - l.bdpEst.timesnap(p.data) - } - return l.framer.fr.WritePing(p.ack, p.data) - -} - -func (l *loopyWriter) outFlowControlSizeRequestHandler(o *outFlowControlSizeRequest) error { - o.resp <- l.sendQuota - return nil -} - -func (l *loopyWriter) cleanupStreamHandler(c *cleanupStream) error { - c.onWrite() - if str, ok := l.estdStreams[c.streamID]; ok { - // On the server side it could be a trailers-only response or - // a RST_STREAM before stream initialization thus the stream might - // not be established yet. - delete(l.estdStreams, c.streamID) - str.deleteSelf() - } - if c.rst { // If RST_STREAM needs to be sent. - if err := l.framer.fr.WriteRSTStream(c.streamID, c.rstCode); err != nil { - return err - } - } - if l.side == clientSide && l.draining && len(l.estdStreams) == 0 { - return ErrConnClosing - } - return nil -} - -func (l *loopyWriter) incomingGoAwayHandler(*incomingGoAway) error { - if l.side == clientSide { - l.draining = true - if len(l.estdStreams) == 0 { - return ErrConnClosing - } - } - return nil -} - -func (l *loopyWriter) goAwayHandler(g *goAway) error { - // Handling of outgoing GoAway is very specific to side. - if l.ssGoAwayHandler != nil { - draining, err := l.ssGoAwayHandler(g) - if err != nil { - return err - } - l.draining = draining - } - return nil -} - -func (l *loopyWriter) handle(i interface{}) error { - switch i := i.(type) { - case *incomingWindowUpdate: - return l.incomingWindowUpdateHandler(i) - case *outgoingWindowUpdate: - return l.outgoingWindowUpdateHandler(i) - case *incomingSettings: - return l.incomingSettingsHandler(i) - case *outgoingSettings: - return l.outgoingSettingsHandler(i) - case *headerFrame: - return l.headerHandler(i) - case *cleanupStream: - return l.cleanupStreamHandler(i) - case *incomingGoAway: - return l.incomingGoAwayHandler(i) - case *dataFrame: - return l.preprocessData(i) - case *ping: - return l.pingHandler(i) - case *goAway: - return l.goAwayHandler(i) - case *outFlowControlSizeRequest: - return l.outFlowControlSizeRequestHandler(i) - default: - return fmt.Errorf("transport: unknown control message type %T", i) - } -} - -func (l *loopyWriter) applySettings(ss []http2.Setting) error { - for _, s := range ss { - switch s.ID { - case http2.SettingInitialWindowSize: - o := l.oiws - l.oiws = s.Val - if o < l.oiws { - // If the new limit is greater make all depleted streams active. - for _, stream := range l.estdStreams { - if stream.state == waitingOnStreamQuota { - stream.state = active - l.activeStreams.enqueue(stream) - } - } - } - } - } - return nil -} - -func (l *loopyWriter) processData() (bool, error) { - if l.sendQuota == 0 { - return true, nil - } - str := l.activeStreams.dequeue() - if str == nil { - return true, nil - } - dataItem := str.itl.peek().(*dataFrame) - if len(dataItem.h) == 0 && len(dataItem.d) == 0 { - // Client sends out empty data frame with endStream = true - if err := l.framer.fr.WriteData(dataItem.streamID, dataItem.endStream, nil); err != nil { - return false, err - } - str.itl.dequeue() - if str.itl.isEmpty() { - str.state = empty - } else if trailer, ok := str.itl.peek().(*headerFrame); ok { // the next item is trailers. - if err := l.writeHeader(trailer.streamID, trailer.endStream, trailer.hf, trailer.onWrite); err != nil { - return false, err - } - if err := l.cleanupStreamHandler(trailer.cleanup); err != nil { - return false, nil - } - } else { - l.activeStreams.enqueue(str) - } - return false, nil - } - var ( - idx int - buf []byte - ) - if len(dataItem.h) != 0 { // data header has not been written out yet. - buf = dataItem.h - } else { - idx = 1 - buf = dataItem.d - } - size := http2MaxFrameLen - if len(buf) < size { - size = len(buf) - } - if strQuota := int(l.oiws) - str.bytesOutStanding; strQuota <= 0 { - str.state = waitingOnStreamQuota - return false, nil - } else if strQuota < size { - size = strQuota - } - - if l.sendQuota < uint32(size) { - size = int(l.sendQuota) - } - // Now that outgoing flow controls are checked we can replenish str's write quota - str.wq.replenish(size) - var endStream bool - // This last data message on this stream and all - // of it can be written in this go. - if dataItem.endStream && size == len(buf) { - // buf contains either data or it contains header but data is empty. - if idx == 1 || len(dataItem.d) == 0 { - endStream = true - } - } - if dataItem.onEachWrite != nil { - dataItem.onEachWrite() - } - if err := l.framer.fr.WriteData(dataItem.streamID, endStream, buf[:size]); err != nil { - return false, err - } - buf = buf[size:] - str.bytesOutStanding += size - l.sendQuota -= uint32(size) - if idx == 0 { - dataItem.h = buf - } else { - dataItem.d = buf - } - - if len(dataItem.h) == 0 && len(dataItem.d) == 0 { // All the data from that message was written out. - str.itl.dequeue() - } - if str.itl.isEmpty() { - str.state = empty - } else if trailer, ok := str.itl.peek().(*headerFrame); ok { // The next item is trailers. - if err := l.writeHeader(trailer.streamID, trailer.endStream, trailer.hf, trailer.onWrite); err != nil { - return false, err - } - if err := l.cleanupStreamHandler(trailer.cleanup); err != nil { - return false, err - } - } else if int(l.oiws)-str.bytesOutStanding <= 0 { // Ran out of stream quota. - str.state = waitingOnStreamQuota - } else { // Otherwise add it back to the list of active streams. - l.activeStreams.enqueue(str) - } - return false, nil -} diff --git a/vendor/google.golang.org/grpc/transport/flowcontrol.go b/vendor/google.golang.org/grpc/transport/flowcontrol.go deleted file mode 100644 index 378f5c4502c..00000000000 --- a/vendor/google.golang.org/grpc/transport/flowcontrol.go +++ /dev/null @@ -1,236 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 transport - -import ( - "fmt" - "math" - "sync" - "sync/atomic" - "time" -) - -const ( - // The default value of flow control window size in HTTP2 spec. - defaultWindowSize = 65535 - // The initial window size for flow control. - initialWindowSize = defaultWindowSize // for an RPC - infinity = time.Duration(math.MaxInt64) - defaultClientKeepaliveTime = infinity - defaultClientKeepaliveTimeout = 20 * time.Second - defaultMaxStreamsClient = 100 - defaultMaxConnectionIdle = infinity - defaultMaxConnectionAge = infinity - defaultMaxConnectionAgeGrace = infinity - defaultServerKeepaliveTime = 2 * time.Hour - defaultServerKeepaliveTimeout = 20 * time.Second - defaultKeepalivePolicyMinTime = 5 * time.Minute - // max window limit set by HTTP2 Specs. - maxWindowSize = math.MaxInt32 - // defaultWriteQuota is the default value for number of data - // bytes that each stream can schedule before some of it being - // flushed out. - defaultWriteQuota = 64 * 1024 -) - -// writeQuota is a soft limit on the amount of data a stream can -// schedule before some of it is written out. -type writeQuota struct { - quota int32 - // get waits on read from when quota goes less than or equal to zero. - // replenish writes on it when quota goes positive again. - ch chan struct{} - // done is triggered in error case. - done <-chan struct{} -} - -func newWriteQuota(sz int32, done <-chan struct{}) *writeQuota { - return &writeQuota{ - quota: sz, - ch: make(chan struct{}, 1), - done: done, - } -} - -func (w *writeQuota) get(sz int32) error { - for { - if atomic.LoadInt32(&w.quota) > 0 { - atomic.AddInt32(&w.quota, -sz) - return nil - } - select { - case <-w.ch: - continue - case <-w.done: - return errStreamDone - } - } -} - -func (w *writeQuota) replenish(n int) { - sz := int32(n) - a := atomic.AddInt32(&w.quota, sz) - b := a - sz - if b <= 0 && a > 0 { - select { - case w.ch <- struct{}{}: - default: - } - } -} - -type trInFlow struct { - limit uint32 - unacked uint32 - effectiveWindowSize uint32 -} - -func (f *trInFlow) newLimit(n uint32) uint32 { - d := n - f.limit - f.limit = n - f.updateEffectiveWindowSize() - return d -} - -func (f *trInFlow) onData(n uint32) uint32 { - f.unacked += n - if f.unacked >= f.limit/4 { - w := f.unacked - f.unacked = 0 - f.updateEffectiveWindowSize() - return w - } - f.updateEffectiveWindowSize() - return 0 -} - -func (f *trInFlow) reset() uint32 { - w := f.unacked - f.unacked = 0 - f.updateEffectiveWindowSize() - return w -} - -func (f *trInFlow) updateEffectiveWindowSize() { - atomic.StoreUint32(&f.effectiveWindowSize, f.limit-f.unacked) -} - -func (f *trInFlow) getSize() uint32 { - return atomic.LoadUint32(&f.effectiveWindowSize) -} - -// TODO(mmukhi): Simplify this code. -// inFlow deals with inbound flow control -type inFlow struct { - mu sync.Mutex - // The inbound flow control limit for pending data. - limit uint32 - // pendingData is the overall data which have been received but not been - // consumed by applications. - pendingData uint32 - // The amount of data the application has consumed but grpc has not sent - // window update for them. Used to reduce window update frequency. - pendingUpdate uint32 - // delta is the extra window update given by receiver when an application - // is reading data bigger in size than the inFlow limit. - delta uint32 -} - -// newLimit updates the inflow window to a new value n. -// It assumes that n is always greater than the old limit. -func (f *inFlow) newLimit(n uint32) uint32 { - f.mu.Lock() - d := n - f.limit - f.limit = n - f.mu.Unlock() - return d -} - -func (f *inFlow) maybeAdjust(n uint32) uint32 { - if n > uint32(math.MaxInt32) { - n = uint32(math.MaxInt32) - } - f.mu.Lock() - // estSenderQuota is the receiver's view of the maximum number of bytes the sender - // can send without a window update. - estSenderQuota := int32(f.limit - (f.pendingData + f.pendingUpdate)) - // estUntransmittedData is the maximum number of bytes the sends might not have put - // on the wire yet. A value of 0 or less means that we have already received all or - // more bytes than the application is requesting to read. - estUntransmittedData := int32(n - f.pendingData) // Casting into int32 since it could be negative. - // This implies that unless we send a window update, the sender won't be able to send all the bytes - // for this message. Therefore we must send an update over the limit since there's an active read - // request from the application. - if estUntransmittedData > estSenderQuota { - // Sender's window shouldn't go more than 2^31 - 1 as specified in the HTTP spec. - if f.limit+n > maxWindowSize { - f.delta = maxWindowSize - f.limit - } else { - // Send a window update for the whole message and not just the difference between - // estUntransmittedData and estSenderQuota. This will be helpful in case the message - // is padded; We will fallback on the current available window(at least a 1/4th of the limit). - f.delta = n - } - f.mu.Unlock() - return f.delta - } - f.mu.Unlock() - return 0 -} - -// onData is invoked when some data frame is received. It updates pendingData. -func (f *inFlow) onData(n uint32) error { - f.mu.Lock() - f.pendingData += n - if f.pendingData+f.pendingUpdate > f.limit+f.delta { - limit := f.limit - rcvd := f.pendingData + f.pendingUpdate - f.mu.Unlock() - return fmt.Errorf("received %d-bytes data exceeding the limit %d bytes", rcvd, limit) - } - f.mu.Unlock() - return nil -} - -// onRead is invoked when the application reads the data. It returns the window size -// to be sent to the peer. -func (f *inFlow) onRead(n uint32) uint32 { - f.mu.Lock() - if f.pendingData == 0 { - f.mu.Unlock() - return 0 - } - f.pendingData -= n - if n > f.delta { - n -= f.delta - f.delta = 0 - } else { - f.delta -= n - n = 0 - } - f.pendingUpdate += n - if f.pendingUpdate >= f.limit/4 { - wu := f.pendingUpdate - f.pendingUpdate = 0 - f.mu.Unlock() - return wu - } - f.mu.Unlock() - return 0 -} diff --git a/vendor/google.golang.org/grpc/transport/go16.go b/vendor/google.golang.org/grpc/transport/go16.go deleted file mode 100644 index 5babcf9b877..00000000000 --- a/vendor/google.golang.org/grpc/transport/go16.go +++ /dev/null @@ -1,51 +0,0 @@ -// +build go1.6,!go1.7 - -/* - * - * Copyright 2016 gRPC 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 transport - -import ( - "net" - "net/http" - - "google.golang.org/grpc/codes" - - "golang.org/x/net/context" -) - -// dialContext connects to the address on the named network. -func dialContext(ctx context.Context, network, address string) (net.Conn, error) { - return (&net.Dialer{Cancel: ctx.Done()}).Dial(network, address) -} - -// ContextErr converts the error from context package into a StreamError. -func ContextErr(err error) StreamError { - switch err { - case context.DeadlineExceeded: - return streamErrorf(codes.DeadlineExceeded, "%v", err) - case context.Canceled: - return streamErrorf(codes.Canceled, "%v", err) - } - return streamErrorf(codes.Internal, "Unexpected error from context packet: %v", err) -} - -// contextFromRequest returns a background context. -func contextFromRequest(r *http.Request) context.Context { - return context.Background() -} diff --git a/vendor/google.golang.org/grpc/transport/go17.go b/vendor/google.golang.org/grpc/transport/go17.go deleted file mode 100644 index b7fa6bdb9ca..00000000000 --- a/vendor/google.golang.org/grpc/transport/go17.go +++ /dev/null @@ -1,52 +0,0 @@ -// +build go1.7 - -/* - * - * Copyright 2016 gRPC 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 transport - -import ( - "context" - "net" - "net/http" - - "google.golang.org/grpc/codes" - - netctx "golang.org/x/net/context" -) - -// dialContext connects to the address on the named network. -func dialContext(ctx context.Context, network, address string) (net.Conn, error) { - return (&net.Dialer{}).DialContext(ctx, network, address) -} - -// ContextErr converts the error from context package into a StreamError. -func ContextErr(err error) StreamError { - switch err { - case context.DeadlineExceeded, netctx.DeadlineExceeded: - return streamErrorf(codes.DeadlineExceeded, "%v", err) - case context.Canceled, netctx.Canceled: - return streamErrorf(codes.Canceled, "%v", err) - } - return streamErrorf(codes.Internal, "Unexpected error from context packet: %v", err) -} - -// contextFromRequest returns a context from the HTTP Request. -func contextFromRequest(r *http.Request) context.Context { - return r.Context() -} diff --git a/vendor/google.golang.org/grpc/transport/handler_server.go b/vendor/google.golang.org/grpc/transport/handler_server.go deleted file mode 100644 index f71b7482174..00000000000 --- a/vendor/google.golang.org/grpc/transport/handler_server.go +++ /dev/null @@ -1,451 +0,0 @@ -/* - * - * Copyright 2016 gRPC 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. - * - */ - -// This file is the implementation of a gRPC server using HTTP/2 which -// uses the standard Go http2 Server implementation (via the -// http.Handler interface), rather than speaking low-level HTTP/2 -// frames itself. It is the implementation of *grpc.Server.ServeHTTP. - -package transport - -import ( - "errors" - "fmt" - "io" - "net" - "net/http" - "strings" - "sync" - "time" - - "github.com/golang/protobuf/proto" - "golang.org/x/net/context" - "golang.org/x/net/http2" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/peer" - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" -) - -// NewServerHandlerTransport returns a ServerTransport handling gRPC -// from inside an http.Handler. It requires that the http Server -// supports HTTP/2. -func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request, stats stats.Handler) (ServerTransport, error) { - if r.ProtoMajor != 2 { - return nil, errors.New("gRPC requires HTTP/2") - } - if r.Method != "POST" { - return nil, errors.New("invalid gRPC request method") - } - contentType := r.Header.Get("Content-Type") - // TODO: do we assume contentType is lowercase? we did before - contentSubtype, validContentType := contentSubtype(contentType) - if !validContentType { - return nil, errors.New("invalid gRPC request content-type") - } - if _, ok := w.(http.Flusher); !ok { - return nil, errors.New("gRPC requires a ResponseWriter supporting http.Flusher") - } - if _, ok := w.(http.CloseNotifier); !ok { - return nil, errors.New("gRPC requires a ResponseWriter supporting http.CloseNotifier") - } - - st := &serverHandlerTransport{ - rw: w, - req: r, - closedCh: make(chan struct{}), - writes: make(chan func()), - contentType: contentType, - contentSubtype: contentSubtype, - stats: stats, - } - - if v := r.Header.Get("grpc-timeout"); v != "" { - to, err := decodeTimeout(v) - if err != nil { - return nil, streamErrorf(codes.Internal, "malformed time-out: %v", err) - } - st.timeoutSet = true - st.timeout = to - } - - metakv := []string{"content-type", contentType} - if r.Host != "" { - metakv = append(metakv, ":authority", r.Host) - } - for k, vv := range r.Header { - k = strings.ToLower(k) - if isReservedHeader(k) && !isWhitelistedHeader(k) { - continue - } - for _, v := range vv { - v, err := decodeMetadataHeader(k, v) - if err != nil { - return nil, streamErrorf(codes.Internal, "malformed binary metadata: %v", err) - } - metakv = append(metakv, k, v) - } - } - st.headerMD = metadata.Pairs(metakv...) - - return st, nil -} - -// serverHandlerTransport is an implementation of ServerTransport -// which replies to exactly one gRPC request (exactly one HTTP request), -// using the net/http.Handler interface. This http.Handler is guaranteed -// at this point to be speaking over HTTP/2, so it's able to speak valid -// gRPC. -type serverHandlerTransport struct { - rw http.ResponseWriter - req *http.Request - timeoutSet bool - timeout time.Duration - didCommonHeaders bool - - headerMD metadata.MD - - closeOnce sync.Once - closedCh chan struct{} // closed on Close - - // writes is a channel of code to run serialized in the - // ServeHTTP (HandleStreams) goroutine. The channel is closed - // when WriteStatus is called. - writes chan func() - - // block concurrent WriteStatus calls - // e.g. grpc/(*serverStream).SendMsg/RecvMsg - writeStatusMu sync.Mutex - - // we just mirror the request content-type - contentType string - // we store both contentType and contentSubtype so we don't keep recreating them - // TODO make sure this is consistent across handler_server and http2_server - contentSubtype string - - stats stats.Handler -} - -func (ht *serverHandlerTransport) Close() error { - ht.closeOnce.Do(ht.closeCloseChanOnce) - return nil -} - -func (ht *serverHandlerTransport) closeCloseChanOnce() { close(ht.closedCh) } - -func (ht *serverHandlerTransport) RemoteAddr() net.Addr { return strAddr(ht.req.RemoteAddr) } - -// strAddr is a net.Addr backed by either a TCP "ip:port" string, or -// the empty string if unknown. -type strAddr string - -func (a strAddr) Network() string { - if a != "" { - // Per the documentation on net/http.Request.RemoteAddr, if this is - // set, it's set to the IP:port of the peer (hence, TCP): - // https://golang.org/pkg/net/http/#Request - // - // If we want to support Unix sockets later, we can - // add our own grpc-specific convention within the - // grpc codebase to set RemoteAddr to a different - // format, or probably better: we can attach it to the - // context and use that from serverHandlerTransport.RemoteAddr. - return "tcp" - } - return "" -} - -func (a strAddr) String() string { return string(a) } - -// do runs fn in the ServeHTTP goroutine. -func (ht *serverHandlerTransport) do(fn func()) error { - // Avoid a panic writing to closed channel. Imperfect but maybe good enough. - select { - case <-ht.closedCh: - return ErrConnClosing - default: - select { - case ht.writes <- fn: - return nil - case <-ht.closedCh: - return ErrConnClosing - } - } -} - -func (ht *serverHandlerTransport) WriteStatus(s *Stream, st *status.Status) error { - ht.writeStatusMu.Lock() - defer ht.writeStatusMu.Unlock() - - err := ht.do(func() { - ht.writeCommonHeaders(s) - - // And flush, in case no header or body has been sent yet. - // This forces a separation of headers and trailers if this is the - // first call (for example, in end2end tests's TestNoService). - ht.rw.(http.Flusher).Flush() - - h := ht.rw.Header() - h.Set("Grpc-Status", fmt.Sprintf("%d", st.Code())) - if m := st.Message(); m != "" { - h.Set("Grpc-Message", encodeGrpcMessage(m)) - } - - if p := st.Proto(); p != nil && len(p.Details) > 0 { - stBytes, err := proto.Marshal(p) - if err != nil { - // TODO: return error instead, when callers are able to handle it. - panic(err) - } - - h.Set("Grpc-Status-Details-Bin", encodeBinHeader(stBytes)) - } - - if md := s.Trailer(); len(md) > 0 { - for k, vv := range md { - // Clients don't tolerate reading restricted headers after some non restricted ones were sent. - if isReservedHeader(k) { - continue - } - for _, v := range vv { - // http2 ResponseWriter mechanism to send undeclared Trailers after - // the headers have possibly been written. - h.Add(http2.TrailerPrefix+k, encodeMetadataHeader(k, v)) - } - } - } - }) - - if err == nil { // transport has not been closed - if ht.stats != nil { - ht.stats.HandleRPC(s.Context(), &stats.OutTrailer{}) - } - ht.Close() - close(ht.writes) - } - return err -} - -// writeCommonHeaders sets common headers on the first write -// call (Write, WriteHeader, or WriteStatus). -func (ht *serverHandlerTransport) writeCommonHeaders(s *Stream) { - if ht.didCommonHeaders { - return - } - ht.didCommonHeaders = true - - h := ht.rw.Header() - h["Date"] = nil // suppress Date to make tests happy; TODO: restore - h.Set("Content-Type", ht.contentType) - - // Predeclare trailers we'll set later in WriteStatus (after the body). - // This is a SHOULD in the HTTP RFC, and the way you add (known) - // Trailers per the net/http.ResponseWriter contract. - // See https://golang.org/pkg/net/http/#ResponseWriter - // and https://golang.org/pkg/net/http/#example_ResponseWriter_trailers - h.Add("Trailer", "Grpc-Status") - h.Add("Trailer", "Grpc-Message") - h.Add("Trailer", "Grpc-Status-Details-Bin") - - if s.sendCompress != "" { - h.Set("Grpc-Encoding", s.sendCompress) - } -} - -func (ht *serverHandlerTransport) Write(s *Stream, hdr []byte, data []byte, opts *Options) error { - return ht.do(func() { - ht.writeCommonHeaders(s) - ht.rw.Write(hdr) - ht.rw.Write(data) - if !opts.Delay { - ht.rw.(http.Flusher).Flush() - } - }) -} - -func (ht *serverHandlerTransport) WriteHeader(s *Stream, md metadata.MD) error { - err := ht.do(func() { - ht.writeCommonHeaders(s) - h := ht.rw.Header() - for k, vv := range md { - // Clients don't tolerate reading restricted headers after some non restricted ones were sent. - if isReservedHeader(k) { - continue - } - for _, v := range vv { - v = encodeMetadataHeader(k, v) - h.Add(k, v) - } - } - ht.rw.WriteHeader(200) - ht.rw.(http.Flusher).Flush() - }) - - if err == nil { - if ht.stats != nil { - ht.stats.HandleRPC(s.Context(), &stats.OutHeader{}) - } - } - return err -} - -func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), traceCtx func(context.Context, string) context.Context) { - // With this transport type there will be exactly 1 stream: this HTTP request. - - ctx := contextFromRequest(ht.req) - var cancel context.CancelFunc - if ht.timeoutSet { - ctx, cancel = context.WithTimeout(ctx, ht.timeout) - } else { - ctx, cancel = context.WithCancel(ctx) - } - - // requestOver is closed when either the request's context is done - // or the status has been written via WriteStatus. - requestOver := make(chan struct{}) - - // clientGone receives a single value if peer is gone, either - // because the underlying connection is dead or because the - // peer sends an http2 RST_STREAM. - clientGone := ht.rw.(http.CloseNotifier).CloseNotify() - go func() { - select { - case <-requestOver: - return - case <-ht.closedCh: - case <-clientGone: - } - cancel() - }() - - req := ht.req - - s := &Stream{ - id: 0, // irrelevant - requestRead: func(int) {}, - cancel: cancel, - buf: newRecvBuffer(), - st: ht, - method: req.URL.Path, - recvCompress: req.Header.Get("grpc-encoding"), - contentSubtype: ht.contentSubtype, - } - pr := &peer.Peer{ - Addr: ht.RemoteAddr(), - } - if req.TLS != nil { - pr.AuthInfo = credentials.TLSInfo{State: *req.TLS} - } - ctx = metadata.NewIncomingContext(ctx, ht.headerMD) - s.ctx = peer.NewContext(ctx, pr) - if ht.stats != nil { - s.ctx = ht.stats.TagRPC(s.ctx, &stats.RPCTagInfo{FullMethodName: s.method}) - inHeader := &stats.InHeader{ - FullMethod: s.method, - RemoteAddr: ht.RemoteAddr(), - Compression: s.recvCompress, - } - ht.stats.HandleRPC(s.ctx, inHeader) - } - s.trReader = &transportReader{ - reader: &recvBufferReader{ctx: s.ctx, ctxDone: s.ctx.Done(), recv: s.buf}, - windowHandler: func(int) {}, - } - - // readerDone is closed when the Body.Read-ing goroutine exits. - readerDone := make(chan struct{}) - go func() { - defer close(readerDone) - - // TODO: minimize garbage, optimize recvBuffer code/ownership - const readSize = 8196 - for buf := make([]byte, readSize); ; { - n, err := req.Body.Read(buf) - if n > 0 { - s.buf.put(recvMsg{data: buf[:n:n]}) - buf = buf[n:] - } - if err != nil { - s.buf.put(recvMsg{err: mapRecvMsgError(err)}) - return - } - if len(buf) == 0 { - buf = make([]byte, readSize) - } - } - }() - - // startStream is provided by the *grpc.Server's serveStreams. - // It starts a goroutine serving s and exits immediately. - // The goroutine that is started is the one that then calls - // into ht, calling WriteHeader, Write, WriteStatus, Close, etc. - startStream(s) - - ht.runStream() - close(requestOver) - - // Wait for reading goroutine to finish. - req.Body.Close() - <-readerDone -} - -func (ht *serverHandlerTransport) runStream() { - for { - select { - case fn, ok := <-ht.writes: - if !ok { - return - } - fn() - case <-ht.closedCh: - return - } - } -} - -func (ht *serverHandlerTransport) IncrMsgSent() {} - -func (ht *serverHandlerTransport) IncrMsgRecv() {} - -func (ht *serverHandlerTransport) Drain() { - panic("Drain() is not implemented") -} - -// mapRecvMsgError returns the non-nil err into the appropriate -// error value as expected by callers of *grpc.parser.recvMsg. -// In particular, in can only be: -// * io.EOF -// * io.ErrUnexpectedEOF -// * of type transport.ConnectionError -// * of type transport.StreamError -func mapRecvMsgError(err error) error { - if err == io.EOF || err == io.ErrUnexpectedEOF { - return err - } - if se, ok := err.(http2.StreamError); ok { - if code, ok := http2ErrConvTab[se.Code]; ok { - return StreamError{ - Code: code, - Desc: se.Error(), - } - } - } - return connectionErrorf(true, err, err.Error()) -} diff --git a/vendor/google.golang.org/grpc/transport/http2_client.go b/vendor/google.golang.org/grpc/transport/http2_client.go deleted file mode 100644 index 1fdabd954ef..00000000000 --- a/vendor/google.golang.org/grpc/transport/http2_client.go +++ /dev/null @@ -1,1284 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 transport - -import ( - "io" - "math" - "net" - "strings" - "sync" - "sync/atomic" - "time" - - "golang.org/x/net/context" - "golang.org/x/net/http2" - "golang.org/x/net/http2/hpack" - - "google.golang.org/grpc/channelz" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/keepalive" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/peer" - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" -) - -// http2Client implements the ClientTransport interface with HTTP2. -type http2Client struct { - ctx context.Context - cancel context.CancelFunc - ctxDone <-chan struct{} // Cache the ctx.Done() chan. - userAgent string - md interface{} - conn net.Conn // underlying communication channel - loopy *loopyWriter - remoteAddr net.Addr - localAddr net.Addr - authInfo credentials.AuthInfo // auth info about the connection - - readerDone chan struct{} // sync point to enable testing. - writerDone chan struct{} // sync point to enable testing. - // goAway is closed to notify the upper layer (i.e., addrConn.transportMonitor) - // that the server sent GoAway on this transport. - goAway chan struct{} - // awakenKeepalive is used to wake up keepalive when after it has gone dormant. - awakenKeepalive chan struct{} - - framer *framer - // controlBuf delivers all the control related tasks (e.g., window - // updates, reset streams, and various settings) to the controller. - controlBuf *controlBuffer - fc *trInFlow - // The scheme used: https if TLS is on, http otherwise. - scheme string - - isSecure bool - - creds []credentials.PerRPCCredentials - - // Boolean to keep track of reading activity on transport. - // 1 is true and 0 is false. - activity uint32 // Accessed atomically. - kp keepalive.ClientParameters - - statsHandler stats.Handler - - initialWindowSize int32 - - bdpEst *bdpEstimator - // onSuccess is a callback that client transport calls upon - // receiving server preface to signal that a succefull HTTP2 - // connection was established. - onSuccess func() - - maxConcurrentStreams uint32 - streamQuota int64 - streamsQuotaAvailable chan struct{} - waitingStreams uint32 - nextID uint32 - - mu sync.Mutex // guard the following variables - state transportState - activeStreams map[uint32]*Stream - // prevGoAway ID records the Last-Stream-ID in the previous GOAway frame. - prevGoAwayID uint32 - // goAwayReason records the http2.ErrCode and debug data received with the - // GoAway frame. - goAwayReason GoAwayReason - - // Fields below are for channelz metric collection. - channelzID int64 // channelz unique identification number - czmu sync.RWMutex - kpCount int64 - // The number of streams that have started, including already finished ones. - streamsStarted int64 - // The number of streams that have ended successfully by receiving EoS bit set - // frame from server. - streamsSucceeded int64 - streamsFailed int64 - lastStreamCreated time.Time - msgSent int64 - msgRecv int64 - lastMsgSent time.Time - lastMsgRecv time.Time -} - -func dial(ctx context.Context, fn func(context.Context, string) (net.Conn, error), addr string) (net.Conn, error) { - if fn != nil { - return fn(ctx, addr) - } - return dialContext(ctx, "tcp", addr) -} - -func isTemporary(err error) bool { - switch err := err.(type) { - case interface { - Temporary() bool - }: - return err.Temporary() - case interface { - Timeout() bool - }: - // Timeouts may be resolved upon retry, and are thus treated as - // temporary. - return err.Timeout() - } - return true -} - -// newHTTP2Client constructs a connected ClientTransport to addr based on HTTP2 -// and starts to receive messages on it. Non-nil error returns if construction -// fails. -func newHTTP2Client(connectCtx, ctx context.Context, addr TargetInfo, opts ConnectOptions, onSuccess func()) (_ ClientTransport, err error) { - scheme := "http" - ctx, cancel := context.WithCancel(ctx) - defer func() { - if err != nil { - cancel() - } - }() - - conn, err := dial(connectCtx, opts.Dialer, addr.Addr) - if err != nil { - if opts.FailOnNonTempDialError { - return nil, connectionErrorf(isTemporary(err), err, "transport: error while dialing: %v", err) - } - return nil, connectionErrorf(true, err, "transport: Error while dialing %v", err) - } - // Any further errors will close the underlying connection - defer func(conn net.Conn) { - if err != nil { - conn.Close() - } - }(conn) - var ( - isSecure bool - authInfo credentials.AuthInfo - ) - if creds := opts.TransportCredentials; creds != nil { - scheme = "https" - conn, authInfo, err = creds.ClientHandshake(connectCtx, addr.Authority, conn) - if err != nil { - return nil, connectionErrorf(isTemporary(err), err, "transport: authentication handshake failed: %v", err) - } - isSecure = true - } - kp := opts.KeepaliveParams - // Validate keepalive parameters. - if kp.Time == 0 { - kp.Time = defaultClientKeepaliveTime - } - if kp.Timeout == 0 { - kp.Timeout = defaultClientKeepaliveTimeout - } - dynamicWindow := true - icwz := int32(initialWindowSize) - if opts.InitialConnWindowSize >= defaultWindowSize { - icwz = opts.InitialConnWindowSize - dynamicWindow = false - } - writeBufSize := defaultWriteBufSize - if opts.WriteBufferSize > 0 { - writeBufSize = opts.WriteBufferSize - } - readBufSize := defaultReadBufSize - if opts.ReadBufferSize > 0 { - readBufSize = opts.ReadBufferSize - } - t := &http2Client{ - ctx: ctx, - ctxDone: ctx.Done(), // Cache Done chan. - cancel: cancel, - userAgent: opts.UserAgent, - md: addr.Metadata, - conn: conn, - remoteAddr: conn.RemoteAddr(), - localAddr: conn.LocalAddr(), - authInfo: authInfo, - readerDone: make(chan struct{}), - writerDone: make(chan struct{}), - goAway: make(chan struct{}), - awakenKeepalive: make(chan struct{}, 1), - framer: newFramer(conn, writeBufSize, readBufSize), - fc: &trInFlow{limit: uint32(icwz)}, - scheme: scheme, - activeStreams: make(map[uint32]*Stream), - isSecure: isSecure, - creds: opts.PerRPCCredentials, - kp: kp, - statsHandler: opts.StatsHandler, - initialWindowSize: initialWindowSize, - onSuccess: onSuccess, - nextID: 1, - maxConcurrentStreams: defaultMaxStreamsClient, - streamQuota: defaultMaxStreamsClient, - streamsQuotaAvailable: make(chan struct{}, 1), - } - t.controlBuf = newControlBuffer(t.ctxDone) - if opts.InitialWindowSize >= defaultWindowSize { - t.initialWindowSize = opts.InitialWindowSize - dynamicWindow = false - } - if dynamicWindow { - t.bdpEst = &bdpEstimator{ - bdp: initialWindowSize, - updateFlowControl: t.updateFlowControl, - } - } - // Make sure awakenKeepalive can't be written upon. - // keepalive routine will make it writable, if need be. - t.awakenKeepalive <- struct{}{} - if t.statsHandler != nil { - t.ctx = t.statsHandler.TagConn(t.ctx, &stats.ConnTagInfo{ - RemoteAddr: t.remoteAddr, - LocalAddr: t.localAddr, - }) - connBegin := &stats.ConnBegin{ - Client: true, - } - t.statsHandler.HandleConn(t.ctx, connBegin) - } - if channelz.IsOn() { - t.channelzID = channelz.RegisterNormalSocket(t, opts.ChannelzParentID, "") - } - // Start the reader goroutine for incoming message. Each transport has - // a dedicated goroutine which reads HTTP2 frame from network. Then it - // dispatches the frame to the corresponding stream entity. - go t.reader() - // Send connection preface to server. - n, err := t.conn.Write(clientPreface) - if err != nil { - t.Close() - return nil, connectionErrorf(true, err, "transport: failed to write client preface: %v", err) - } - if n != len(clientPreface) { - t.Close() - return nil, connectionErrorf(true, err, "transport: preface mismatch, wrote %d bytes; want %d", n, len(clientPreface)) - } - if t.initialWindowSize != defaultWindowSize { - err = t.framer.fr.WriteSettings(http2.Setting{ - ID: http2.SettingInitialWindowSize, - Val: uint32(t.initialWindowSize), - }) - } else { - err = t.framer.fr.WriteSettings() - } - if err != nil { - t.Close() - return nil, connectionErrorf(true, err, "transport: failed to write initial settings frame: %v", err) - } - // Adjust the connection flow control window if needed. - if delta := uint32(icwz - defaultWindowSize); delta > 0 { - if err := t.framer.fr.WriteWindowUpdate(0, delta); err != nil { - t.Close() - return nil, connectionErrorf(true, err, "transport: failed to write window update: %v", err) - } - } - t.framer.writer.Flush() - go func() { - t.loopy = newLoopyWriter(clientSide, t.framer, t.controlBuf, t.bdpEst) - t.loopy.run() - t.conn.Close() - close(t.writerDone) - }() - if t.kp.Time != infinity { - go t.keepalive() - } - return t, nil -} - -func (t *http2Client) newStream(ctx context.Context, callHdr *CallHdr) *Stream { - // TODO(zhaoq): Handle uint32 overflow of Stream.id. - s := &Stream{ - done: make(chan struct{}), - method: callHdr.Method, - sendCompress: callHdr.SendCompress, - buf: newRecvBuffer(), - headerChan: make(chan struct{}), - contentSubtype: callHdr.ContentSubtype, - } - s.wq = newWriteQuota(defaultWriteQuota, s.done) - s.requestRead = func(n int) { - t.adjustWindow(s, uint32(n)) - } - // The client side stream context should have exactly the same life cycle with the user provided context. - // That means, s.ctx should be read-only. And s.ctx is done iff ctx is done. - // So we use the original context here instead of creating a copy. - s.ctx = ctx - s.trReader = &transportReader{ - reader: &recvBufferReader{ - ctx: s.ctx, - ctxDone: s.ctx.Done(), - recv: s.buf, - }, - windowHandler: func(n int) { - t.updateWindow(s, uint32(n)) - }, - } - return s -} - -func (t *http2Client) getPeer() *peer.Peer { - pr := &peer.Peer{ - Addr: t.remoteAddr, - } - // Attach Auth info if there is any. - if t.authInfo != nil { - pr.AuthInfo = t.authInfo - } - return pr -} - -func (t *http2Client) createHeaderFields(ctx context.Context, callHdr *CallHdr) ([]hpack.HeaderField, error) { - aud := t.createAudience(callHdr) - authData, err := t.getTrAuthData(ctx, aud) - if err != nil { - return nil, err - } - callAuthData, err := t.getCallAuthData(ctx, aud, callHdr) - if err != nil { - return nil, err - } - // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields - // first and create a slice of that exact size. - // Make the slice of certain predictable size to reduce allocations made by append. - hfLen := 7 // :method, :scheme, :path, :authority, content-type, user-agent, te - hfLen += len(authData) + len(callAuthData) - headerFields := make([]hpack.HeaderField, 0, hfLen) - headerFields = append(headerFields, hpack.HeaderField{Name: ":method", Value: "POST"}) - headerFields = append(headerFields, hpack.HeaderField{Name: ":scheme", Value: t.scheme}) - headerFields = append(headerFields, hpack.HeaderField{Name: ":path", Value: callHdr.Method}) - headerFields = append(headerFields, hpack.HeaderField{Name: ":authority", Value: callHdr.Host}) - headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: contentType(callHdr.ContentSubtype)}) - headerFields = append(headerFields, hpack.HeaderField{Name: "user-agent", Value: t.userAgent}) - headerFields = append(headerFields, hpack.HeaderField{Name: "te", Value: "trailers"}) - - if callHdr.SendCompress != "" { - headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-encoding", Value: callHdr.SendCompress}) - } - if dl, ok := ctx.Deadline(); ok { - // Send out timeout regardless its value. The server can detect timeout context by itself. - // TODO(mmukhi): Perhaps this field should be updated when actually writing out to the wire. - timeout := dl.Sub(time.Now()) - headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-timeout", Value: encodeTimeout(timeout)}) - } - for k, v := range authData { - headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) - } - for k, v := range callAuthData { - headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) - } - if b := stats.OutgoingTags(ctx); b != nil { - headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-tags-bin", Value: encodeBinHeader(b)}) - } - if b := stats.OutgoingTrace(ctx); b != nil { - headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-trace-bin", Value: encodeBinHeader(b)}) - } - - if md, added, ok := metadata.FromOutgoingContextRaw(ctx); ok { - var k string - for _, vv := range added { - for i, v := range vv { - if i%2 == 0 { - k = v - continue - } - // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set. - if isReservedHeader(k) { - continue - } - headerFields = append(headerFields, hpack.HeaderField{Name: strings.ToLower(k), Value: encodeMetadataHeader(k, v)}) - } - } - for k, vv := range md { - // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set. - if isReservedHeader(k) { - continue - } - for _, v := range vv { - headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) - } - } - } - if md, ok := t.md.(*metadata.MD); ok { - for k, vv := range *md { - if isReservedHeader(k) { - continue - } - for _, v := range vv { - headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) - } - } - } - return headerFields, nil -} - -func (t *http2Client) createAudience(callHdr *CallHdr) string { - // Create an audience string only if needed. - if len(t.creds) == 0 && callHdr.Creds == nil { - return "" - } - // Construct URI required to get auth request metadata. - // Omit port if it is the default one. - host := strings.TrimSuffix(callHdr.Host, ":443") - pos := strings.LastIndex(callHdr.Method, "/") - if pos == -1 { - pos = len(callHdr.Method) - } - return "https://" + host + callHdr.Method[:pos] -} - -func (t *http2Client) getTrAuthData(ctx context.Context, audience string) (map[string]string, error) { - authData := map[string]string{} - for _, c := range t.creds { - data, err := c.GetRequestMetadata(ctx, audience) - if err != nil { - if _, ok := status.FromError(err); ok { - return nil, err - } - - return nil, streamErrorf(codes.Unauthenticated, "transport: %v", err) - } - for k, v := range data { - // Capital header names are illegal in HTTP/2. - k = strings.ToLower(k) - authData[k] = v - } - } - return authData, nil -} - -func (t *http2Client) getCallAuthData(ctx context.Context, audience string, callHdr *CallHdr) (map[string]string, error) { - callAuthData := map[string]string{} - // Check if credentials.PerRPCCredentials were provided via call options. - // Note: if these credentials are provided both via dial options and call - // options, then both sets of credentials will be applied. - if callCreds := callHdr.Creds; callCreds != nil { - if !t.isSecure && callCreds.RequireTransportSecurity() { - return nil, streamErrorf(codes.Unauthenticated, "transport: cannot send secure credentials on an insecure connection") - } - data, err := callCreds.GetRequestMetadata(ctx, audience) - if err != nil { - return nil, streamErrorf(codes.Internal, "transport: %v", err) - } - for k, v := range data { - // Capital header names are illegal in HTTP/2 - k = strings.ToLower(k) - callAuthData[k] = v - } - } - return callAuthData, nil -} - -// NewStream creates a stream and registers it into the transport as "active" -// streams. -func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Stream, err error) { - ctx = peer.NewContext(ctx, t.getPeer()) - headerFields, err := t.createHeaderFields(ctx, callHdr) - if err != nil { - return nil, err - } - s := t.newStream(ctx, callHdr) - cleanup := func(err error) { - if s.swapState(streamDone) == streamDone { - // If it was already done, return. - return - } - // The stream was unprocessed by the server. - atomic.StoreUint32(&s.unprocessed, 1) - s.write(recvMsg{err: err}) - close(s.done) - // If headerChan isn't closed, then close it. - if atomic.SwapUint32(&s.headerDone, 1) == 0 { - close(s.headerChan) - } - - } - hdr := &headerFrame{ - hf: headerFields, - endStream: false, - initStream: func(id uint32) (bool, error) { - t.mu.Lock() - if state := t.state; state != reachable { - t.mu.Unlock() - // Do a quick cleanup. - err := error(errStreamDrain) - if state == closing { - err = ErrConnClosing - } - cleanup(err) - return false, err - } - t.activeStreams[id] = s - if channelz.IsOn() { - t.czmu.Lock() - t.streamsStarted++ - t.lastStreamCreated = time.Now() - t.czmu.Unlock() - } - var sendPing bool - // If the number of active streams change from 0 to 1, then check if keepalive - // has gone dormant. If so, wake it up. - if len(t.activeStreams) == 1 { - select { - case t.awakenKeepalive <- struct{}{}: - sendPing = true - // Fill the awakenKeepalive channel again as this channel must be - // kept non-writable except at the point that the keepalive() - // goroutine is waiting either to be awaken or shutdown. - t.awakenKeepalive <- struct{}{} - default: - } - } - t.mu.Unlock() - return sendPing, nil - }, - onOrphaned: cleanup, - wq: s.wq, - } - firstTry := true - var ch chan struct{} - checkForStreamQuota := func(it interface{}) bool { - if t.streamQuota <= 0 { // Can go negative if server decreases it. - if firstTry { - t.waitingStreams++ - } - ch = t.streamsQuotaAvailable - return false - } - if !firstTry { - t.waitingStreams-- - } - t.streamQuota-- - h := it.(*headerFrame) - h.streamID = t.nextID - t.nextID += 2 - s.id = h.streamID - s.fc = &inFlow{limit: uint32(t.initialWindowSize)} - if t.streamQuota > 0 && t.waitingStreams > 0 { - select { - case t.streamsQuotaAvailable <- struct{}{}: - default: - } - } - return true - } - for { - success, err := t.controlBuf.executeAndPut(checkForStreamQuota, hdr) - if err != nil { - return nil, err - } - if success { - break - } - firstTry = false - select { - case <-ch: - case <-s.ctx.Done(): - return nil, ContextErr(s.ctx.Err()) - case <-t.goAway: - return nil, errStreamDrain - case <-t.ctx.Done(): - return nil, ErrConnClosing - } - } - if t.statsHandler != nil { - outHeader := &stats.OutHeader{ - Client: true, - FullMethod: callHdr.Method, - RemoteAddr: t.remoteAddr, - LocalAddr: t.localAddr, - Compression: callHdr.SendCompress, - } - t.statsHandler.HandleRPC(s.ctx, outHeader) - } - return s, nil -} - -// CloseStream clears the footprint of a stream when the stream is not needed any more. -// This must not be executed in reader's goroutine. -func (t *http2Client) CloseStream(s *Stream, err error) { - var ( - rst bool - rstCode http2.ErrCode - ) - if err != nil { - rst = true - rstCode = http2.ErrCodeCancel - } - t.closeStream(s, err, rst, rstCode, nil, nil, false) -} - -func (t *http2Client) closeStream(s *Stream, err error, rst bool, rstCode http2.ErrCode, st *status.Status, mdata map[string][]string, eosReceived bool) { - // Set stream status to done. - if s.swapState(streamDone) == streamDone { - // If it was already done, return. - return - } - // status and trailers can be updated here without any synchronization because the stream goroutine will - // only read it after it sees an io.EOF error from read or write and we'll write those errors - // only after updating this. - s.status = st - if len(mdata) > 0 { - s.trailer = mdata - } - if err != nil { - // This will unblock reads eventually. - s.write(recvMsg{err: err}) - } - // This will unblock write. - close(s.done) - // If headerChan isn't closed, then close it. - if atomic.SwapUint32(&s.headerDone, 1) == 0 { - close(s.headerChan) - } - cleanup := &cleanupStream{ - streamID: s.id, - onWrite: func() { - t.mu.Lock() - if t.activeStreams != nil { - delete(t.activeStreams, s.id) - } - t.mu.Unlock() - if channelz.IsOn() { - t.czmu.Lock() - if eosReceived { - t.streamsSucceeded++ - } else { - t.streamsFailed++ - } - t.czmu.Unlock() - } - }, - rst: rst, - rstCode: rstCode, - } - addBackStreamQuota := func(interface{}) bool { - t.streamQuota++ - if t.streamQuota > 0 && t.waitingStreams > 0 { - select { - case t.streamsQuotaAvailable <- struct{}{}: - default: - } - } - return true - } - t.controlBuf.executeAndPut(addBackStreamQuota, cleanup) -} - -// Close kicks off the shutdown process of the transport. This should be called -// only once on a transport. Once it is called, the transport should not be -// accessed any more. -func (t *http2Client) Close() error { - t.mu.Lock() - // Make sure we only Close once. - if t.state == closing { - t.mu.Unlock() - return nil - } - t.state = closing - streams := t.activeStreams - t.activeStreams = nil - t.mu.Unlock() - t.controlBuf.finish() - t.cancel() - err := t.conn.Close() - if channelz.IsOn() { - channelz.RemoveEntry(t.channelzID) - } - // Notify all active streams. - for _, s := range streams { - t.closeStream(s, ErrConnClosing, false, http2.ErrCodeNo, nil, nil, false) - } - if t.statsHandler != nil { - connEnd := &stats.ConnEnd{ - Client: true, - } - t.statsHandler.HandleConn(t.ctx, connEnd) - } - return err -} - -// GracefulClose sets the state to draining, which prevents new streams from -// being created and causes the transport to be closed when the last active -// stream is closed. If there are no active streams, the transport is closed -// immediately. This does nothing if the transport is already draining or -// closing. -func (t *http2Client) GracefulClose() error { - t.mu.Lock() - // Make sure we move to draining only from active. - if t.state == draining || t.state == closing { - t.mu.Unlock() - return nil - } - t.state = draining - active := len(t.activeStreams) - t.mu.Unlock() - if active == 0 { - return t.Close() - } - return nil -} - -// Write formats the data into HTTP2 data frame(s) and sends it out. The caller -// should proceed only if Write returns nil. -func (t *http2Client) Write(s *Stream, hdr []byte, data []byte, opts *Options) error { - if opts.Last { - // If it's the last message, update stream state. - if !s.compareAndSwapState(streamActive, streamWriteDone) { - return errStreamDone - } - } else if s.getState() != streamActive { - return errStreamDone - } - df := &dataFrame{ - streamID: s.id, - endStream: opts.Last, - } - if hdr != nil || data != nil { // If it's not an empty data frame. - // Add some data to grpc message header so that we can equally - // distribute bytes across frames. - emptyLen := http2MaxFrameLen - len(hdr) - if emptyLen > len(data) { - emptyLen = len(data) - } - hdr = append(hdr, data[:emptyLen]...) - data = data[emptyLen:] - df.h, df.d = hdr, data - // TODO(mmukhi): The above logic in this if can be moved to loopyWriter's data handler. - if err := s.wq.get(int32(len(hdr) + len(data))); err != nil { - return err - } - } - return t.controlBuf.put(df) -} - -func (t *http2Client) getStream(f http2.Frame) (*Stream, bool) { - t.mu.Lock() - defer t.mu.Unlock() - s, ok := t.activeStreams[f.Header().StreamID] - return s, ok -} - -// adjustWindow sends out extra window update over the initial window size -// of stream if the application is requesting data larger in size than -// the window. -func (t *http2Client) adjustWindow(s *Stream, n uint32) { - if w := s.fc.maybeAdjust(n); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w}) - } -} - -// updateWindow adjusts the inbound quota for the stream. -// Window updates will be sent out when the cumulative quota -// exceeds the corresponding threshold. -func (t *http2Client) updateWindow(s *Stream, n uint32) { - if w := s.fc.onRead(n); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w}) - } -} - -// updateFlowControl updates the incoming flow control windows -// for the transport and the stream based on the current bdp -// estimation. -func (t *http2Client) updateFlowControl(n uint32) { - t.mu.Lock() - for _, s := range t.activeStreams { - s.fc.newLimit(n) - } - t.mu.Unlock() - updateIWS := func(interface{}) bool { - t.initialWindowSize = int32(n) - return true - } - t.controlBuf.executeAndPut(updateIWS, &outgoingWindowUpdate{streamID: 0, increment: t.fc.newLimit(n)}) - t.controlBuf.put(&outgoingSettings{ - ss: []http2.Setting{ - { - ID: http2.SettingInitialWindowSize, - Val: n, - }, - }, - }) -} - -func (t *http2Client) handleData(f *http2.DataFrame) { - size := f.Header().Length - var sendBDPPing bool - if t.bdpEst != nil { - sendBDPPing = t.bdpEst.add(size) - } - // Decouple connection's flow control from application's read. - // An update on connection's flow control should not depend on - // whether user application has read the data or not. Such a - // restriction is already imposed on the stream's flow control, - // and therefore the sender will be blocked anyways. - // Decoupling the connection flow control will prevent other - // active(fast) streams from starving in presence of slow or - // inactive streams. - // - if w := t.fc.onData(size); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{ - streamID: 0, - increment: w, - }) - } - if sendBDPPing { - // Avoid excessive ping detection (e.g. in an L7 proxy) - // by sending a window update prior to the BDP ping. - - if w := t.fc.reset(); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{ - streamID: 0, - increment: w, - }) - } - - t.controlBuf.put(bdpPing) - } - // Select the right stream to dispatch. - s, ok := t.getStream(f) - if !ok { - return - } - if size > 0 { - if err := s.fc.onData(size); err != nil { - t.closeStream(s, io.EOF, true, http2.ErrCodeFlowControl, status.New(codes.Internal, err.Error()), nil, false) - return - } - if f.Header().Flags.Has(http2.FlagDataPadded) { - if w := s.fc.onRead(size - uint32(len(f.Data()))); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{s.id, w}) - } - } - // TODO(bradfitz, zhaoq): A copy is required here because there is no - // guarantee f.Data() is consumed before the arrival of next frame. - // Can this copy be eliminated? - if len(f.Data()) > 0 { - data := make([]byte, len(f.Data())) - copy(data, f.Data()) - s.write(recvMsg{data: data}) - } - } - // The server has closed the stream without sending trailers. Record that - // the read direction is closed, and set the status appropriately. - if f.FrameHeader.Flags.Has(http2.FlagDataEndStream) { - t.closeStream(s, io.EOF, false, http2.ErrCodeNo, status.New(codes.Internal, "server closed the stream without sending trailers"), nil, true) - } -} - -func (t *http2Client) handleRSTStream(f *http2.RSTStreamFrame) { - s, ok := t.getStream(f) - if !ok { - return - } - if f.ErrCode == http2.ErrCodeRefusedStream { - // The stream was unprocessed by the server. - atomic.StoreUint32(&s.unprocessed, 1) - } - statusCode, ok := http2ErrConvTab[f.ErrCode] - if !ok { - warningf("transport: http2Client.handleRSTStream found no mapped gRPC status for the received http2 error %v", f.ErrCode) - statusCode = codes.Unknown - } - t.closeStream(s, io.EOF, false, http2.ErrCodeNo, status.Newf(statusCode, "stream terminated by RST_STREAM with error code: %v", f.ErrCode), nil, false) -} - -func (t *http2Client) handleSettings(f *http2.SettingsFrame, isFirst bool) { - if f.IsAck() { - return - } - var maxStreams *uint32 - var ss []http2.Setting - f.ForeachSetting(func(s http2.Setting) error { - if s.ID == http2.SettingMaxConcurrentStreams { - maxStreams = new(uint32) - *maxStreams = s.Val - return nil - } - ss = append(ss, s) - return nil - }) - if isFirst && maxStreams == nil { - maxStreams = new(uint32) - *maxStreams = math.MaxUint32 - } - sf := &incomingSettings{ - ss: ss, - } - if maxStreams == nil { - t.controlBuf.put(sf) - return - } - updateStreamQuota := func(interface{}) bool { - delta := int64(*maxStreams) - int64(t.maxConcurrentStreams) - t.maxConcurrentStreams = *maxStreams - t.streamQuota += delta - if delta > 0 && t.waitingStreams > 0 { - close(t.streamsQuotaAvailable) // wake all of them up. - t.streamsQuotaAvailable = make(chan struct{}, 1) - } - return true - } - t.controlBuf.executeAndPut(updateStreamQuota, sf) -} - -func (t *http2Client) handlePing(f *http2.PingFrame) { - if f.IsAck() { - // Maybe it's a BDP ping. - if t.bdpEst != nil { - t.bdpEst.calculate(f.Data) - } - return - } - pingAck := &ping{ack: true} - copy(pingAck.data[:], f.Data[:]) - t.controlBuf.put(pingAck) -} - -func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) { - t.mu.Lock() - if t.state == closing { - t.mu.Unlock() - return - } - if f.ErrCode == http2.ErrCodeEnhanceYourCalm { - infof("Client received GoAway with http2.ErrCodeEnhanceYourCalm.") - } - id := f.LastStreamID - if id > 0 && id%2 != 1 { - t.mu.Unlock() - t.Close() - return - } - // A client can receive multiple GoAways from the server (see - // https://github.com/grpc/grpc-go/issues/1387). The idea is that the first - // GoAway will be sent with an ID of MaxInt32 and the second GoAway will be - // sent after an RTT delay with the ID of the last stream the server will - // process. - // - // Therefore, when we get the first GoAway we don't necessarily close any - // streams. While in case of second GoAway we close all streams created after - // the GoAwayId. This way streams that were in-flight while the GoAway from - // server was being sent don't get killed. - select { - case <-t.goAway: // t.goAway has been closed (i.e.,multiple GoAways). - // If there are multiple GoAways the first one should always have an ID greater than the following ones. - if id > t.prevGoAwayID { - t.mu.Unlock() - t.Close() - return - } - default: - t.setGoAwayReason(f) - close(t.goAway) - t.state = draining - t.controlBuf.put(&incomingGoAway{}) - } - // All streams with IDs greater than the GoAwayId - // and smaller than the previous GoAway ID should be killed. - upperLimit := t.prevGoAwayID - if upperLimit == 0 { // This is the first GoAway Frame. - upperLimit = math.MaxUint32 // Kill all streams after the GoAway ID. - } - for streamID, stream := range t.activeStreams { - if streamID > id && streamID <= upperLimit { - // The stream was unprocessed by the server. - atomic.StoreUint32(&stream.unprocessed, 1) - t.closeStream(stream, errStreamDrain, false, http2.ErrCodeNo, statusGoAway, nil, false) - } - } - t.prevGoAwayID = id - active := len(t.activeStreams) - t.mu.Unlock() - if active == 0 { - t.Close() - } -} - -// setGoAwayReason sets the value of t.goAwayReason based -// on the GoAway frame received. -// It expects a lock on transport's mutext to be held by -// the caller. -func (t *http2Client) setGoAwayReason(f *http2.GoAwayFrame) { - t.goAwayReason = GoAwayNoReason - switch f.ErrCode { - case http2.ErrCodeEnhanceYourCalm: - if string(f.DebugData()) == "too_many_pings" { - t.goAwayReason = GoAwayTooManyPings - } - } -} - -func (t *http2Client) GetGoAwayReason() GoAwayReason { - t.mu.Lock() - defer t.mu.Unlock() - return t.goAwayReason -} - -func (t *http2Client) handleWindowUpdate(f *http2.WindowUpdateFrame) { - t.controlBuf.put(&incomingWindowUpdate{ - streamID: f.Header().StreamID, - increment: f.Increment, - }) -} - -// operateHeaders takes action on the decoded headers. -func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) { - s, ok := t.getStream(frame) - if !ok { - return - } - atomic.StoreUint32(&s.bytesReceived, 1) - var state decodeState - if err := state.decodeResponseHeader(frame); err != nil { - t.closeStream(s, err, true, http2.ErrCodeProtocol, nil, nil, false) - // Something wrong. Stops reading even when there is remaining. - return - } - - endStream := frame.StreamEnded() - var isHeader bool - defer func() { - if t.statsHandler != nil { - if isHeader { - inHeader := &stats.InHeader{ - Client: true, - WireLength: int(frame.Header().Length), - } - t.statsHandler.HandleRPC(s.ctx, inHeader) - } else { - inTrailer := &stats.InTrailer{ - Client: true, - WireLength: int(frame.Header().Length), - } - t.statsHandler.HandleRPC(s.ctx, inTrailer) - } - } - }() - // If headers haven't been received yet. - if atomic.SwapUint32(&s.headerDone, 1) == 0 { - if !endStream { - // Headers frame is not actually a trailers-only frame. - isHeader = true - // These values can be set without any synchronization because - // stream goroutine will read it only after seeing a closed - // headerChan which we'll close after setting this. - s.recvCompress = state.encoding - if len(state.mdata) > 0 { - s.header = state.mdata - } - } - close(s.headerChan) - } - if !endStream { - return - } - t.closeStream(s, io.EOF, false, http2.ErrCodeNo, state.status(), state.mdata, true) -} - -// reader runs as a separate goroutine in charge of reading data from network -// connection. -// -// TODO(zhaoq): currently one reader per transport. Investigate whether this is -// optimal. -// TODO(zhaoq): Check the validity of the incoming frame sequence. -func (t *http2Client) reader() { - defer close(t.readerDone) - // Check the validity of server preface. - frame, err := t.framer.fr.ReadFrame() - if err != nil { - t.Close() - return - } - atomic.CompareAndSwapUint32(&t.activity, 0, 1) - sf, ok := frame.(*http2.SettingsFrame) - if !ok { - t.Close() - return - } - t.onSuccess() - t.handleSettings(sf, true) - - // loop to keep reading incoming messages on this transport. - for { - frame, err := t.framer.fr.ReadFrame() - atomic.CompareAndSwapUint32(&t.activity, 0, 1) - if err != nil { - // Abort an active stream if the http2.Framer returns a - // http2.StreamError. This can happen only if the server's response - // is malformed http2. - if se, ok := err.(http2.StreamError); ok { - t.mu.Lock() - s := t.activeStreams[se.StreamID] - t.mu.Unlock() - if s != nil { - // use error detail to provide better err message - t.closeStream(s, streamErrorf(http2ErrConvTab[se.Code], "%v", t.framer.fr.ErrorDetail()), true, http2.ErrCodeProtocol, nil, nil, false) - } - continue - } else { - // Transport error. - t.Close() - return - } - } - switch frame := frame.(type) { - case *http2.MetaHeadersFrame: - t.operateHeaders(frame) - case *http2.DataFrame: - t.handleData(frame) - case *http2.RSTStreamFrame: - t.handleRSTStream(frame) - case *http2.SettingsFrame: - t.handleSettings(frame, false) - case *http2.PingFrame: - t.handlePing(frame) - case *http2.GoAwayFrame: - t.handleGoAway(frame) - case *http2.WindowUpdateFrame: - t.handleWindowUpdate(frame) - default: - errorf("transport: http2Client.reader got unhandled frame type %v.", frame) - } - } -} - -// keepalive running in a separate goroutune makes sure the connection is alive by sending pings. -func (t *http2Client) keepalive() { - p := &ping{data: [8]byte{}} - timer := time.NewTimer(t.kp.Time) - for { - select { - case <-timer.C: - if atomic.CompareAndSwapUint32(&t.activity, 1, 0) { - timer.Reset(t.kp.Time) - continue - } - // Check if keepalive should go dormant. - t.mu.Lock() - if len(t.activeStreams) < 1 && !t.kp.PermitWithoutStream { - // Make awakenKeepalive writable. - <-t.awakenKeepalive - t.mu.Unlock() - select { - case <-t.awakenKeepalive: - // If the control gets here a ping has been sent - // need to reset the timer with keepalive.Timeout. - case <-t.ctx.Done(): - return - } - } else { - t.mu.Unlock() - if channelz.IsOn() { - t.czmu.Lock() - t.kpCount++ - t.czmu.Unlock() - } - // Send ping. - t.controlBuf.put(p) - } - - // By the time control gets here a ping has been sent one way or the other. - timer.Reset(t.kp.Timeout) - select { - case <-timer.C: - if atomic.CompareAndSwapUint32(&t.activity, 1, 0) { - timer.Reset(t.kp.Time) - continue - } - t.Close() - return - case <-t.ctx.Done(): - if !timer.Stop() { - <-timer.C - } - return - } - case <-t.ctx.Done(): - if !timer.Stop() { - <-timer.C - } - return - } - } -} - -func (t *http2Client) Error() <-chan struct{} { - return t.ctx.Done() -} - -func (t *http2Client) GoAway() <-chan struct{} { - return t.goAway -} - -func (t *http2Client) ChannelzMetric() *channelz.SocketInternalMetric { - t.czmu.RLock() - s := channelz.SocketInternalMetric{ - StreamsStarted: t.streamsStarted, - StreamsSucceeded: t.streamsSucceeded, - StreamsFailed: t.streamsFailed, - MessagesSent: t.msgSent, - MessagesReceived: t.msgRecv, - KeepAlivesSent: t.kpCount, - LastLocalStreamCreatedTimestamp: t.lastStreamCreated, - LastMessageSentTimestamp: t.lastMsgSent, - LastMessageReceivedTimestamp: t.lastMsgRecv, - LocalFlowControlWindow: int64(t.fc.getSize()), - //socket options - LocalAddr: t.localAddr, - RemoteAddr: t.remoteAddr, - // Security - // RemoteName : - } - t.czmu.RUnlock() - s.RemoteFlowControlWindow = t.getOutFlowWindow() - return &s -} - -func (t *http2Client) IncrMsgSent() { - t.czmu.Lock() - t.msgSent++ - t.lastMsgSent = time.Now() - t.czmu.Unlock() -} - -func (t *http2Client) IncrMsgRecv() { - t.czmu.Lock() - t.msgRecv++ - t.lastMsgRecv = time.Now() - t.czmu.Unlock() -} - -func (t *http2Client) getOutFlowWindow() int64 { - resp := make(chan uint32, 1) - timer := time.NewTimer(time.Second) - defer timer.Stop() - t.controlBuf.put(&outFlowControlSizeRequest{resp}) - select { - case sz := <-resp: - return int64(sz) - case <-t.ctxDone: - return -1 - case <-timer.C: - return -2 - } -} diff --git a/vendor/google.golang.org/grpc/transport/http2_server.go b/vendor/google.golang.org/grpc/transport/http2_server.go deleted file mode 100644 index 8b93e222e9e..00000000000 --- a/vendor/google.golang.org/grpc/transport/http2_server.go +++ /dev/null @@ -1,1136 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 transport - -import ( - "bytes" - "errors" - "fmt" - "io" - "math" - "math/rand" - "net" - "strconv" - "sync" - "sync/atomic" - "time" - - "github.com/golang/protobuf/proto" - "golang.org/x/net/context" - "golang.org/x/net/http2" - "golang.org/x/net/http2/hpack" - - "google.golang.org/grpc/channelz" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/keepalive" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/peer" - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" - "google.golang.org/grpc/tap" -) - -// ErrIllegalHeaderWrite indicates that setting header is illegal because of -// the stream's state. -var ErrIllegalHeaderWrite = errors.New("transport: the stream is done or WriteHeader was already called") - -// http2Server implements the ServerTransport interface with HTTP2. -type http2Server struct { - ctx context.Context - ctxDone <-chan struct{} // Cache the context.Done() chan - cancel context.CancelFunc - conn net.Conn - loopy *loopyWriter - readerDone chan struct{} // sync point to enable testing. - writerDone chan struct{} // sync point to enable testing. - remoteAddr net.Addr - localAddr net.Addr - maxStreamID uint32 // max stream ID ever seen - authInfo credentials.AuthInfo // auth info about the connection - inTapHandle tap.ServerInHandle - framer *framer - // The max number of concurrent streams. - maxStreams uint32 - // controlBuf delivers all the control related tasks (e.g., window - // updates, reset streams, and various settings) to the controller. - controlBuf *controlBuffer - fc *trInFlow - stats stats.Handler - // Flag to keep track of reading activity on transport. - // 1 is true and 0 is false. - activity uint32 // Accessed atomically. - // Keepalive and max-age parameters for the server. - kp keepalive.ServerParameters - - // Keepalive enforcement policy. - kep keepalive.EnforcementPolicy - // The time instance last ping was received. - lastPingAt time.Time - // Number of times the client has violated keepalive ping policy so far. - pingStrikes uint8 - // Flag to signify that number of ping strikes should be reset to 0. - // This is set whenever data or header frames are sent. - // 1 means yes. - resetPingStrikes uint32 // Accessed atomically. - initialWindowSize int32 - bdpEst *bdpEstimator - - mu sync.Mutex // guard the following - - // drainChan is initialized when drain(...) is called the first time. - // After which the server writes out the first GoAway(with ID 2^31-1) frame. - // Then an independent goroutine will be launched to later send the second GoAway. - // During this time we don't want to write another first GoAway(with ID 2^31 -1) frame. - // Thus call to drain(...) will be a no-op if drainChan is already initialized since draining is - // already underway. - drainChan chan struct{} - state transportState - activeStreams map[uint32]*Stream - // idle is the time instant when the connection went idle. - // This is either the beginning of the connection or when the number of - // RPCs go down to 0. - // When the connection is busy, this value is set to 0. - idle time.Time - - // Fields below are for channelz metric collection. - channelzID int64 // channelz unique identification number - czmu sync.RWMutex - kpCount int64 - // The number of streams that have started, including already finished ones. - streamsStarted int64 - // The number of streams that have ended successfully by sending frame with - // EoS bit set. - streamsSucceeded int64 - streamsFailed int64 - lastStreamCreated time.Time - msgSent int64 - msgRecv int64 - lastMsgSent time.Time - lastMsgRecv time.Time -} - -// newHTTP2Server constructs a ServerTransport based on HTTP2. ConnectionError is -// returned if something goes wrong. -func newHTTP2Server(conn net.Conn, config *ServerConfig) (_ ServerTransport, err error) { - writeBufSize := defaultWriteBufSize - if config.WriteBufferSize > 0 { - writeBufSize = config.WriteBufferSize - } - readBufSize := defaultReadBufSize - if config.ReadBufferSize > 0 { - readBufSize = config.ReadBufferSize - } - framer := newFramer(conn, writeBufSize, readBufSize) - // Send initial settings as connection preface to client. - var isettings []http2.Setting - // TODO(zhaoq): Have a better way to signal "no limit" because 0 is - // permitted in the HTTP2 spec. - maxStreams := config.MaxStreams - if maxStreams == 0 { - maxStreams = math.MaxUint32 - } else { - isettings = append(isettings, http2.Setting{ - ID: http2.SettingMaxConcurrentStreams, - Val: maxStreams, - }) - } - dynamicWindow := true - iwz := int32(initialWindowSize) - if config.InitialWindowSize >= defaultWindowSize { - iwz = config.InitialWindowSize - dynamicWindow = false - } - icwz := int32(initialWindowSize) - if config.InitialConnWindowSize >= defaultWindowSize { - icwz = config.InitialConnWindowSize - dynamicWindow = false - } - if iwz != defaultWindowSize { - isettings = append(isettings, http2.Setting{ - ID: http2.SettingInitialWindowSize, - Val: uint32(iwz)}) - } - if err := framer.fr.WriteSettings(isettings...); err != nil { - return nil, connectionErrorf(false, err, "transport: %v", err) - } - // Adjust the connection flow control window if needed. - if delta := uint32(icwz - defaultWindowSize); delta > 0 { - if err := framer.fr.WriteWindowUpdate(0, delta); err != nil { - return nil, connectionErrorf(false, err, "transport: %v", err) - } - } - kp := config.KeepaliveParams - if kp.MaxConnectionIdle == 0 { - kp.MaxConnectionIdle = defaultMaxConnectionIdle - } - if kp.MaxConnectionAge == 0 { - kp.MaxConnectionAge = defaultMaxConnectionAge - } - // Add a jitter to MaxConnectionAge. - kp.MaxConnectionAge += getJitter(kp.MaxConnectionAge) - if kp.MaxConnectionAgeGrace == 0 { - kp.MaxConnectionAgeGrace = defaultMaxConnectionAgeGrace - } - if kp.Time == 0 { - kp.Time = defaultServerKeepaliveTime - } - if kp.Timeout == 0 { - kp.Timeout = defaultServerKeepaliveTimeout - } - kep := config.KeepalivePolicy - if kep.MinTime == 0 { - kep.MinTime = defaultKeepalivePolicyMinTime - } - ctx, cancel := context.WithCancel(context.Background()) - t := &http2Server{ - ctx: ctx, - cancel: cancel, - ctxDone: ctx.Done(), - conn: conn, - remoteAddr: conn.RemoteAddr(), - localAddr: conn.LocalAddr(), - authInfo: config.AuthInfo, - framer: framer, - readerDone: make(chan struct{}), - writerDone: make(chan struct{}), - maxStreams: maxStreams, - inTapHandle: config.InTapHandle, - fc: &trInFlow{limit: uint32(icwz)}, - state: reachable, - activeStreams: make(map[uint32]*Stream), - stats: config.StatsHandler, - kp: kp, - idle: time.Now(), - kep: kep, - initialWindowSize: iwz, - } - t.controlBuf = newControlBuffer(t.ctxDone) - if dynamicWindow { - t.bdpEst = &bdpEstimator{ - bdp: initialWindowSize, - updateFlowControl: t.updateFlowControl, - } - } - if t.stats != nil { - t.ctx = t.stats.TagConn(t.ctx, &stats.ConnTagInfo{ - RemoteAddr: t.remoteAddr, - LocalAddr: t.localAddr, - }) - connBegin := &stats.ConnBegin{} - t.stats.HandleConn(t.ctx, connBegin) - } - if channelz.IsOn() { - t.channelzID = channelz.RegisterNormalSocket(t, config.ChannelzParentID, "") - } - t.framer.writer.Flush() - - defer func() { - if err != nil { - t.Close() - } - }() - - // Check the validity of client preface. - preface := make([]byte, len(clientPreface)) - if _, err := io.ReadFull(t.conn, preface); err != nil { - return nil, connectionErrorf(false, err, "transport: http2Server.HandleStreams failed to receive the preface from client: %v", err) - } - if !bytes.Equal(preface, clientPreface) { - return nil, connectionErrorf(false, nil, "transport: http2Server.HandleStreams received bogus greeting from client: %q", preface) - } - - frame, err := t.framer.fr.ReadFrame() - if err == io.EOF || err == io.ErrUnexpectedEOF { - return nil, err - } - if err != nil { - return nil, connectionErrorf(false, err, "transport: http2Server.HandleStreams failed to read initial settings frame: %v", err) - } - atomic.StoreUint32(&t.activity, 1) - sf, ok := frame.(*http2.SettingsFrame) - if !ok { - return nil, connectionErrorf(false, nil, "transport: http2Server.HandleStreams saw invalid preface type %T from client", frame) - } - t.handleSettings(sf) - - go func() { - t.loopy = newLoopyWriter(serverSide, t.framer, t.controlBuf, t.bdpEst) - t.loopy.ssGoAwayHandler = t.outgoingGoAwayHandler - t.loopy.run() - t.conn.Close() - close(t.writerDone) - }() - go t.keepalive() - return t, nil -} - -// operateHeader takes action on the decoded headers. -func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func(*Stream), traceCtx func(context.Context, string) context.Context) (close bool) { - streamID := frame.Header().StreamID - var state decodeState - for _, hf := range frame.Fields { - if err := state.processHeaderField(hf); err != nil { - if se, ok := err.(StreamError); ok { - t.controlBuf.put(&cleanupStream{ - streamID: streamID, - rst: true, - rstCode: statusCodeConvTab[se.Code], - onWrite: func() {}, - }) - } - return - } - } - - buf := newRecvBuffer() - s := &Stream{ - id: streamID, - st: t, - buf: buf, - fc: &inFlow{limit: uint32(t.initialWindowSize)}, - recvCompress: state.encoding, - method: state.method, - contentSubtype: state.contentSubtype, - } - if frame.StreamEnded() { - // s is just created by the caller. No lock needed. - s.state = streamReadDone - } - if state.timeoutSet { - s.ctx, s.cancel = context.WithTimeout(t.ctx, state.timeout) - } else { - s.ctx, s.cancel = context.WithCancel(t.ctx) - } - pr := &peer.Peer{ - Addr: t.remoteAddr, - } - // Attach Auth info if there is any. - if t.authInfo != nil { - pr.AuthInfo = t.authInfo - } - s.ctx = peer.NewContext(s.ctx, pr) - // Attach the received metadata to the context. - if len(state.mdata) > 0 { - s.ctx = metadata.NewIncomingContext(s.ctx, state.mdata) - } - if state.statsTags != nil { - s.ctx = stats.SetIncomingTags(s.ctx, state.statsTags) - } - if state.statsTrace != nil { - s.ctx = stats.SetIncomingTrace(s.ctx, state.statsTrace) - } - if t.inTapHandle != nil { - var err error - info := &tap.Info{ - FullMethodName: state.method, - } - s.ctx, err = t.inTapHandle(s.ctx, info) - if err != nil { - warningf("transport: http2Server.operateHeaders got an error from InTapHandle: %v", err) - t.controlBuf.put(&cleanupStream{ - streamID: s.id, - rst: true, - rstCode: http2.ErrCodeRefusedStream, - onWrite: func() {}, - }) - return - } - } - t.mu.Lock() - if t.state != reachable { - t.mu.Unlock() - return - } - if uint32(len(t.activeStreams)) >= t.maxStreams { - t.mu.Unlock() - t.controlBuf.put(&cleanupStream{ - streamID: streamID, - rst: true, - rstCode: http2.ErrCodeRefusedStream, - onWrite: func() {}, - }) - return - } - if streamID%2 != 1 || streamID <= t.maxStreamID { - t.mu.Unlock() - // illegal gRPC stream id. - errorf("transport: http2Server.HandleStreams received an illegal stream id: %v", streamID) - return true - } - t.maxStreamID = streamID - t.activeStreams[streamID] = s - if len(t.activeStreams) == 1 { - t.idle = time.Time{} - } - t.mu.Unlock() - if channelz.IsOn() { - t.czmu.Lock() - t.streamsStarted++ - t.lastStreamCreated = time.Now() - t.czmu.Unlock() - } - s.requestRead = func(n int) { - t.adjustWindow(s, uint32(n)) - } - s.ctx = traceCtx(s.ctx, s.method) - if t.stats != nil { - s.ctx = t.stats.TagRPC(s.ctx, &stats.RPCTagInfo{FullMethodName: s.method}) - inHeader := &stats.InHeader{ - FullMethod: s.method, - RemoteAddr: t.remoteAddr, - LocalAddr: t.localAddr, - Compression: s.recvCompress, - WireLength: int(frame.Header().Length), - } - t.stats.HandleRPC(s.ctx, inHeader) - } - s.ctxDone = s.ctx.Done() - s.wq = newWriteQuota(defaultWriteQuota, s.ctxDone) - s.trReader = &transportReader{ - reader: &recvBufferReader{ - ctx: s.ctx, - ctxDone: s.ctxDone, - recv: s.buf, - }, - windowHandler: func(n int) { - t.updateWindow(s, uint32(n)) - }, - } - handle(s) - return -} - -// HandleStreams receives incoming streams using the given handler. This is -// typically run in a separate goroutine. -// traceCtx attaches trace to ctx and returns the new context. -func (t *http2Server) HandleStreams(handle func(*Stream), traceCtx func(context.Context, string) context.Context) { - defer close(t.readerDone) - for { - frame, err := t.framer.fr.ReadFrame() - atomic.StoreUint32(&t.activity, 1) - if err != nil { - if se, ok := err.(http2.StreamError); ok { - warningf("transport: http2Server.HandleStreams encountered http2.StreamError: %v", se) - t.mu.Lock() - s := t.activeStreams[se.StreamID] - t.mu.Unlock() - if s != nil { - t.closeStream(s, true, se.Code, nil, false) - } else { - t.controlBuf.put(&cleanupStream{ - streamID: se.StreamID, - rst: true, - rstCode: se.Code, - onWrite: func() {}, - }) - } - continue - } - if err == io.EOF || err == io.ErrUnexpectedEOF { - t.Close() - return - } - warningf("transport: http2Server.HandleStreams failed to read frame: %v", err) - t.Close() - return - } - switch frame := frame.(type) { - case *http2.MetaHeadersFrame: - if t.operateHeaders(frame, handle, traceCtx) { - t.Close() - break - } - case *http2.DataFrame: - t.handleData(frame) - case *http2.RSTStreamFrame: - t.handleRSTStream(frame) - case *http2.SettingsFrame: - t.handleSettings(frame) - case *http2.PingFrame: - t.handlePing(frame) - case *http2.WindowUpdateFrame: - t.handleWindowUpdate(frame) - case *http2.GoAwayFrame: - // TODO: Handle GoAway from the client appropriately. - default: - errorf("transport: http2Server.HandleStreams found unhandled frame type %v.", frame) - } - } -} - -func (t *http2Server) getStream(f http2.Frame) (*Stream, bool) { - t.mu.Lock() - defer t.mu.Unlock() - if t.activeStreams == nil { - // The transport is closing. - return nil, false - } - s, ok := t.activeStreams[f.Header().StreamID] - if !ok { - // The stream is already done. - return nil, false - } - return s, true -} - -// adjustWindow sends out extra window update over the initial window size -// of stream if the application is requesting data larger in size than -// the window. -func (t *http2Server) adjustWindow(s *Stream, n uint32) { - if w := s.fc.maybeAdjust(n); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w}) - } - -} - -// updateWindow adjusts the inbound quota for the stream and the transport. -// Window updates will deliver to the controller for sending when -// the cumulative quota exceeds the corresponding threshold. -func (t *http2Server) updateWindow(s *Stream, n uint32) { - if w := s.fc.onRead(n); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, - increment: w, - }) - } -} - -// updateFlowControl updates the incoming flow control windows -// for the transport and the stream based on the current bdp -// estimation. -func (t *http2Server) updateFlowControl(n uint32) { - t.mu.Lock() - for _, s := range t.activeStreams { - s.fc.newLimit(n) - } - t.initialWindowSize = int32(n) - t.mu.Unlock() - t.controlBuf.put(&outgoingWindowUpdate{ - streamID: 0, - increment: t.fc.newLimit(n), - }) - t.controlBuf.put(&outgoingSettings{ - ss: []http2.Setting{ - { - ID: http2.SettingInitialWindowSize, - Val: n, - }, - }, - }) - -} - -func (t *http2Server) handleData(f *http2.DataFrame) { - size := f.Header().Length - var sendBDPPing bool - if t.bdpEst != nil { - sendBDPPing = t.bdpEst.add(size) - } - // Decouple connection's flow control from application's read. - // An update on connection's flow control should not depend on - // whether user application has read the data or not. Such a - // restriction is already imposed on the stream's flow control, - // and therefore the sender will be blocked anyways. - // Decoupling the connection flow control will prevent other - // active(fast) streams from starving in presence of slow or - // inactive streams. - if w := t.fc.onData(size); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{ - streamID: 0, - increment: w, - }) - } - if sendBDPPing { - // Avoid excessive ping detection (e.g. in an L7 proxy) - // by sending a window update prior to the BDP ping. - if w := t.fc.reset(); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{ - streamID: 0, - increment: w, - }) - } - t.controlBuf.put(bdpPing) - } - // Select the right stream to dispatch. - s, ok := t.getStream(f) - if !ok { - return - } - if size > 0 { - if err := s.fc.onData(size); err != nil { - t.closeStream(s, true, http2.ErrCodeFlowControl, nil, false) - return - } - if f.Header().Flags.Has(http2.FlagDataPadded) { - if w := s.fc.onRead(size - uint32(len(f.Data()))); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{s.id, w}) - } - } - // TODO(bradfitz, zhaoq): A copy is required here because there is no - // guarantee f.Data() is consumed before the arrival of next frame. - // Can this copy be eliminated? - if len(f.Data()) > 0 { - data := make([]byte, len(f.Data())) - copy(data, f.Data()) - s.write(recvMsg{data: data}) - } - } - if f.Header().Flags.Has(http2.FlagDataEndStream) { - // Received the end of stream from the client. - s.compareAndSwapState(streamActive, streamReadDone) - s.write(recvMsg{err: io.EOF}) - } -} - -func (t *http2Server) handleRSTStream(f *http2.RSTStreamFrame) { - s, ok := t.getStream(f) - if !ok { - return - } - t.closeStream(s, false, 0, nil, false) -} - -func (t *http2Server) handleSettings(f *http2.SettingsFrame) { - if f.IsAck() { - return - } - var ss []http2.Setting - f.ForeachSetting(func(s http2.Setting) error { - ss = append(ss, s) - return nil - }) - t.controlBuf.put(&incomingSettings{ - ss: ss, - }) -} - -const ( - maxPingStrikes = 2 - defaultPingTimeout = 2 * time.Hour -) - -func (t *http2Server) handlePing(f *http2.PingFrame) { - if f.IsAck() { - if f.Data == goAwayPing.data && t.drainChan != nil { - close(t.drainChan) - return - } - // Maybe it's a BDP ping. - if t.bdpEst != nil { - t.bdpEst.calculate(f.Data) - } - return - } - pingAck := &ping{ack: true} - copy(pingAck.data[:], f.Data[:]) - t.controlBuf.put(pingAck) - - now := time.Now() - defer func() { - t.lastPingAt = now - }() - // A reset ping strikes means that we don't need to check for policy - // violation for this ping and the pingStrikes counter should be set - // to 0. - if atomic.CompareAndSwapUint32(&t.resetPingStrikes, 1, 0) { - t.pingStrikes = 0 - return - } - t.mu.Lock() - ns := len(t.activeStreams) - t.mu.Unlock() - if ns < 1 && !t.kep.PermitWithoutStream { - // Keepalive shouldn't be active thus, this new ping should - // have come after at least defaultPingTimeout. - if t.lastPingAt.Add(defaultPingTimeout).After(now) { - t.pingStrikes++ - } - } else { - // Check if keepalive policy is respected. - if t.lastPingAt.Add(t.kep.MinTime).After(now) { - t.pingStrikes++ - } - } - - if t.pingStrikes > maxPingStrikes { - // Send goaway and close the connection. - errorf("transport: Got too many pings from the client, closing the connection.") - t.controlBuf.put(&goAway{code: http2.ErrCodeEnhanceYourCalm, debugData: []byte("too_many_pings"), closeConn: true}) - } -} - -func (t *http2Server) handleWindowUpdate(f *http2.WindowUpdateFrame) { - t.controlBuf.put(&incomingWindowUpdate{ - streamID: f.Header().StreamID, - increment: f.Increment, - }) -} - -// WriteHeader sends the header metedata md back to the client. -func (t *http2Server) WriteHeader(s *Stream, md metadata.MD) error { - if s.headerOk || s.getState() == streamDone { - return ErrIllegalHeaderWrite - } - s.headerOk = true - if md.Len() > 0 { - if s.header.Len() > 0 { - s.header = metadata.Join(s.header, md) - } else { - s.header = md - } - } - md = s.header - // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields - // first and create a slice of that exact size. - headerFields := make([]hpack.HeaderField, 0, 2) // at least :status, content-type will be there if none else. - headerFields = append(headerFields, hpack.HeaderField{Name: ":status", Value: "200"}) - headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: contentType(s.contentSubtype)}) - if s.sendCompress != "" { - headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-encoding", Value: s.sendCompress}) - } - for k, vv := range md { - if isReservedHeader(k) { - // Clients don't tolerate reading restricted headers after some non restricted ones were sent. - continue - } - for _, v := range vv { - headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) - } - } - t.controlBuf.put(&headerFrame{ - streamID: s.id, - hf: headerFields, - endStream: false, - onWrite: func() { - atomic.StoreUint32(&t.resetPingStrikes, 1) - }, - wq: s.wq, - }) - if t.stats != nil { - // Note: WireLength is not set in outHeader. - // TODO(mmukhi): Revisit this later, if needed. - outHeader := &stats.OutHeader{} - t.stats.HandleRPC(s.Context(), outHeader) - } - return nil -} - -// WriteStatus sends stream status to the client and terminates the stream. -// There is no further I/O operations being able to perform on this stream. -// TODO(zhaoq): Now it indicates the end of entire stream. Revisit if early -// OK is adopted. -func (t *http2Server) WriteStatus(s *Stream, st *status.Status) error { - if !s.headerOk && s.header.Len() > 0 { - if err := t.WriteHeader(s, nil); err != nil { - return err - } - } else { - if s.getState() == streamDone { - return nil - } - } - // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields - // first and create a slice of that exact size. - headerFields := make([]hpack.HeaderField, 0, 2) // grpc-status and grpc-message will be there if none else. - if !s.headerOk { - headerFields = append(headerFields, hpack.HeaderField{Name: ":status", Value: "200"}) - headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: contentType(s.contentSubtype)}) - } - headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-status", Value: strconv.Itoa(int(st.Code()))}) - headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-message", Value: encodeGrpcMessage(st.Message())}) - - if p := st.Proto(); p != nil && len(p.Details) > 0 { - stBytes, err := proto.Marshal(p) - if err != nil { - // TODO: return error instead, when callers are able to handle it. - panic(err) - } - - headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-status-details-bin", Value: encodeBinHeader(stBytes)}) - } - - // Attach the trailer metadata. - for k, vv := range s.trailer { - // Clients don't tolerate reading restricted headers after some non restricted ones were sent. - if isReservedHeader(k) { - continue - } - for _, v := range vv { - headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) - } - } - trailer := &headerFrame{ - streamID: s.id, - hf: headerFields, - endStream: true, - onWrite: func() { - atomic.StoreUint32(&t.resetPingStrikes, 1) - }, - } - t.closeStream(s, false, 0, trailer, true) - if t.stats != nil { - t.stats.HandleRPC(s.Context(), &stats.OutTrailer{}) - } - return nil -} - -// Write converts the data into HTTP2 data frame and sends it out. Non-nil error -// is returns if it fails (e.g., framing error, transport error). -func (t *http2Server) Write(s *Stream, hdr []byte, data []byte, opts *Options) error { - if !s.headerOk { // Headers haven't been written yet. - if err := t.WriteHeader(s, nil); err != nil { - // TODO(mmukhi, dfawley): Make sure this is the right code to return. - return streamErrorf(codes.Internal, "transport: %v", err) - } - } else { - // Writing headers checks for this condition. - if s.getState() == streamDone { - // TODO(mmukhi, dfawley): Should the server write also return io.EOF? - s.cancel() - select { - case <-t.ctx.Done(): - return ErrConnClosing - default: - } - return ContextErr(s.ctx.Err()) - } - } - // Add some data to header frame so that we can equally distribute bytes across frames. - emptyLen := http2MaxFrameLen - len(hdr) - if emptyLen > len(data) { - emptyLen = len(data) - } - hdr = append(hdr, data[:emptyLen]...) - data = data[emptyLen:] - df := &dataFrame{ - streamID: s.id, - h: hdr, - d: data, - onEachWrite: func() { - atomic.StoreUint32(&t.resetPingStrikes, 1) - }, - } - if err := s.wq.get(int32(len(hdr) + len(data))); err != nil { - select { - case <-t.ctx.Done(): - return ErrConnClosing - default: - } - return ContextErr(s.ctx.Err()) - } - return t.controlBuf.put(df) -} - -// keepalive running in a separate goroutine does the following: -// 1. Gracefully closes an idle connection after a duration of keepalive.MaxConnectionIdle. -// 2. Gracefully closes any connection after a duration of keepalive.MaxConnectionAge. -// 3. Forcibly closes a connection after an additive period of keepalive.MaxConnectionAgeGrace over keepalive.MaxConnectionAge. -// 4. Makes sure a connection is alive by sending pings with a frequency of keepalive.Time and closes a non-responsive connection -// after an additional duration of keepalive.Timeout. -func (t *http2Server) keepalive() { - p := &ping{} - var pingSent bool - maxIdle := time.NewTimer(t.kp.MaxConnectionIdle) - maxAge := time.NewTimer(t.kp.MaxConnectionAge) - keepalive := time.NewTimer(t.kp.Time) - // NOTE: All exit paths of this function should reset their - // respective timers. A failure to do so will cause the - // following clean-up to deadlock and eventually leak. - defer func() { - if !maxIdle.Stop() { - <-maxIdle.C - } - if !maxAge.Stop() { - <-maxAge.C - } - if !keepalive.Stop() { - <-keepalive.C - } - }() - for { - select { - case <-maxIdle.C: - t.mu.Lock() - idle := t.idle - if idle.IsZero() { // The connection is non-idle. - t.mu.Unlock() - maxIdle.Reset(t.kp.MaxConnectionIdle) - continue - } - val := t.kp.MaxConnectionIdle - time.Since(idle) - t.mu.Unlock() - if val <= 0 { - // The connection has been idle for a duration of keepalive.MaxConnectionIdle or more. - // Gracefully close the connection. - t.drain(http2.ErrCodeNo, []byte{}) - // Resetting the timer so that the clean-up doesn't deadlock. - maxIdle.Reset(infinity) - return - } - maxIdle.Reset(val) - case <-maxAge.C: - t.drain(http2.ErrCodeNo, []byte{}) - maxAge.Reset(t.kp.MaxConnectionAgeGrace) - select { - case <-maxAge.C: - // Close the connection after grace period. - t.Close() - // Resetting the timer so that the clean-up doesn't deadlock. - maxAge.Reset(infinity) - case <-t.ctx.Done(): - } - return - case <-keepalive.C: - if atomic.CompareAndSwapUint32(&t.activity, 1, 0) { - pingSent = false - keepalive.Reset(t.kp.Time) - continue - } - if pingSent { - t.Close() - // Resetting the timer so that the clean-up doesn't deadlock. - keepalive.Reset(infinity) - return - } - pingSent = true - if channelz.IsOn() { - t.czmu.Lock() - t.kpCount++ - t.czmu.Unlock() - } - t.controlBuf.put(p) - keepalive.Reset(t.kp.Timeout) - case <-t.ctx.Done(): - return - } - } -} - -// Close starts shutting down the http2Server transport. -// TODO(zhaoq): Now the destruction is not blocked on any pending streams. This -// could cause some resource issue. Revisit this later. -func (t *http2Server) Close() error { - t.mu.Lock() - if t.state == closing { - t.mu.Unlock() - return errors.New("transport: Close() was already called") - } - t.state = closing - streams := t.activeStreams - t.activeStreams = nil - t.mu.Unlock() - t.controlBuf.finish() - t.cancel() - err := t.conn.Close() - if channelz.IsOn() { - channelz.RemoveEntry(t.channelzID) - } - // Cancel all active streams. - for _, s := range streams { - s.cancel() - } - if t.stats != nil { - connEnd := &stats.ConnEnd{} - t.stats.HandleConn(t.ctx, connEnd) - } - return err -} - -// closeStream clears the footprint of a stream when the stream is not needed -// any more. -func (t *http2Server) closeStream(s *Stream, rst bool, rstCode http2.ErrCode, hdr *headerFrame, eosReceived bool) { - if s.swapState(streamDone) == streamDone { - // If the stream was already done, return. - return - } - // In case stream sending and receiving are invoked in separate - // goroutines (e.g., bi-directional streaming), cancel needs to be - // called to interrupt the potential blocking on other goroutines. - s.cancel() - cleanup := &cleanupStream{ - streamID: s.id, - rst: rst, - rstCode: rstCode, - onWrite: func() { - t.mu.Lock() - if t.activeStreams != nil { - delete(t.activeStreams, s.id) - if len(t.activeStreams) == 0 { - t.idle = time.Now() - } - } - t.mu.Unlock() - if channelz.IsOn() { - t.czmu.Lock() - if eosReceived { - t.streamsSucceeded++ - } else { - t.streamsFailed++ - } - t.czmu.Unlock() - } - }, - } - if hdr != nil { - hdr.cleanup = cleanup - t.controlBuf.put(hdr) - } else { - t.controlBuf.put(cleanup) - } -} - -func (t *http2Server) RemoteAddr() net.Addr { - return t.remoteAddr -} - -func (t *http2Server) Drain() { - t.drain(http2.ErrCodeNo, []byte{}) -} - -func (t *http2Server) drain(code http2.ErrCode, debugData []byte) { - t.mu.Lock() - defer t.mu.Unlock() - if t.drainChan != nil { - return - } - t.drainChan = make(chan struct{}) - t.controlBuf.put(&goAway{code: code, debugData: debugData, headsUp: true}) -} - -var goAwayPing = &ping{data: [8]byte{1, 6, 1, 8, 0, 3, 3, 9}} - -// Handles outgoing GoAway and returns true if loopy needs to put itself -// in draining mode. -func (t *http2Server) outgoingGoAwayHandler(g *goAway) (bool, error) { - t.mu.Lock() - if t.state == closing { // TODO(mmukhi): This seems unnecessary. - t.mu.Unlock() - // The transport is closing. - return false, ErrConnClosing - } - sid := t.maxStreamID - if !g.headsUp { - // Stop accepting more streams now. - t.state = draining - if len(t.activeStreams) == 0 { - g.closeConn = true - } - t.mu.Unlock() - if err := t.framer.fr.WriteGoAway(sid, g.code, g.debugData); err != nil { - return false, err - } - if g.closeConn { - // Abruptly close the connection following the GoAway (via - // loopywriter). But flush out what's inside the buffer first. - t.framer.writer.Flush() - return false, fmt.Errorf("transport: Connection closing") - } - return true, nil - } - t.mu.Unlock() - // For a graceful close, send out a GoAway with stream ID of MaxUInt32, - // Follow that with a ping and wait for the ack to come back or a timer - // to expire. During this time accept new streams since they might have - // originated before the GoAway reaches the client. - // After getting the ack or timer expiration send out another GoAway this - // time with an ID of the max stream server intends to process. - if err := t.framer.fr.WriteGoAway(math.MaxUint32, http2.ErrCodeNo, []byte{}); err != nil { - return false, err - } - if err := t.framer.fr.WritePing(false, goAwayPing.data); err != nil { - return false, err - } - go func() { - timer := time.NewTimer(time.Minute) - defer timer.Stop() - select { - case <-t.drainChan: - case <-timer.C: - case <-t.ctx.Done(): - return - } - t.controlBuf.put(&goAway{code: g.code, debugData: g.debugData}) - }() - return false, nil -} - -func (t *http2Server) ChannelzMetric() *channelz.SocketInternalMetric { - t.czmu.RLock() - s := channelz.SocketInternalMetric{ - StreamsStarted: t.streamsStarted, - StreamsSucceeded: t.streamsSucceeded, - StreamsFailed: t.streamsFailed, - MessagesSent: t.msgSent, - MessagesReceived: t.msgRecv, - KeepAlivesSent: t.kpCount, - LastRemoteStreamCreatedTimestamp: t.lastStreamCreated, - LastMessageSentTimestamp: t.lastMsgSent, - LastMessageReceivedTimestamp: t.lastMsgRecv, - LocalFlowControlWindow: int64(t.fc.getSize()), - //socket options - LocalAddr: t.localAddr, - RemoteAddr: t.remoteAddr, - // Security - // RemoteName : - } - t.czmu.RUnlock() - s.RemoteFlowControlWindow = t.getOutFlowWindow() - return &s -} - -func (t *http2Server) IncrMsgSent() { - t.czmu.Lock() - t.msgSent++ - t.lastMsgSent = time.Now() - t.czmu.Unlock() -} - -func (t *http2Server) IncrMsgRecv() { - t.czmu.Lock() - t.msgRecv++ - t.lastMsgRecv = time.Now() - t.czmu.Unlock() -} - -func (t *http2Server) getOutFlowWindow() int64 { - resp := make(chan uint32) - timer := time.NewTimer(time.Second) - defer timer.Stop() - t.controlBuf.put(&outFlowControlSizeRequest{resp}) - select { - case sz := <-resp: - return int64(sz) - case <-t.ctxDone: - return -1 - case <-timer.C: - return -2 - } -} - -var rgen = rand.New(rand.NewSource(time.Now().UnixNano())) - -func getJitter(v time.Duration) time.Duration { - if v == infinity { - return 0 - } - // Generate a jitter between +/- 10% of the value. - r := int64(v / 10) - j := rgen.Int63n(2*r) - r - return time.Duration(j) -} diff --git a/vendor/google.golang.org/grpc/transport/http_util.go b/vendor/google.golang.org/grpc/transport/http_util.go deleted file mode 100644 index a355866089c..00000000000 --- a/vendor/google.golang.org/grpc/transport/http_util.go +++ /dev/null @@ -1,574 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 transport - -import ( - "bufio" - "bytes" - "encoding/base64" - "fmt" - "net" - "net/http" - "strconv" - "strings" - "time" - - "github.com/golang/protobuf/proto" - "golang.org/x/net/http2" - "golang.org/x/net/http2/hpack" - spb "google.golang.org/genproto/googleapis/rpc/status" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -const ( - // http2MaxFrameLen specifies the max length of a HTTP2 frame. - http2MaxFrameLen = 16384 // 16KB frame - // http://http2.github.io/http2-spec/#SettingValues - http2InitHeaderTableSize = 4096 - // http2IOBufSize specifies the buffer size for sending frames. - defaultWriteBufSize = 32 * 1024 - defaultReadBufSize = 32 * 1024 - // baseContentType is the base content-type for gRPC. This is a valid - // content-type on it's own, but can also include a content-subtype such as - // "proto" as a suffix after "+" or ";". See - // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests - // for more details. - baseContentType = "application/grpc" -) - -var ( - clientPreface = []byte(http2.ClientPreface) - http2ErrConvTab = map[http2.ErrCode]codes.Code{ - http2.ErrCodeNo: codes.Internal, - http2.ErrCodeProtocol: codes.Internal, - http2.ErrCodeInternal: codes.Internal, - http2.ErrCodeFlowControl: codes.ResourceExhausted, - http2.ErrCodeSettingsTimeout: codes.Internal, - http2.ErrCodeStreamClosed: codes.Internal, - http2.ErrCodeFrameSize: codes.Internal, - http2.ErrCodeRefusedStream: codes.Unavailable, - http2.ErrCodeCancel: codes.Canceled, - http2.ErrCodeCompression: codes.Internal, - http2.ErrCodeConnect: codes.Internal, - http2.ErrCodeEnhanceYourCalm: codes.ResourceExhausted, - http2.ErrCodeInadequateSecurity: codes.PermissionDenied, - http2.ErrCodeHTTP11Required: codes.Internal, - } - statusCodeConvTab = map[codes.Code]http2.ErrCode{ - codes.Internal: http2.ErrCodeInternal, - codes.Canceled: http2.ErrCodeCancel, - codes.Unavailable: http2.ErrCodeRefusedStream, - codes.ResourceExhausted: http2.ErrCodeEnhanceYourCalm, - codes.PermissionDenied: http2.ErrCodeInadequateSecurity, - } - httpStatusConvTab = map[int]codes.Code{ - // 400 Bad Request - INTERNAL. - http.StatusBadRequest: codes.Internal, - // 401 Unauthorized - UNAUTHENTICATED. - http.StatusUnauthorized: codes.Unauthenticated, - // 403 Forbidden - PERMISSION_DENIED. - http.StatusForbidden: codes.PermissionDenied, - // 404 Not Found - UNIMPLEMENTED. - http.StatusNotFound: codes.Unimplemented, - // 429 Too Many Requests - UNAVAILABLE. - http.StatusTooManyRequests: codes.Unavailable, - // 502 Bad Gateway - UNAVAILABLE. - http.StatusBadGateway: codes.Unavailable, - // 503 Service Unavailable - UNAVAILABLE. - http.StatusServiceUnavailable: codes.Unavailable, - // 504 Gateway timeout - UNAVAILABLE. - http.StatusGatewayTimeout: codes.Unavailable, - } -) - -// Records the states during HPACK decoding. Must be reset once the -// decoding of the entire headers are finished. -type decodeState struct { - encoding string - // statusGen caches the stream status received from the trailer the server - // sent. Client side only. Do not access directly. After all trailers are - // parsed, use the status method to retrieve the status. - statusGen *status.Status - // rawStatusCode and rawStatusMsg are set from the raw trailer fields and are not - // intended for direct access outside of parsing. - rawStatusCode *int - rawStatusMsg string - httpStatus *int - // Server side only fields. - timeoutSet bool - timeout time.Duration - method string - // key-value metadata map from the peer. - mdata map[string][]string - statsTags []byte - statsTrace []byte - contentSubtype string -} - -// isReservedHeader checks whether hdr belongs to HTTP2 headers -// reserved by gRPC protocol. Any other headers are classified as the -// user-specified metadata. -func isReservedHeader(hdr string) bool { - if hdr != "" && hdr[0] == ':' { - return true - } - switch hdr { - case "content-type", - "user-agent", - "grpc-message-type", - "grpc-encoding", - "grpc-message", - "grpc-status", - "grpc-timeout", - "grpc-status-details-bin", - "te": - return true - default: - return false - } -} - -// isWhitelistedHeader checks whether hdr should be propagated -// into metadata visible to users. -func isWhitelistedHeader(hdr string) bool { - switch hdr { - case ":authority", "user-agent": - return true - default: - return false - } -} - -// contentSubtype returns the content-subtype for the given content-type. The -// given content-type must be a valid content-type that starts with -// "application/grpc". A content-subtype will follow "application/grpc" after a -// "+" or ";". See -// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for -// more details. -// -// If contentType is not a valid content-type for gRPC, the boolean -// will be false, otherwise true. If content-type == "application/grpc", -// "application/grpc+", or "application/grpc;", the boolean will be true, -// but no content-subtype will be returned. -// -// contentType is assumed to be lowercase already. -func contentSubtype(contentType string) (string, bool) { - if contentType == baseContentType { - return "", true - } - if !strings.HasPrefix(contentType, baseContentType) { - return "", false - } - // guaranteed since != baseContentType and has baseContentType prefix - switch contentType[len(baseContentType)] { - case '+', ';': - // this will return true for "application/grpc+" or "application/grpc;" - // which the previous validContentType function tested to be valid, so we - // just say that no content-subtype is specified in this case - return contentType[len(baseContentType)+1:], true - default: - return "", false - } -} - -// contentSubtype is assumed to be lowercase -func contentType(contentSubtype string) string { - if contentSubtype == "" { - return baseContentType - } - return baseContentType + "+" + contentSubtype -} - -func (d *decodeState) status() *status.Status { - if d.statusGen == nil { - // No status-details were provided; generate status using code/msg. - d.statusGen = status.New(codes.Code(int32(*(d.rawStatusCode))), d.rawStatusMsg) - } - return d.statusGen -} - -const binHdrSuffix = "-bin" - -func encodeBinHeader(v []byte) string { - return base64.RawStdEncoding.EncodeToString(v) -} - -func decodeBinHeader(v string) ([]byte, error) { - if len(v)%4 == 0 { - // Input was padded, or padding was not necessary. - return base64.StdEncoding.DecodeString(v) - } - return base64.RawStdEncoding.DecodeString(v) -} - -func encodeMetadataHeader(k, v string) string { - if strings.HasSuffix(k, binHdrSuffix) { - return encodeBinHeader(([]byte)(v)) - } - return v -} - -func decodeMetadataHeader(k, v string) (string, error) { - if strings.HasSuffix(k, binHdrSuffix) { - b, err := decodeBinHeader(v) - return string(b), err - } - return v, nil -} - -func (d *decodeState) decodeResponseHeader(frame *http2.MetaHeadersFrame) error { - for _, hf := range frame.Fields { - if err := d.processHeaderField(hf); err != nil { - return err - } - } - - // If grpc status exists, no need to check further. - if d.rawStatusCode != nil || d.statusGen != nil { - return nil - } - - // If grpc status doesn't exist and http status doesn't exist, - // then it's a malformed header. - if d.httpStatus == nil { - return streamErrorf(codes.Internal, "malformed header: doesn't contain status(gRPC or HTTP)") - } - - if *(d.httpStatus) != http.StatusOK { - code, ok := httpStatusConvTab[*(d.httpStatus)] - if !ok { - code = codes.Unknown - } - return streamErrorf(code, http.StatusText(*(d.httpStatus))) - } - - // gRPC status doesn't exist and http status is OK. - // Set rawStatusCode to be unknown and return nil error. - // So that, if the stream has ended this Unknown status - // will be propagated to the user. - // Otherwise, it will be ignored. In which case, status from - // a later trailer, that has StreamEnded flag set, is propagated. - code := int(codes.Unknown) - d.rawStatusCode = &code - return nil - -} - -func (d *decodeState) addMetadata(k, v string) { - if d.mdata == nil { - d.mdata = make(map[string][]string) - } - d.mdata[k] = append(d.mdata[k], v) -} - -func (d *decodeState) processHeaderField(f hpack.HeaderField) error { - switch f.Name { - case "content-type": - contentSubtype, validContentType := contentSubtype(f.Value) - if !validContentType { - return streamErrorf(codes.Internal, "transport: received the unexpected content-type %q", f.Value) - } - d.contentSubtype = contentSubtype - // TODO: do we want to propagate the whole content-type in the metadata, - // or come up with a way to just propagate the content-subtype if it was set? - // ie {"content-type": "application/grpc+proto"} or {"content-subtype": "proto"} - // in the metadata? - d.addMetadata(f.Name, f.Value) - case "grpc-encoding": - d.encoding = f.Value - case "grpc-status": - code, err := strconv.Atoi(f.Value) - if err != nil { - return streamErrorf(codes.Internal, "transport: malformed grpc-status: %v", err) - } - d.rawStatusCode = &code - case "grpc-message": - d.rawStatusMsg = decodeGrpcMessage(f.Value) - case "grpc-status-details-bin": - v, err := decodeBinHeader(f.Value) - if err != nil { - return streamErrorf(codes.Internal, "transport: malformed grpc-status-details-bin: %v", err) - } - s := &spb.Status{} - if err := proto.Unmarshal(v, s); err != nil { - return streamErrorf(codes.Internal, "transport: malformed grpc-status-details-bin: %v", err) - } - d.statusGen = status.FromProto(s) - case "grpc-timeout": - d.timeoutSet = true - var err error - if d.timeout, err = decodeTimeout(f.Value); err != nil { - return streamErrorf(codes.Internal, "transport: malformed time-out: %v", err) - } - case ":path": - d.method = f.Value - case ":status": - code, err := strconv.Atoi(f.Value) - if err != nil { - return streamErrorf(codes.Internal, "transport: malformed http-status: %v", err) - } - d.httpStatus = &code - case "grpc-tags-bin": - v, err := decodeBinHeader(f.Value) - if err != nil { - return streamErrorf(codes.Internal, "transport: malformed grpc-tags-bin: %v", err) - } - d.statsTags = v - d.addMetadata(f.Name, string(v)) - case "grpc-trace-bin": - v, err := decodeBinHeader(f.Value) - if err != nil { - return streamErrorf(codes.Internal, "transport: malformed grpc-trace-bin: %v", err) - } - d.statsTrace = v - d.addMetadata(f.Name, string(v)) - default: - if isReservedHeader(f.Name) && !isWhitelistedHeader(f.Name) { - break - } - v, err := decodeMetadataHeader(f.Name, f.Value) - if err != nil { - errorf("Failed to decode metadata header (%q, %q): %v", f.Name, f.Value, err) - return nil - } - d.addMetadata(f.Name, v) - } - return nil -} - -type timeoutUnit uint8 - -const ( - hour timeoutUnit = 'H' - minute timeoutUnit = 'M' - second timeoutUnit = 'S' - millisecond timeoutUnit = 'm' - microsecond timeoutUnit = 'u' - nanosecond timeoutUnit = 'n' -) - -func timeoutUnitToDuration(u timeoutUnit) (d time.Duration, ok bool) { - switch u { - case hour: - return time.Hour, true - case minute: - return time.Minute, true - case second: - return time.Second, true - case millisecond: - return time.Millisecond, true - case microsecond: - return time.Microsecond, true - case nanosecond: - return time.Nanosecond, true - default: - } - return -} - -const maxTimeoutValue int64 = 100000000 - 1 - -// div does integer division and round-up the result. Note that this is -// equivalent to (d+r-1)/r but has less chance to overflow. -func div(d, r time.Duration) int64 { - if m := d % r; m > 0 { - return int64(d/r + 1) - } - return int64(d / r) -} - -// TODO(zhaoq): It is the simplistic and not bandwidth efficient. Improve it. -func encodeTimeout(t time.Duration) string { - if t <= 0 { - return "0n" - } - if d := div(t, time.Nanosecond); d <= maxTimeoutValue { - return strconv.FormatInt(d, 10) + "n" - } - if d := div(t, time.Microsecond); d <= maxTimeoutValue { - return strconv.FormatInt(d, 10) + "u" - } - if d := div(t, time.Millisecond); d <= maxTimeoutValue { - return strconv.FormatInt(d, 10) + "m" - } - if d := div(t, time.Second); d <= maxTimeoutValue { - return strconv.FormatInt(d, 10) + "S" - } - if d := div(t, time.Minute); d <= maxTimeoutValue { - return strconv.FormatInt(d, 10) + "M" - } - // Note that maxTimeoutValue * time.Hour > MaxInt64. - return strconv.FormatInt(div(t, time.Hour), 10) + "H" -} - -func decodeTimeout(s string) (time.Duration, error) { - size := len(s) - if size < 2 { - return 0, fmt.Errorf("transport: timeout string is too short: %q", s) - } - unit := timeoutUnit(s[size-1]) - d, ok := timeoutUnitToDuration(unit) - if !ok { - return 0, fmt.Errorf("transport: timeout unit is not recognized: %q", s) - } - t, err := strconv.ParseInt(s[:size-1], 10, 64) - if err != nil { - return 0, err - } - return d * time.Duration(t), nil -} - -const ( - spaceByte = ' ' - tildaByte = '~' - percentByte = '%' -) - -// encodeGrpcMessage is used to encode status code in header field -// "grpc-message". -// It checks to see if each individual byte in msg is an -// allowable byte, and then either percent encoding or passing it through. -// When percent encoding, the byte is converted into hexadecimal notation -// with a '%' prepended. -func encodeGrpcMessage(msg string) string { - if msg == "" { - return "" - } - lenMsg := len(msg) - for i := 0; i < lenMsg; i++ { - c := msg[i] - if !(c >= spaceByte && c < tildaByte && c != percentByte) { - return encodeGrpcMessageUnchecked(msg) - } - } - return msg -} - -func encodeGrpcMessageUnchecked(msg string) string { - var buf bytes.Buffer - lenMsg := len(msg) - for i := 0; i < lenMsg; i++ { - c := msg[i] - if c >= spaceByte && c < tildaByte && c != percentByte { - buf.WriteByte(c) - } else { - buf.WriteString(fmt.Sprintf("%%%02X", c)) - } - } - return buf.String() -} - -// decodeGrpcMessage decodes the msg encoded by encodeGrpcMessage. -func decodeGrpcMessage(msg string) string { - if msg == "" { - return "" - } - lenMsg := len(msg) - for i := 0; i < lenMsg; i++ { - if msg[i] == percentByte && i+2 < lenMsg { - return decodeGrpcMessageUnchecked(msg) - } - } - return msg -} - -func decodeGrpcMessageUnchecked(msg string) string { - var buf bytes.Buffer - lenMsg := len(msg) - for i := 0; i < lenMsg; i++ { - c := msg[i] - if c == percentByte && i+2 < lenMsg { - parsed, err := strconv.ParseUint(msg[i+1:i+3], 16, 8) - if err != nil { - buf.WriteByte(c) - } else { - buf.WriteByte(byte(parsed)) - i += 2 - } - } else { - buf.WriteByte(c) - } - } - return buf.String() -} - -type bufWriter struct { - buf []byte - offset int - batchSize int - conn net.Conn - err error - - onFlush func() -} - -func newBufWriter(conn net.Conn, batchSize int) *bufWriter { - return &bufWriter{ - buf: make([]byte, batchSize*2), - batchSize: batchSize, - conn: conn, - } -} - -func (w *bufWriter) Write(b []byte) (n int, err error) { - if w.err != nil { - return 0, w.err - } - n = copy(w.buf[w.offset:], b) - w.offset += n - if w.offset >= w.batchSize { - err = w.Flush() - } - return n, err -} - -func (w *bufWriter) Flush() error { - if w.err != nil { - return w.err - } - if w.offset == 0 { - return nil - } - if w.onFlush != nil { - w.onFlush() - } - _, w.err = w.conn.Write(w.buf[:w.offset]) - w.offset = 0 - return w.err -} - -type framer struct { - writer *bufWriter - fr *http2.Framer -} - -func newFramer(conn net.Conn, writeBufferSize, readBufferSize int) *framer { - r := bufio.NewReaderSize(conn, readBufferSize) - w := newBufWriter(conn, writeBufferSize) - f := &framer{ - writer: w, - fr: http2.NewFramer(w, r), - } - // Opt-in to Frame reuse API on framer to reduce garbage. - // Frames aren't safe to read from after a subsequent call to ReadFrame. - f.fr.SetReuseFrames() - f.fr.ReadMetaHeaders = hpack.NewDecoder(http2InitHeaderTableSize, nil) - return f -} diff --git a/vendor/google.golang.org/grpc/transport/log.go b/vendor/google.golang.org/grpc/transport/log.go deleted file mode 100644 index ac8e358c5c8..00000000000 --- a/vendor/google.golang.org/grpc/transport/log.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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. - * - */ - -// This file contains wrappers for grpclog functions. -// The transport package only logs to verbose level 2 by default. - -package transport - -import "google.golang.org/grpc/grpclog" - -const logLevel = 2 - -func infof(format string, args ...interface{}) { - if grpclog.V(logLevel) { - grpclog.Infof(format, args...) - } -} - -func warningf(format string, args ...interface{}) { - if grpclog.V(logLevel) { - grpclog.Warningf(format, args...) - } -} - -func errorf(format string, args ...interface{}) { - if grpclog.V(logLevel) { - grpclog.Errorf(format, args...) - } -} - -func fatalf(format string, args ...interface{}) { - if grpclog.V(logLevel) { - grpclog.Fatalf(format, args...) - } -} diff --git a/vendor/google.golang.org/grpc/transport/transport.go b/vendor/google.golang.org/grpc/transport/transport.go deleted file mode 100644 index 2f643a3d042..00000000000 --- a/vendor/google.golang.org/grpc/transport/transport.go +++ /dev/null @@ -1,683 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 transport defines and implements message oriented communication -// channel to complete various transactions (e.g., an RPC). It is meant for -// grpc-internal usage and is not intended to be imported directly by users. -package transport // externally used as import "google.golang.org/grpc/transport" - -import ( - "errors" - "fmt" - "io" - "net" - "sync" - "sync/atomic" - - "golang.org/x/net/context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/keepalive" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" - "google.golang.org/grpc/tap" -) - -// recvMsg represents the received msg from the transport. All transport -// protocol specific info has been removed. -type recvMsg struct { - data []byte - // nil: received some data - // io.EOF: stream is completed. data is nil. - // other non-nil error: transport failure. data is nil. - err error -} - -// recvBuffer is an unbounded channel of recvMsg structs. -// Note recvBuffer differs from controlBuffer only in that recvBuffer -// holds a channel of only recvMsg structs instead of objects implementing "item" interface. -// recvBuffer is written to much more often than -// controlBuffer and using strict recvMsg structs helps avoid allocation in "recvBuffer.put" -type recvBuffer struct { - c chan recvMsg - mu sync.Mutex - backlog []recvMsg - err error -} - -func newRecvBuffer() *recvBuffer { - b := &recvBuffer{ - c: make(chan recvMsg, 1), - } - return b -} - -func (b *recvBuffer) put(r recvMsg) { - b.mu.Lock() - if b.err != nil { - b.mu.Unlock() - // An error had occurred earlier, don't accept more - // data or errors. - return - } - b.err = r.err - if len(b.backlog) == 0 { - select { - case b.c <- r: - b.mu.Unlock() - return - default: - } - } - b.backlog = append(b.backlog, r) - b.mu.Unlock() -} - -func (b *recvBuffer) load() { - b.mu.Lock() - if len(b.backlog) > 0 { - select { - case b.c <- b.backlog[0]: - b.backlog[0] = recvMsg{} - b.backlog = b.backlog[1:] - default: - } - } - b.mu.Unlock() -} - -// get returns the channel that receives a recvMsg in the buffer. -// -// Upon receipt of a recvMsg, the caller should call load to send another -// recvMsg onto the channel if there is any. -func (b *recvBuffer) get() <-chan recvMsg { - return b.c -} - -// -// recvBufferReader implements io.Reader interface to read the data from -// recvBuffer. -type recvBufferReader struct { - ctx context.Context - ctxDone <-chan struct{} // cache of ctx.Done() (for performance). - recv *recvBuffer - last []byte // Stores the remaining data in the previous calls. - err error -} - -// Read reads the next len(p) bytes from last. If last is drained, it tries to -// read additional data from recv. It blocks if there no additional data available -// in recv. If Read returns any non-nil error, it will continue to return that error. -func (r *recvBufferReader) Read(p []byte) (n int, err error) { - if r.err != nil { - return 0, r.err - } - n, r.err = r.read(p) - return n, r.err -} - -func (r *recvBufferReader) read(p []byte) (n int, err error) { - if r.last != nil && len(r.last) > 0 { - // Read remaining data left in last call. - copied := copy(p, r.last) - r.last = r.last[copied:] - return copied, nil - } - select { - case <-r.ctxDone: - return 0, ContextErr(r.ctx.Err()) - case m := <-r.recv.get(): - r.recv.load() - if m.err != nil { - return 0, m.err - } - copied := copy(p, m.data) - r.last = m.data[copied:] - return copied, nil - } -} - -type streamState uint32 - -const ( - streamActive streamState = iota - streamWriteDone // EndStream sent - streamReadDone // EndStream received - streamDone // the entire stream is finished. -) - -// Stream represents an RPC in the transport layer. -type Stream struct { - id uint32 - st ServerTransport // nil for client side Stream - ctx context.Context // the associated context of the stream - cancel context.CancelFunc // always nil for client side Stream - done chan struct{} // closed at the end of stream to unblock writers. On the client side. - ctxDone <-chan struct{} // same as done chan but for server side. Cache of ctx.Done() (for performance) - method string // the associated RPC method of the stream - recvCompress string - sendCompress string - buf *recvBuffer - trReader io.Reader - fc *inFlow - recvQuota uint32 - wq *writeQuota - - // Callback to state application's intentions to read data. This - // is used to adjust flow control, if needed. - requestRead func(int) - - headerChan chan struct{} // closed to indicate the end of header metadata. - headerDone uint32 // set when headerChan is closed. Used to avoid closing headerChan multiple times. - header metadata.MD // the received header metadata. - trailer metadata.MD // the key-value map of trailer metadata. - - headerOk bool // becomes true from the first header is about to send - state streamState - - status *status.Status // the status error received from the server - - bytesReceived uint32 // indicates whether any bytes have been received on this stream - unprocessed uint32 // set if the server sends a refused stream or GOAWAY including this stream - - // contentSubtype is the content-subtype for requests. - // this must be lowercase or the behavior is undefined. - contentSubtype string -} - -func (s *Stream) swapState(st streamState) streamState { - return streamState(atomic.SwapUint32((*uint32)(&s.state), uint32(st))) -} - -func (s *Stream) compareAndSwapState(oldState, newState streamState) bool { - return atomic.CompareAndSwapUint32((*uint32)(&s.state), uint32(oldState), uint32(newState)) -} - -func (s *Stream) getState() streamState { - return streamState(atomic.LoadUint32((*uint32)(&s.state))) -} - -func (s *Stream) waitOnHeader() error { - if s.headerChan == nil { - // On the server headerChan is always nil since a stream originates - // only after having received headers. - return nil - } - select { - case <-s.ctx.Done(): - return ContextErr(s.ctx.Err()) - case <-s.headerChan: - return nil - } -} - -// RecvCompress returns the compression algorithm applied to the inbound -// message. It is empty string if there is no compression applied. -func (s *Stream) RecvCompress() string { - if err := s.waitOnHeader(); err != nil { - return "" - } - return s.recvCompress -} - -// SetSendCompress sets the compression algorithm to the stream. -func (s *Stream) SetSendCompress(str string) { - s.sendCompress = str -} - -// Done returns a chanel which is closed when it receives the final status -// from the server. -func (s *Stream) Done() <-chan struct{} { - return s.done -} - -// Header acquires the key-value pairs of header metadata once it -// is available. It blocks until i) the metadata is ready or ii) there is no -// header metadata or iii) the stream is canceled/expired. -func (s *Stream) Header() (metadata.MD, error) { - err := s.waitOnHeader() - // Even if the stream is closed, header is returned if available. - select { - case <-s.headerChan: - if s.header == nil { - return nil, nil - } - return s.header.Copy(), nil - default: - } - return nil, err -} - -// Trailer returns the cached trailer metedata. Note that if it is not called -// after the entire stream is done, it could return an empty MD. Client -// side only. -// It can be safely read only after stream has ended that is either read -// or write have returned io.EOF. -func (s *Stream) Trailer() metadata.MD { - c := s.trailer.Copy() - return c -} - -// ServerTransport returns the underlying ServerTransport for the stream. -// The client side stream always returns nil. -func (s *Stream) ServerTransport() ServerTransport { - return s.st -} - -// ContentSubtype returns the content-subtype for a request. For example, a -// content-subtype of "proto" will result in a content-type of -// "application/grpc+proto". This will always be lowercase. See -// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for -// more details. -func (s *Stream) ContentSubtype() string { - return s.contentSubtype -} - -// Context returns the context of the stream. -func (s *Stream) Context() context.Context { - return s.ctx -} - -// Method returns the method for the stream. -func (s *Stream) Method() string { - return s.method -} - -// Status returns the status received from the server. -// Status can be read safely only after the stream has ended, -// that is, read or write has returned io.EOF. -func (s *Stream) Status() *status.Status { - return s.status -} - -// SetHeader sets the header metadata. This can be called multiple times. -// Server side only. -// This should not be called in parallel to other data writes. -func (s *Stream) SetHeader(md metadata.MD) error { - if md.Len() == 0 { - return nil - } - if s.headerOk || atomic.LoadUint32((*uint32)(&s.state)) == uint32(streamDone) { - return ErrIllegalHeaderWrite - } - s.header = metadata.Join(s.header, md) - return nil -} - -// SendHeader sends the given header metadata. The given metadata is -// combined with any metadata set by previous calls to SetHeader and -// then written to the transport stream. -func (s *Stream) SendHeader(md metadata.MD) error { - t := s.ServerTransport() - return t.WriteHeader(s, md) -} - -// SetTrailer sets the trailer metadata which will be sent with the RPC status -// by the server. This can be called multiple times. Server side only. -// This should not be called parallel to other data writes. -func (s *Stream) SetTrailer(md metadata.MD) error { - if md.Len() == 0 { - return nil - } - s.trailer = metadata.Join(s.trailer, md) - return nil -} - -func (s *Stream) write(m recvMsg) { - s.buf.put(m) -} - -// Read reads all p bytes from the wire for this stream. -func (s *Stream) Read(p []byte) (n int, err error) { - // Don't request a read if there was an error earlier - if er := s.trReader.(*transportReader).er; er != nil { - return 0, er - } - s.requestRead(len(p)) - return io.ReadFull(s.trReader, p) -} - -// tranportReader reads all the data available for this Stream from the transport and -// passes them into the decoder, which converts them into a gRPC message stream. -// The error is io.EOF when the stream is done or another non-nil error if -// the stream broke. -type transportReader struct { - reader io.Reader - // The handler to control the window update procedure for both this - // particular stream and the associated transport. - windowHandler func(int) - er error -} - -func (t *transportReader) Read(p []byte) (n int, err error) { - n, err = t.reader.Read(p) - if err != nil { - t.er = err - return - } - t.windowHandler(n) - return -} - -// BytesReceived indicates whether any bytes have been received on this stream. -func (s *Stream) BytesReceived() bool { - return atomic.LoadUint32(&s.bytesReceived) == 1 -} - -// Unprocessed indicates whether the server did not process this stream -- -// i.e. it sent a refused stream or GOAWAY including this stream ID. -func (s *Stream) Unprocessed() bool { - return atomic.LoadUint32(&s.unprocessed) == 1 -} - -// GoString is implemented by Stream so context.String() won't -// race when printing %#v. -func (s *Stream) GoString() string { - return fmt.Sprintf("", s, s.method) -} - -// state of transport -type transportState int - -const ( - reachable transportState = iota - closing - draining -) - -// ServerConfig consists of all the configurations to establish a server transport. -type ServerConfig struct { - MaxStreams uint32 - AuthInfo credentials.AuthInfo - InTapHandle tap.ServerInHandle - StatsHandler stats.Handler - KeepaliveParams keepalive.ServerParameters - KeepalivePolicy keepalive.EnforcementPolicy - InitialWindowSize int32 - InitialConnWindowSize int32 - WriteBufferSize int - ReadBufferSize int - ChannelzParentID int64 -} - -// NewServerTransport creates a ServerTransport with conn or non-nil error -// if it fails. -func NewServerTransport(protocol string, conn net.Conn, config *ServerConfig) (ServerTransport, error) { - return newHTTP2Server(conn, config) -} - -// ConnectOptions covers all relevant options for communicating with the server. -type ConnectOptions struct { - // UserAgent is the application user agent. - UserAgent string - // Authority is the :authority pseudo-header to use. This field has no effect if - // TransportCredentials is set. - Authority string - // Dialer specifies how to dial a network address. - Dialer func(context.Context, string) (net.Conn, error) - // FailOnNonTempDialError specifies if gRPC fails on non-temporary dial errors. - FailOnNonTempDialError bool - // PerRPCCredentials stores the PerRPCCredentials required to issue RPCs. - PerRPCCredentials []credentials.PerRPCCredentials - // TransportCredentials stores the Authenticator required to setup a client connection. - TransportCredentials credentials.TransportCredentials - // KeepaliveParams stores the keepalive parameters. - KeepaliveParams keepalive.ClientParameters - // StatsHandler stores the handler for stats. - StatsHandler stats.Handler - // InitialWindowSize sets the initial window size for a stream. - InitialWindowSize int32 - // InitialConnWindowSize sets the initial window size for a connection. - InitialConnWindowSize int32 - // WriteBufferSize sets the size of write buffer which in turn determines how much data can be batched before it's written on the wire. - WriteBufferSize int - // ReadBufferSize sets the size of read buffer, which in turn determines how much data can be read at most for one read syscall. - ReadBufferSize int - // ChannelzParentID sets the addrConn id which initiate the creation of this client transport. - ChannelzParentID int64 -} - -// TargetInfo contains the information of the target such as network address and metadata. -type TargetInfo struct { - Addr string - Metadata interface{} - Authority string -} - -// NewClientTransport establishes the transport with the required ConnectOptions -// and returns it to the caller. -func NewClientTransport(connectCtx, ctx context.Context, target TargetInfo, opts ConnectOptions, onSuccess func()) (ClientTransport, error) { - return newHTTP2Client(connectCtx, ctx, target, opts, onSuccess) -} - -// Options provides additional hints and information for message -// transmission. -type Options struct { - // Last indicates whether this write is the last piece for - // this stream. - Last bool - - // Delay is a hint to the transport implementation for whether - // the data could be buffered for a batching write. The - // transport implementation may ignore the hint. - Delay bool -} - -// CallHdr carries the information of a particular RPC. -type CallHdr struct { - // Host specifies the peer's host. - Host string - - // Method specifies the operation to perform. - Method string - - // SendCompress specifies the compression algorithm applied on - // outbound message. - SendCompress string - - // Creds specifies credentials.PerRPCCredentials for a call. - Creds credentials.PerRPCCredentials - - // Flush indicates whether a new stream command should be sent - // to the peer without waiting for the first data. This is - // only a hint. - // If it's true, the transport may modify the flush decision - // for performance purposes. - // If it's false, new stream will never be flushed. - Flush bool - - // ContentSubtype specifies the content-subtype for a request. For example, a - // content-subtype of "proto" will result in a content-type of - // "application/grpc+proto". The value of ContentSubtype must be all - // lowercase, otherwise the behavior is undefined. See - // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests - // for more details. - ContentSubtype string -} - -// ClientTransport is the common interface for all gRPC client-side transport -// implementations. -type ClientTransport interface { - // Close tears down this transport. Once it returns, the transport - // should not be accessed any more. The caller must make sure this - // is called only once. - Close() error - - // GracefulClose starts to tear down the transport. It stops accepting - // new RPCs and wait the completion of the pending RPCs. - GracefulClose() error - - // Write sends the data for the given stream. A nil stream indicates - // the write is to be performed on the transport as a whole. - Write(s *Stream, hdr []byte, data []byte, opts *Options) error - - // NewStream creates a Stream for an RPC. - NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, error) - - // CloseStream clears the footprint of a stream when the stream is - // not needed any more. The err indicates the error incurred when - // CloseStream is called. Must be called when a stream is finished - // unless the associated transport is closing. - CloseStream(stream *Stream, err error) - - // Error returns a channel that is closed when some I/O error - // happens. Typically the caller should have a goroutine to monitor - // this in order to take action (e.g., close the current transport - // and create a new one) in error case. It should not return nil - // once the transport is initiated. - Error() <-chan struct{} - - // GoAway returns a channel that is closed when ClientTransport - // receives the draining signal from the server (e.g., GOAWAY frame in - // HTTP/2). - GoAway() <-chan struct{} - - // GetGoAwayReason returns the reason why GoAway frame was received. - GetGoAwayReason() GoAwayReason - - // IncrMsgSent increments the number of message sent through this transport. - IncrMsgSent() - - // IncrMsgRecv increments the number of message received through this transport. - IncrMsgRecv() -} - -// ServerTransport is the common interface for all gRPC server-side transport -// implementations. -// -// Methods may be called concurrently from multiple goroutines, but -// Write methods for a given Stream will be called serially. -type ServerTransport interface { - // HandleStreams receives incoming streams using the given handler. - HandleStreams(func(*Stream), func(context.Context, string) context.Context) - - // WriteHeader sends the header metadata for the given stream. - // WriteHeader may not be called on all streams. - WriteHeader(s *Stream, md metadata.MD) error - - // Write sends the data for the given stream. - // Write may not be called on all streams. - Write(s *Stream, hdr []byte, data []byte, opts *Options) error - - // WriteStatus sends the status of a stream to the client. WriteStatus is - // the final call made on a stream and always occurs. - WriteStatus(s *Stream, st *status.Status) error - - // Close tears down the transport. Once it is called, the transport - // should not be accessed any more. All the pending streams and their - // handlers will be terminated asynchronously. - Close() error - - // RemoteAddr returns the remote network address. - RemoteAddr() net.Addr - - // Drain notifies the client this ServerTransport stops accepting new RPCs. - Drain() - - // IncrMsgSent increments the number of message sent through this transport. - IncrMsgSent() - - // IncrMsgRecv increments the number of message received through this transport. - IncrMsgRecv() -} - -// streamErrorf creates an StreamError with the specified error code and description. -func streamErrorf(c codes.Code, format string, a ...interface{}) StreamError { - return StreamError{ - Code: c, - Desc: fmt.Sprintf(format, a...), - } -} - -// connectionErrorf creates an ConnectionError with the specified error description. -func connectionErrorf(temp bool, e error, format string, a ...interface{}) ConnectionError { - return ConnectionError{ - Desc: fmt.Sprintf(format, a...), - temp: temp, - err: e, - } -} - -// ConnectionError is an error that results in the termination of the -// entire connection and the retry of all the active streams. -type ConnectionError struct { - Desc string - temp bool - err error -} - -func (e ConnectionError) Error() string { - return fmt.Sprintf("connection error: desc = %q", e.Desc) -} - -// Temporary indicates if this connection error is temporary or fatal. -func (e ConnectionError) Temporary() bool { - return e.temp -} - -// Origin returns the original error of this connection error. -func (e ConnectionError) Origin() error { - // Never return nil error here. - // If the original error is nil, return itself. - if e.err == nil { - return e - } - return e.err -} - -var ( - // ErrConnClosing indicates that the transport is closing. - ErrConnClosing = connectionErrorf(true, nil, "transport is closing") - // errStreamDrain indicates that the stream is rejected because the - // connection is draining. This could be caused by goaway or balancer - // removing the address. - errStreamDrain = streamErrorf(codes.Unavailable, "the connection is draining") - // errStreamDone is returned from write at the client side to indiacte application - // layer of an error. - errStreamDone = errors.New("the stream is done") - // StatusGoAway indicates that the server sent a GOAWAY that included this - // stream's ID in unprocessed RPCs. - statusGoAway = status.New(codes.Unavailable, "the stream is rejected because server is draining the connection") -) - -// TODO: See if we can replace StreamError with status package errors. - -// StreamError is an error that only affects one stream within a connection. -type StreamError struct { - Code codes.Code - Desc string -} - -func (e StreamError) Error() string { - return fmt.Sprintf("stream error: code = %s desc = %q", e.Code, e.Desc) -} - -// GoAwayReason contains the reason for the GoAway frame received. -type GoAwayReason uint8 - -const ( - // GoAwayInvalid indicates that no GoAway frame is received. - GoAwayInvalid GoAwayReason = 0 - // GoAwayNoReason is the default value when GoAway frame is received. - GoAwayNoReason GoAwayReason = 1 - // GoAwayTooManyPings indicates that a GoAway frame with - // ErrCodeEnhanceYourCalm was received and that the debug data said - // "too_many_pings". - GoAwayTooManyPings GoAwayReason = 2 -) diff --git a/vendor/gopkg.in/go-playground/webhooks.v3/LICENSE b/vendor/gopkg.in/go-playground/webhooks.v3/LICENSE deleted file mode 100644 index 6a2ae9aa4da..00000000000 --- a/vendor/gopkg.in/go-playground/webhooks.v3/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Dean Karn - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/vendor/gopkg.in/go-playground/webhooks.v3/github/github.go b/vendor/gopkg.in/go-playground/webhooks.v3/github/github.go deleted file mode 100644 index 2b5c9330e62..00000000000 --- a/vendor/gopkg.in/go-playground/webhooks.v3/github/github.go +++ /dev/null @@ -1,292 +0,0 @@ -package github - -import ( - "crypto/hmac" - "crypto/sha1" - "encoding/hex" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - - "gopkg.in/go-playground/webhooks.v3" -) - -// Webhook instance contains all methods needed to process events -type Webhook struct { - provider webhooks.Provider - secret string - eventFuncs map[Event]webhooks.ProcessPayloadFunc -} - -// Config defines the configuration to create a new GitHub Webhook instance -type Config struct { - Secret string -} - -// Event defines a GitHub hook event type -type Event string - -// GitHub hook types -const ( - CommitCommentEvent Event = "commit_comment" - CreateEvent Event = "create" - DeleteEvent Event = "delete" - DeploymentEvent Event = "deployment" - DeploymentStatusEvent Event = "deployment_status" - ForkEvent Event = "fork" - GollumEvent Event = "gollum" - InstallationEvent Event = "installation" - IntegrationInstallationEvent Event = "integration_installation" - IssueCommentEvent Event = "issue_comment" - IssuesEvent Event = "issues" - LabelEvent Event = "label" - MemberEvent Event = "member" - MembershipEvent Event = "membership" - MilestoneEvent Event = "milestone" - OrganizationEvent Event = "organization" - OrgBlockEvent Event = "org_block" - PageBuildEvent Event = "page_build" - PingEvent Event = "ping" - ProjectCardEvent Event = "project_card" - ProjectColumnEvent Event = "project_column" - ProjectEvent Event = "project" - PublicEvent Event = "public" - PullRequestEvent Event = "pull_request" - PullRequestReviewEvent Event = "pull_request_review" - PullRequestReviewCommentEvent Event = "pull_request_review_comment" - PushEvent Event = "push" - ReleaseEvent Event = "release" - RepositoryEvent Event = "repository" - StatusEvent Event = "status" - TeamEvent Event = "team" - TeamAddEvent Event = "team_add" - WatchEvent Event = "watch" -) - -// EventSubtype defines a GitHub Hook Event subtype -type EventSubtype string - -// GitHub hook event subtypes -const ( - NoSubtype EventSubtype = "" - BranchSubtype EventSubtype = "branch" - TagSubtype EventSubtype = "tag" - PullSubtype EventSubtype = "pull" - IssueSubtype EventSubtype = "issues" -) - -// New creates and returns a WebHook instance denoted by the Provider type -func New(config *Config) *Webhook { - return &Webhook{ - provider: webhooks.GitHub, - secret: config.Secret, - eventFuncs: map[Event]webhooks.ProcessPayloadFunc{}, - } -} - -// Provider returns the current hooks provider ID -func (hook Webhook) Provider() webhooks.Provider { - return hook.provider -} - -// RegisterEvents registers the function to call when the specified event(s) are encountered -func (hook Webhook) RegisterEvents(fn webhooks.ProcessPayloadFunc, events ...Event) { - - for _, event := range events { - hook.eventFuncs[event] = fn - } -} - -// ParsePayload parses and verifies the payload and fires off the mapped function, if it exists. -func (hook Webhook) ParsePayload(w http.ResponseWriter, r *http.Request) { - webhooks.DefaultLog.Info("Parsing Payload...") - - event := r.Header.Get("X-GitHub-Event") - if len(event) == 0 { - webhooks.DefaultLog.Error("Missing X-GitHub-Event Header") - http.Error(w, "400 Bad Request - Missing X-GitHub-Event Header", http.StatusBadRequest) - return - } - webhooks.DefaultLog.Debug(fmt.Sprintf("X-GitHub-Event:%s", event)) - - gitHubEvent := Event(event) - - fn, ok := hook.eventFuncs[gitHubEvent] - // if no event registered - if !ok { - webhooks.DefaultLog.Info(fmt.Sprintf("Webhook Event %s not registered, it is recommended to setup only events in github that will be registered in the webhook to avoid unnecessary traffic and reduce potential attack vectors.", event)) - return - } - - payload, err := ioutil.ReadAll(r.Body) - if err != nil || len(payload) == 0 { - webhooks.DefaultLog.Error("Issue reading Payload") - http.Error(w, "Issue reading Payload", http.StatusInternalServerError) - return - } - webhooks.DefaultLog.Debug(fmt.Sprintf("Payload:%s", string(payload))) - - // If we have a Secret set, we should check the MAC - if len(hook.secret) > 0 { - webhooks.DefaultLog.Info("Checking secret") - signature := r.Header.Get("X-Hub-Signature") - if len(signature) == 0 { - webhooks.DefaultLog.Error("Missing X-Hub-Signature required for HMAC verification") - http.Error(w, "403 Forbidden - Missing X-Hub-Signature required for HMAC verification", http.StatusForbidden) - return - } - webhooks.DefaultLog.Debug(fmt.Sprintf("X-Hub-Signature:%s", signature)) - - mac := hmac.New(sha1.New, []byte(hook.secret)) - mac.Write(payload) - - expectedMAC := hex.EncodeToString(mac.Sum(nil)) - - if !hmac.Equal([]byte(signature[5:]), []byte(expectedMAC)) { - webhooks.DefaultLog.Error("HMAC verification failed") - http.Error(w, "403 Forbidden - HMAC verification failed", http.StatusForbidden) - return - } - } - - // Make headers available to ProcessPayloadFunc as a webhooks type - hd := webhooks.Header(r.Header) - - switch gitHubEvent { - case CommitCommentEvent: - var cc CommitCommentPayload - json.Unmarshal([]byte(payload), &cc) - hook.runProcessPayloadFunc(fn, cc, hd) - case CreateEvent: - var c CreatePayload - json.Unmarshal([]byte(payload), &c) - hook.runProcessPayloadFunc(fn, c, hd) - case DeleteEvent: - var d DeletePayload - json.Unmarshal([]byte(payload), &d) - hook.runProcessPayloadFunc(fn, d, hd) - case DeploymentEvent: - var d DeploymentPayload - json.Unmarshal([]byte(payload), &d) - hook.runProcessPayloadFunc(fn, d, hd) - case DeploymentStatusEvent: - var d DeploymentStatusPayload - json.Unmarshal([]byte(payload), &d) - hook.runProcessPayloadFunc(fn, d, hd) - case ForkEvent: - var f ForkPayload - json.Unmarshal([]byte(payload), &f) - hook.runProcessPayloadFunc(fn, f, hd) - case GollumEvent: - var g GollumPayload - json.Unmarshal([]byte(payload), &g) - hook.runProcessPayloadFunc(fn, g, hd) - case InstallationEvent, IntegrationInstallationEvent: - var i InstallationPayload - json.Unmarshal([]byte(payload), &i) - hook.runProcessPayloadFunc(fn, i, hd) - case IssueCommentEvent: - var i IssueCommentPayload - json.Unmarshal([]byte(payload), &i) - hook.runProcessPayloadFunc(fn, i, hd) - case IssuesEvent: - var i IssuesPayload - json.Unmarshal([]byte(payload), &i) - hook.runProcessPayloadFunc(fn, i, hd) - case LabelEvent: - var l LabelPayload - json.Unmarshal([]byte(payload), &l) - hook.runProcessPayloadFunc(fn, l, hd) - case MemberEvent: - var m MemberPayload - json.Unmarshal([]byte(payload), &m) - hook.runProcessPayloadFunc(fn, m, hd) - case MembershipEvent: - var m MembershipPayload - json.Unmarshal([]byte(payload), &m) - hook.runProcessPayloadFunc(fn, m, hd) - case MilestoneEvent: - var m MilestonePayload - json.Unmarshal([]byte(payload), &m) - hook.runProcessPayloadFunc(fn, m, hd) - case OrganizationEvent: - var o OrganizationPayload - json.Unmarshal([]byte(payload), &o) - hook.runProcessPayloadFunc(fn, o, hd) - case OrgBlockEvent: - var o OrgBlockPayload - json.Unmarshal([]byte(payload), &o) - hook.runProcessPayloadFunc(fn, o, hd) - case PageBuildEvent: - var p PageBuildPayload - json.Unmarshal([]byte(payload), &p) - hook.runProcessPayloadFunc(fn, p, hd) - case PingEvent: - var p PingPayload - json.Unmarshal([]byte(payload), &p) - hook.runProcessPayloadFunc(fn, p, hd) - case ProjectCardEvent: - var p ProjectCardPayload - json.Unmarshal([]byte(payload), &p) - hook.runProcessPayloadFunc(fn, p, hd) - case ProjectColumnEvent: - var p ProjectColumnPayload - json.Unmarshal([]byte(payload), &p) - hook.runProcessPayloadFunc(fn, p, hd) - case ProjectEvent: - var p ProjectPayload - json.Unmarshal([]byte(payload), &p) - hook.runProcessPayloadFunc(fn, p, hd) - case PublicEvent: - var p PublicPayload - json.Unmarshal([]byte(payload), &p) - hook.runProcessPayloadFunc(fn, p, hd) - case PullRequestEvent: - var p PullRequestPayload - json.Unmarshal([]byte(payload), &p) - hook.runProcessPayloadFunc(fn, p, hd) - case PullRequestReviewEvent: - var p PullRequestReviewPayload - json.Unmarshal([]byte(payload), &p) - hook.runProcessPayloadFunc(fn, p, hd) - case PullRequestReviewCommentEvent: - var p PullRequestReviewCommentPayload - json.Unmarshal([]byte(payload), &p) - hook.runProcessPayloadFunc(fn, p, hd) - case PushEvent: - var p PushPayload - json.Unmarshal([]byte(payload), &p) - hook.runProcessPayloadFunc(fn, p, hd) - case ReleaseEvent: - var r ReleasePayload - json.Unmarshal([]byte(payload), &r) - hook.runProcessPayloadFunc(fn, r, hd) - case RepositoryEvent: - var r RepositoryPayload - json.Unmarshal([]byte(payload), &r) - hook.runProcessPayloadFunc(fn, r, hd) - case StatusEvent: - var s StatusPayload - json.Unmarshal([]byte(payload), &s) - hook.runProcessPayloadFunc(fn, s, hd) - case TeamEvent: - var t TeamPayload - json.Unmarshal([]byte(payload), &t) - hook.runProcessPayloadFunc(fn, t, hd) - case TeamAddEvent: - var t TeamAddPayload - json.Unmarshal([]byte(payload), &t) - hook.runProcessPayloadFunc(fn, t, hd) - case WatchEvent: - var w WatchPayload - json.Unmarshal([]byte(payload), &w) - hook.runProcessPayloadFunc(fn, w, hd) - } -} - -func (hook Webhook) runProcessPayloadFunc(fn webhooks.ProcessPayloadFunc, results interface{}, header webhooks.Header) { - go func(fn webhooks.ProcessPayloadFunc, results interface{}, header webhooks.Header) { - fn(results, header) - }(fn, results, header) -} diff --git a/vendor/gopkg.in/go-playground/webhooks.v3/github/payload.go b/vendor/gopkg.in/go-playground/webhooks.v3/github/payload.go deleted file mode 100644 index 330c44916a4..00000000000 --- a/vendor/gopkg.in/go-playground/webhooks.v3/github/payload.go +++ /dev/null @@ -1,5087 +0,0 @@ -package github - -import "time" - -// CommitCommentPayload contains the information for GitHub's commit_comment hook event -type CommitCommentPayload struct { - Action string `json:"action"` - Comment struct { - URL string `json:"url"` - HTMLURL string `json:"html_url"` - ID int64 `json:"id"` - User struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"user"` - Position *int64 `json:"position"` - Line *int64 `json:"line"` - Path *string `json:"path"` - CommitID string `json:"commit_id"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - Body string `json:"body"` - AuthorAssociation string `json:"author_association"` - } `json:"comment"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// CreatePayload contains the information for GitHub's create hook event -type CreatePayload struct { - Ref string `json:"ref"` - RefType string `json:"ref_type"` - MasterBranch string `json:"master_branch"` - Description string `json:"description"` - PusherType string `json:"pusher_type"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// DeletePayload contains the information for GitHub's delete hook event -type DeletePayload struct { - Ref string `json:"ref"` - RefType string `json:"ref_type"` - PusherType string `json:"pusher_type"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// DeploymentPayload contains the information for GitHub's deployment hook -type DeploymentPayload struct { - Deployment struct { - URL string `json:"url"` - ID int64 `json:"id"` - Sha string `json:"sha"` - Ref string `json:"ref"` - Task string `json:"task"` - Payload struct { - } `json:"payload"` - Environment string `json:"environment"` - Description *string `json:"description"` - Creator struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"creator"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - StatusesURL string `json:"statuses_url"` - RepositoryURL string `json:"repository_url"` - } `json:"deployment"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// DeploymentStatusPayload contains the information for GitHub's deployment_status hook event -type DeploymentStatusPayload struct { - DeploymentStatus struct { - URL string `json:"url"` - ID int64 `json:"id"` - State string `json:"state"` - Creator struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"creator"` - Description *string `json:"description"` - TargetURL *string `json:"target_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - DeploymentURL string `json:"deployment_url"` - RepositoryURL string `json:"repository_url"` - } `json:"deployment_status"` - Deployment struct { - URL string `json:"url"` - ID int64 `json:"id"` - Sha string `json:"sha"` - Ref string `json:"ref"` - Task string `json:"task"` - Payload struct { - } `json:"payload"` - Environment string `json:"environment"` - Description *string `json:"description"` - Creator struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"creator"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - StatusesURL string `json:"statuses_url"` - RepositoryURL string `json:"repository_url"` - } `json:"deployment"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// ForkPayload contains the information for GitHub's fork hook event -type ForkPayload struct { - Forkee struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - Public bool `json:"public"` - } `json:"forkee"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// GollumPayload contains the information for GitHub's gollum hook event -type GollumPayload struct { - Pages []struct { - PageName string `json:"page_name"` - Title string `json:"title"` - Summary *string `json:"summary"` - Action string `json:"action"` - Sha string `json:"sha"` - HTMLURL string `json:"html_url"` - } `json:"pages"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// InstallationPayload contains the information for GitHub's installation and integration_installation hook events -type InstallationPayload struct { - Action string `json:"action"` - Installation struct { - ID int64 `json:"id"` - Account struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"account"` - RepositorySelection string `json:"repository_selection"` - AccessTokensURL string `json:"access_tokens_url"` - RepositoriesURL string `json:"repositories_url"` - HTMLURL string `json:"html_url"` - AppID int `json:"app_id"` - TargetID int `json:"target_id"` - TargetType string `json:"target_type"` - Permissions struct { - Issues string `json:"issues"` - Metadata string `json:"metadata"` - PullRequests string `json:"pull_requests"` - RepositoryProjects string `json:"repository_projects"` - } `json:"permissions"` - Events []string `json:"events"` - CreatedAt int64 `json:"created_at"` - UpdatedAt int64 `json:"updated_at"` - SingleFileName *string `json:"single_file_name"` - } `json:"installation"` - Repositories []struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - } `json:"repositories"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// IssueCommentPayload contains the information for GitHub's issue_comment hook event -type IssueCommentPayload struct { - Action string `json:"action"` - Issue struct { - URL string `json:"url"` - LabelsURL string `json:"labels_url"` - CommentsURL string `json:"comments_url"` - EventsURL string `json:"events_url"` - HTMLURL string `json:"html_url"` - ID int64 `json:"id"` - Number int64 `json:"number"` - Title string `json:"title"` - User struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"user"` - Labels []struct { - URL string `json:"url"` - Name string `json:"name"` - Color string `json:"color"` - } `json:"labels"` - State string `json:"state"` - Locked bool `json:"locked"` - Assignee *Assignee `json:"assignee"` - Milestone *Milestone `json:"milestone"` - Comments int64 `json:"comments"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - ClosedAt *time.Time `json:"closed_at"` - Body string `json:"body"` - } `json:"issue"` - Comment struct { - URL string `json:"url"` - HTMLURL string `json:"html_url"` - IssueURL string `json:"issue_url"` - ID int64 `json:"id"` - User struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"user"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - Body string `json:"body"` - AuthorAssociation string `json:"author_association"` - } `json:"comment"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// IssuesPayload contains the information for GitHub's issues hook event -type IssuesPayload struct { - Action string `json:"action"` - Issue struct { - URL string `json:"url"` - LabelsURL string `json:"labels_url"` - CommentsURL string `json:"comments_url"` - EventsURL string `json:"events_url"` - HTMLURL string `json:"html_url"` - ID int64 `json:"id"` - Number int64 `json:"number"` - Title string `json:"title"` - User struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"user"` - Labels []struct { - ID int64 `json:"id"` - URL string `json:"url"` - Name string `json:"name"` - Color string `json:"color"` - Default bool `json:"default"` - } `json:"labels"` - State string `json:"state"` - Locked bool `json:"locked"` - Assignee *Assignee `json:"assignee"` - Milestone *Milestone `json:"milestone"` - Comments int64 `json:"comments"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - ClosedAt *time.Time `json:"closed_at"` - Body string `json:"body"` - } `json:"issue"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// LabelPayload contains the information for GitHub's label hook event -type LabelPayload struct { - Action string `json:"action"` - Label struct { - URL string `json:"url"` - Name string `json:"name"` - Color string `json:"color"` - } `json:"label"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description *string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - DeploymentsURL string `json:"deployments_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Organization struct { - Login string `json:"login"` - ID int64 `json:"id"` - URL string `json:"url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - HooksURL string `json:"hooks_url"` - IssuesURL string `json:"issues_url"` - MembersURL string `json:"members_url"` - PublicMembersURL string `json:"public_members_url"` - AvatarURL string `json:"avatar_url"` - Description string `json:"description"` - } `json:"organization"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// MemberPayload contains the information for GitHub's member hook event -type MemberPayload struct { - Action string `json:"action"` - Member struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"member"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// MembershipPayload contains the information for GitHub's membership hook event -type MembershipPayload struct { - Action string `json:"action"` - Scope string `json:"scope"` - Member struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"member"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` - Team struct { - Name string `json:"name"` - ID int64 `json:"id"` - Slug string `json:"slug"` - Permission string `json:"permission"` - URL string `json:"url"` - MembersURL string `json:"members_url"` - RepositoriesURL string `json:"repositories_url"` - } `json:"team"` - Organization struct { - Login string `json:"login"` - ID int64 `json:"id"` - URL string `json:"url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - MembersURL string `json:"members_url"` - PublicMembersURL string `json:"public_members_url"` - AvatarURL string `json:"avatar_url"` - } `json:"organization"` -} - -// MilestonePayload contains the information for GitHub's milestone hook event -type MilestonePayload struct { - Action string `json:"action"` - Milestone struct { - URL string `json:"url"` - HTMLURL string `json:"html_url"` - LabelsURL string `json:"labels_url"` - ID int64 `json:"id"` - Number int64 `json:"number"` - Title string `json:"title"` - Description *string `json:"description"` - Creator struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"creator"` - OpenIssues int64 `json:"open_issues"` - ClosedIssues int64 `json:"closed_issues"` - State string `json:"state"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - DueOn *time.Time `json:"due_on"` - ClosedAt *time.Time `json:"closed_at"` - } `json:"milestone"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description *string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - DeploymentsURL string `json:"deployments_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Organization struct { - Login string `json:"login"` - ID int64 `json:"id"` - URL string `json:"url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - HooksURL string `json:"hooks_url"` - IssuesURL string `json:"issues_url"` - MembersURL string `json:"members_url"` - PublicMembersURL string `json:"public_members_url"` - AvatarURL string `json:"avatar_url"` - Description string `json:"description"` - } `json:"organization"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// OrganizationPayload contains the information for GitHub's organization hook event -type OrganizationPayload struct { - Action string `json:"action"` - Invitation struct { - ID int64 `json:"id"` - Login string `json:"login"` - Email *string `json:"email"` - Role string `json:"role"` - } `json:"invitation"` - Membership struct { - URL string `json:"url"` - State string `json:"state"` - Role string `json:"role"` - OrganizationURL string `json:"organization_url"` - User struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"user"` - } `json:"membership"` - Organization struct { - Login string `json:"login"` - ID int64 `json:"id"` - URL string `json:"url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - HooksURL string `json:"hooks_url"` - IssuesURL string `json:"issues_url"` - MembersURL string `json:"members_url"` - PublicMembersURL string `json:"public_members_url"` - AvatarURL string `json:"avatar_url"` - Description string `json:"description"` - } `json:"organization"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// OrgBlockPayload contains the information for GitHub's org_block hook event -type OrgBlockPayload struct { - Action string `json:"action"` - BlockedUser struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"blocked_user"` - Organization struct { - Login string `json:"login"` - ID int64 `json:"id"` - URL string `json:"url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - HooksURL string `json:"hooks_url"` - IssuesURL string `json:"issues_url"` - MembersURL string `json:"members_url"` - PublicMembersURL string `json:"public_members_url"` - AvatarURL string `json:"avatar_url"` - Description string `json:"description"` - } `json:"organization"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// PageBuildPayload contains the information for GitHub's page_build hook event -type PageBuildPayload struct { - ID int64 `json:"id"` - Build struct { - URL string `json:"url"` - Status string `json:"status"` - Error struct { - Message *string `json:"message"` - } `json:"error"` - Pusher struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"pusher"` - Commit string `json:"commit"` - Duration int64 `json:"duration"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - } `json:"build"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// PingPayload contains the information for GitHub's ping hook event -type PingPayload struct { - HookID int `json:"hook_id"` - Hook struct { - Type string `json:"type"` - ID int64 `json:"id"` - Name string `json:"name"` - Active bool `json:"active"` - Events []string `json:"events"` - AppID int `json:"app_id"` - Config struct { - ContentType string `json:"content_type"` - InsecureSSL int `json:"insecure_ssl"` - Secret string `json:"secret"` - URL string `json:"url"` - } `json:"config"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - } `json:"hook"` -} - -// ProjectCardPayload contains the information for GitHub's project_payload hook event -type ProjectCardPayload struct { - Action string `json:"action"` - ProjectCard struct { - URL string `json:"url"` - ColumnURL string `json:"column_url"` - ColumnID int64 `json:"column_id"` - ID int64 `json:"id"` - Note *string `json:"note"` - Creator struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"creator"` - CreatedAt int64 `json:"created_at"` - UpdatedAt int64 `json:"updated_at"` - ContentURL string `json:"content_url"` - } `json:"project_card"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Organization struct { - Login string `json:"login"` - ID int64 `json:"id"` - URL string `json:"url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - MembersURL string `json:"members_url"` - PublicMembersURL string `json:"public_members_url"` - AvatarURL string `json:"avatar_url"` - } `json:"organization"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// ProjectColumnPayload contains the information for GitHub's project_column hook event -type ProjectColumnPayload struct { - Action string `json:"action"` - ProjectColumn struct { - URL string `json:"url"` - ProjectURL string `json:"project_url"` - CardsURL string `json:"cards_url"` - ID int64 `json:"id"` - Name string `json:"name"` - CreatedAt int64 `json:"created_at"` - UpdatedAt int64 `json:"updated_at"` - } `json:"project_column"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Organization struct { - Login string `json:"login"` - ID int64 `json:"id"` - URL string `json:"url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - MembersURL string `json:"members_url"` - PublicMembersURL string `json:"public_members_url"` - AvatarURL string `json:"avatar_url"` - } `json:"organization"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// ProjectPayload contains the information for GitHub's project hook event -type ProjectPayload struct { - Action string `json:"action"` - Project struct { - OwnerURL string `json:"owner_url"` - URL string `json:"url"` - ColumnsURL string `json:"columns_url"` - ID int64 `json:"id"` - Name string `json:"name"` - Body string `json:"body"` - Number int64 `json:"number"` - State string `json:"state"` - Creator struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"creator"` - CreatedAt int64 `json:"created_at"` - UpdatedAt int64 `json:"updated_at"` - } `json:"project"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Organization struct { - Login string `json:"login"` - ID int64 `json:"id"` - URL string `json:"url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - MembersURL string `json:"members_url"` - PublicMembersURL string `json:"public_members_url"` - AvatarURL string `json:"avatar_url"` - } `json:"organization"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// PublicPayload contains the information for GitHub's public hook event -type PublicPayload struct { - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// PullRequestPayload contains the information for GitHub's pull_request hook event -type PullRequestPayload struct { - Action string `json:"action"` - Number int64 `json:"number"` - PullRequest struct { - URL string `json:"url"` - ID int64 `json:"id"` - HTMLURL string `json:"html_url"` - DiffURL string `json:"diff_url"` - PatchURL string `json:"patch_url"` - IssueURL string `json:"issue_url"` - Number int64 `json:"number"` - State string `json:"state"` - Locked bool `json:"locked"` - Title string `json:"title"` - User struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"user"` - Body string `json:"body"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - ClosedAt *time.Time `json:"closed_at"` - MergedAt *time.Time `json:"merged_at"` - MergeCommitSha *string `json:"merge_commit_sha"` - Assignee *Assignee `json:"assignee"` - Milestone *Milestone `json:"milestone"` - CommitsURL string `json:"commits_url"` - ReviewCommentsURL string `json:"review_comments_url"` - ReviewCommentURL string `json:"review_comment_url"` - CommentsURL string `json:"comments_url"` - StatusesURL string `json:"statuses_url"` - RequestedReviewers []struct { - Login string `json:"login"` - ID int `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"requested_reviewers,omitempty"` - Labels []struct { - ID int64 `json:"id"` - URL string `json:"url"` - Name string `json:"name"` - Color string `json:"color"` - Default bool `json:"default"` - } `json:"labels"` - Head struct { - Label string `json:"label"` - Ref string `json:"ref"` - Sha string `json:"sha"` - User struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"user"` - Repo struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repo"` - } `json:"head"` - Base struct { - Label string `json:"label"` - Ref string `json:"ref"` - Sha string `json:"sha"` - User struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"user"` - Repo struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repo"` - } `json:"base"` - Links struct { - Self struct { - Href string `json:"href"` - } `json:"self"` - HTML struct { - Href string `json:"href"` - } `json:"html"` - Issue struct { - Href string `json:"href"` - } `json:"issue"` - Comments struct { - Href string `json:"href"` - } `json:"comments"` - ReviewComments struct { - Href string `json:"href"` - } `json:"review_comments"` - ReviewComment struct { - Href string `json:"href"` - } `json:"review_comment"` - Commits struct { - Href string `json:"href"` - } `json:"commits"` - Statuses struct { - Href string `json:"href"` - } `json:"statuses"` - } `json:"_links"` - Merged bool `json:"merged"` - Mergeable *bool `json:"mergeable"` - MergeableState string `json:"mergeable_state"` - MergedBy *MergedBy `json:"merged_by"` - Comments int64 `json:"comments"` - ReviewComments int64 `json:"review_comments"` - Commits int64 `json:"commits"` - Additions int64 `json:"additions"` - Deletions int64 `json:"deletions"` - ChangedFiles int64 `json:"changed_files"` - } `json:"pull_request"` - Label struct { - ID int64 `json:"id"` - URL string `json:"url"` - Name string `json:"name"` - Color string `json:"color"` - Default bool `json:"default"` - } `json:"label"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` - Installation struct { - ID int64 `json:"id"` - } `json:"installation"` -} - -// PullRequestReviewPayload contains the information for GitHub's pull_request_review hook event -type PullRequestReviewPayload struct { - Action string `json:"action"` - Review struct { - ID int64 `json:"id"` - User struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"user"` - Body string `json:"body"` - SubmittedAt time.Time `json:"submitted_at"` - State string `json:"state"` - HTMLURL string `json:"html_url"` - PullRequestURL string `json:"pull_request_url"` - Links struct { - HTML struct { - Href string `json:"href"` - } `json:"html"` - PullRequest struct { - Href string `json:"href"` - } `json:"pull_request"` - } `json:"_links"` - } `json:"review"` - PullRequest struct { - URL string `json:"url"` - ID int64 `json:"id"` - HTMLURL string `json:"html_url"` - DiffURL string `json:"diff_url"` - PatchURL string `json:"patch_url"` - IssueURL string `json:"issue_url"` - Number int64 `json:"number"` - State string `json:"state"` - Locked bool `json:"locked"` - Title string `json:"title"` - User struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"user"` - Body string `json:"body"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - ClosedAt *time.Time `json:"closed_at"` - MergedAt *time.Time `json:"merged_at"` - MergeCommitSha string `json:"merge_commit_sha"` - Assignee *Assignee `json:"assignee"` - Assignees []Assignee `json:"assignees"` - Milestone *Milestone `json:"milestone"` - CommitsURL string `json:"commits_url"` - ReviewCommentsURL string `json:"review_comments_url"` - ReviewCommentURL string `json:"review_comment_url"` - CommentsURL string `json:"comments_url"` - StatusesURL string `json:"statuses_url"` - Head struct { - Label string `json:"label"` - Ref string `json:"ref"` - Sha string `json:"sha"` - User struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"user"` - Repo struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description *string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - DeploymentsURL string `json:"deployments_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repo"` - } `json:"head"` - Base struct { - Label string `json:"label"` - Ref string `json:"ref"` - Sha string `json:"sha"` - User struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"user"` - Repo struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - DeploymentsURL string `json:"deployments_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repo"` - } `json:"base"` - Links struct { - Self struct { - Href string `json:"href"` - } `json:"self"` - HTML struct { - Href string `json:"href"` - } `json:"html"` - Issue struct { - Href string `json:"href"` - } `json:"issue"` - Comments struct { - Href string `json:"href"` - } `json:"comments"` - ReviewComments struct { - Href string `json:"href"` - } `json:"review_comments"` - ReviewComment struct { - Href string `json:"href"` - } `json:"review_comment"` - Commits struct { - Href string `json:"href"` - } `json:"commits"` - Statuses struct { - Href string `json:"href"` - } `json:"statuses"` - } `json:"_links"` - } `json:"pull_request"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - DeploymentsURL string `json:"deployments_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// PullRequestReviewCommentPayload contains the information for GitHub's pull_request_review_comments hook event -type PullRequestReviewCommentPayload struct { - Action string `json:"action"` - Comment struct { - URL string `json:"url"` - ID int64 `json:"id"` - DiffHunk string `json:"diff_hunk"` - Path string `json:"path"` - Position int64 `json:"position"` - OriginalPosition int64 `json:"original_position"` - CommitID string `json:"commit_id"` - OriginalCommitID string `json:"original_commit_id"` - User struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"user"` - Body string `json:"body"` - AuthorAssociation string `json:"author_association"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - HTMLURL string `json:"html_url"` - PullRequestURL string `json:"pull_request_url"` - Links struct { - Self struct { - Href string `json:"href"` - } `json:"self"` - HTML struct { - Href string `json:"href"` - } `json:"html"` - PullRequest struct { - Href string `json:"href"` - } `json:"pull_request"` - } `json:"_links"` - } `json:"comment"` - PullRequest struct { - URL string `json:"url"` - ID int64 `json:"id"` - HTMLURL string `json:"html_url"` - DiffURL string `json:"diff_url"` - PatchURL string `json:"patch_url"` - IssueURL string `json:"issue_url"` - Number int64 `json:"number"` - State string `json:"state"` - Locked bool `json:"locked"` - Title string `json:"title"` - User struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"user"` - Body string `json:"body"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - ClosedAt *time.Time `json:"closed_at"` - MergedAt *time.Time `json:"merged_at"` - MergeCommitSha string `json:"merge_commit_sha"` - Assignee *Assignee `json:"assignee"` - Milestone *Milestone `json:"milestone"` - CommitsURL string `json:"commits_url"` - ReviewCommentsURL string `json:"review_comments_url"` - ReviewCommentURL string `json:"review_comment_url"` - CommentsURL string `json:"comments_url"` - StatusesURL string `json:"statuses_url"` - Head struct { - Label string `json:"label"` - Ref string `json:"ref"` - Sha string `json:"sha"` - User struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"user"` - Repo struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repo"` - } `json:"head"` - Base struct { - Label string `json:"label"` - Ref string `json:"ref"` - Sha string `json:"sha"` - User struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"user"` - Repo struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repo"` - } `json:"base"` - Links struct { - Self struct { - Href string `json:"href"` - } `json:"self"` - HTML struct { - Href string `json:"href"` - } `json:"html"` - Issue struct { - Href string `json:"href"` - } `json:"issue"` - Comments struct { - Href string `json:"href"` - } `json:"comments"` - ReviewComments struct { - Href string `json:"href"` - } `json:"review_comments"` - ReviewComment struct { - Href string `json:"href"` - } `json:"review_comment"` - Commits struct { - Href string `json:"href"` - } `json:"commits"` - Statuses struct { - Href string `json:"href"` - } `json:"statuses"` - } `json:"_links"` - } `json:"pull_request"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// PushPayload contains the information for GitHub's push hook event -type PushPayload struct { - Ref string `json:"ref"` - Before string `json:"before"` - After string `json:"after"` - Created bool `json:"created"` - Deleted bool `json:"deleted"` - Forced bool `json:"forced"` - BaseRef *string `json:"base_ref"` - Compare string `json:"compare"` - Commits []struct { - Sha string `json:"sha"` - ID string `json:"id"` - TreeID string `json:"tree_id"` - Distinct bool `json:"distinct"` - Message string `json:"message"` - Timestamp string `json:"timestamp"` - URL string `json:"url"` - Author struct { - Name string `json:"name"` - Email string `json:"email"` - Username string `json:"username"` - } `json:"author"` - Committer struct { - Name string `json:"name"` - Email string `json:"email"` - Username string `json:"username"` - } `json:"committer"` - Added []string `json:"added"` - Removed []string `json:"removed"` - Modified []string `json:"modified"` - } `json:"commits"` - HeadCommit struct { - ID string `json:"id"` - TreeID string `json:"tree_id"` - Distinct bool `json:"distinct"` - Message string `json:"message"` - Timestamp string `json:"timestamp"` - URL string `json:"url"` - Author struct { - Name string `json:"name"` - Email string `json:"email"` - Username string `json:"username"` - } `json:"author"` - Committer struct { - Name string `json:"name"` - Email string `json:"email"` - Username string `json:"username"` - } `json:"committer"` - Added []string `json:"added"` - Removed []string `json:"removed"` - Modified []string `json:"modified"` - } `json:"head_commit"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Name string `json:"name"` - Email string `json:"email"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt int64 `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt int64 `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - Stargazers int64 `json:"stargazers"` - MasterBranch string `json:"master_branch"` - } `json:"repository"` - Pusher struct { - Name string `json:"name"` - Email string `json:"email"` - } `json:"pusher"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// ReleasePayload contains the information for GitHub's release hook event -type ReleasePayload struct { - Action string `json:"action"` - Release struct { - URL string `json:"url"` - AssetsURL string `json:"assets_url"` - UploadURL string `json:"upload_url"` - HTMLURL string `json:"html_url"` - ID int64 `json:"id"` - TagName string `json:"tag_name"` - TargetCommitish string `json:"target_commitish"` - Name *string `json:"name"` - Draft bool `json:"draft"` - Author struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"author"` - Prerelease bool `json:"prerelease"` - CreatedAt time.Time `json:"created_at"` - PublishedAt time.Time `json:"published_at"` - Assets []Asset `json:"assets"` - TarballURL string `json:"tarball_url"` - ZipballURL string `json:"zipball_url"` - Body *string `json:"body"` - } `json:"release"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// RepositoryPayload contains the information for GitHub's repository hook event -type RepositoryPayload struct { - Action string `json:"action"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Organization struct { - Login string `json:"login"` - ID int64 `json:"id"` - URL string `json:"url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - MembersURL string `json:"members_url"` - PublicMembersURL string `json:"public_members_url"` - AvatarURL string `json:"avatar_url"` - } `json:"organization"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// StatusPayload contains the information for GitHub's status hook event -type StatusPayload struct { - ID int64 `json:"id"` - Sha string `json:"sha"` - Name string `json:"name"` - TargetURL *string `json:"target_url"` - Context string `json:"context"` - Description *string `json:"description"` - State string `json:"state"` - Commit struct { - Sha string `json:"sha"` - Commit struct { - Author struct { - Name string `json:"name"` - Email string `json:"email"` - Date time.Time `json:"date"` - } `json:"author"` - Committer struct { - Name string `json:"name"` - Email string `json:"email"` - Date time.Time `json:"date"` - } `json:"committer"` - Message string `json:"message"` - Tree struct { - Sha string `json:"sha"` - URL string `json:"url"` - } `json:"tree"` - URL string `json:"url"` - CommentCount int64 `json:"comment_count"` - } `json:"commit"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - CommentsURL string `json:"comments_url"` - Author struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"author"` - Committer struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"committer"` - Parents []Parent `json:"parents"` - } `json:"commit"` - Branches []struct { - Name string `json:"name"` - Commit struct { - Sha string `json:"sha"` - URL string `json:"url"` - } `json:"commit"` - } `json:"branches"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// TeamPayload contains the information for GitHub's team hook event -type TeamPayload struct { - Action string `json:"action"` - Team struct { - Name string `json:"name"` - ID int64 `json:"id"` - Slug string `json:"slug"` - Description string `json:"description"` - Privacy string `json:"privacy"` - URL string `json:"url"` - MembersURL string `json:"members_url"` - RepositoriesURL string `json:"repositories_url"` - Permission string `json:"permission"` - } `json:"team"` - Organization struct { - Login string `json:"login"` - ID int64 `json:"id"` - URL string `json:"url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - HooksURL string `json:"hooks_url"` - IssuesURL string `json:"issues_url"` - MembersURL string `json:"members_url"` - PublicMembersURL string `json:"public_members_url"` - AvatarURL string `json:"avatar_url"` - Description string `json:"description"` - } `json:"organization"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// TeamAddPayload contains the information for GitHub's team_add hook event -type TeamAddPayload struct { - Team struct { - Name string `json:"name"` - ID int64 `json:"id"` - Slug string `json:"slug"` - Description string `json:"description"` - Permission string `json:"permission"` - URL string `json:"url"` - MembersURL string `json:"members_url"` - RepositoriesURL string `json:"repositories_url"` - } `json:"team"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Organization struct { - Login string `json:"login"` - ID int64 `json:"id"` - URL string `json:"url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - MembersURL string `json:"members_url"` - PublicMembersURL string `json:"public_members_url"` - AvatarURL string `json:"avatar_url"` - Description *string `json:"description"` - } `json:"organization"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// WatchPayload contains the information for GitHub's watch hook event -type WatchPayload struct { - Action string `json:"action"` - Repository struct { - ID int64 `json:"id"` - Name string `json:"name"` - FullName string `json:"full_name"` - Owner struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"owner"` - Private bool `json:"private"` - HTMLURL string `json:"html_url"` - Description string `json:"description"` - Fork bool `json:"fork"` - URL string `json:"url"` - ForksURL string `json:"forks_url"` - KeysURL string `json:"keys_url"` - CollaboratorsURL string `json:"collaborators_url"` - TeamsURL string `json:"teams_url"` - HooksURL string `json:"hooks_url"` - IssueEventsURL string `json:"issue_events_url"` - EventsURL string `json:"events_url"` - AssigneesURL string `json:"assignees_url"` - BranchesURL string `json:"branches_url"` - TagsURL string `json:"tags_url"` - BlobsURL string `json:"blobs_url"` - GitTagsURL string `json:"git_tags_url"` - GitRefsURL string `json:"git_refs_url"` - TreesURL string `json:"trees_url"` - StatusesURL string `json:"statuses_url"` - LanguagesURL string `json:"languages_url"` - StargazersURL string `json:"stargazers_url"` - ContributorsURL string `json:"contributors_url"` - SubscribersURL string `json:"subscribers_url"` - SubscriptionURL string `json:"subscription_url"` - CommitsURL string `json:"commits_url"` - GitCommitsURL string `json:"git_commits_url"` - CommentsURL string `json:"comments_url"` - IssueCommentURL string `json:"issue_comment_url"` - ContentsURL string `json:"contents_url"` - CompareURL string `json:"compare_url"` - MergesURL string `json:"merges_url"` - ArchiveURL string `json:"archive_url"` - DownloadsURL string `json:"downloads_url"` - IssuesURL string `json:"issues_url"` - PullsURL string `json:"pulls_url"` - MilestonesURL string `json:"milestones_url"` - NotificationsURL string `json:"notifications_url"` - LabelsURL string `json:"labels_url"` - ReleasesURL string `json:"releases_url"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - PushedAt time.Time `json:"pushed_at"` - GitURL string `json:"git_url"` - SSHURL string `json:"ssh_url"` - CloneURL string `json:"clone_url"` - SvnURL string `json:"svn_url"` - Homepage *string `json:"homepage"` - Size int64 `json:"size"` - StargazersCount int64 `json:"stargazers_count"` - WatchersCount int64 `json:"watchers_count"` - Language *string `json:"language"` - HasIssues bool `json:"has_issues"` - HasDownloads bool `json:"has_downloads"` - HasWiki bool `json:"has_wiki"` - HasPages bool `json:"has_pages"` - ForksCount int64 `json:"forks_count"` - MirrorURL *string `json:"mirror_url"` - OpenIssuesCount int64 `json:"open_issues_count"` - Forks int64 `json:"forks"` - OpenIssues int64 `json:"open_issues"` - Watchers int64 `json:"watchers"` - DefaultBranch string `json:"default_branch"` - } `json:"repository"` - Sender struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"sender"` -} - -// Assignee contains GitHub's assignee information -type Assignee struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` -} - -// Milestone contains GitHub's milestone information -type Milestone struct { - URL string `json:"url"` - HTMLURL string `json:"html_url"` - LabelsURL string `json:"labels_url"` - ID int64 `json:"id"` - Number int64 `json:"number"` - State string `json:"state"` - Title string `json:"title"` - Description string `json:"description"` - Creator struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"creator"` - OpenIssues int64 `json:"open_issues"` - ClosedIssues int64 `json:"closed_issues"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - ClosedAt time.Time `json:"closed_at"` - DueOn time.Time `json:"due_on"` -} - -// MergedBy contains GitHub's merged-by information -type MergedBy struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` -} - -// Asset contains GitHub's asset information -type Asset struct { - URL string `json:"url"` - BrowserDownloadURL string `json:"browser_download_url"` - ID int64 `json:"id"` - Name string `json:"name"` - Label string `json:"label"` - State string `json:"state"` - ContentType string `json:"content_type"` - Size int64 `json:"size"` - DownloadCount int64 `json:"download_count"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - Uploader struct { - Login string `json:"login"` - ID int64 `json:"id"` - AvatarURL string `json:"avatar_url"` - GravatarID string `json:"gravatar_id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - FollowersURL string `json:"followers_url"` - FollowingURL string `json:"following_url"` - GistsURL string `json:"gists_url"` - StarredURL string `json:"starred_url"` - SubscriptionsURL string `json:"subscriptions_url"` - OrganizationsURL string `json:"organizations_url"` - ReposURL string `json:"repos_url"` - EventsURL string `json:"events_url"` - ReceivedEventsURL string `json:"received_events_url"` - Type string `json:"type"` - SiteAdmin bool `json:"site_admin"` - } `json:"uploader"` -} - -// Parent contains GitHub's parent information -type Parent struct { - URL string `json:"url"` - Sha string `json:"sha"` -} diff --git a/vendor/gopkg.in/go-playground/webhooks.v3/logger.go b/vendor/gopkg.in/go-playground/webhooks.v3/logger.go deleted file mode 100644 index 0d3d588e0b6..00000000000 --- a/vendor/gopkg.in/go-playground/webhooks.v3/logger.go +++ /dev/null @@ -1,44 +0,0 @@ -package webhooks - -import "log" - -// DefaultLog contains the default logger for webhooks, and prints only info and error messages by default -// for debugs override DefaultLog or see NewLogger for creating one without debugs. -var DefaultLog Logger = new(logger) - -// Logger allows for customizable logging -type Logger interface { - // Info prints basic information. - Info(string) - // Error prints error information. - Error(string) - // Debug prints information usefull for debugging. - Debug(string) -} - -// NewLogger returns a new logger for use. -func NewLogger(debug bool) Logger { - return &logger{PrintDebugs: debug} -} - -type logger struct { - PrintDebugs bool -} - -// Info prints basic information. -func (l *logger) Info(msg string) { - log.Println("INFO:", msg) -} - -// v prints error information. -func (l *logger) Error(msg string) { - log.Println("ERROR:", msg) -} - -// Debug prints information usefull for debugging. -func (l *logger) Debug(msg string) { - if !l.PrintDebugs { - return - } - log.Println("DEBUG:", msg) -} diff --git a/vendor/gopkg.in/go-playground/webhooks.v3/webhooks.go b/vendor/gopkg.in/go-playground/webhooks.v3/webhooks.go deleted file mode 100644 index 4ab78b1bfef..00000000000 --- a/vendor/gopkg.in/go-playground/webhooks.v3/webhooks.go +++ /dev/null @@ -1,124 +0,0 @@ -package webhooks - -import ( - "fmt" - "net/http" -) - -// Header provides http.Header to minimize imports -type Header http.Header - -// Provider defines the type of webhook -type Provider int - -func (p Provider) String() string { - switch p { - case GitHub: - return "GitHub" - case Bitbucket: - return "Bitbucket" - case GitLab: - return "GitLab" - case Gogs: - return "Gogs" - default: - return "Unknown" - } -} - -// webhooks available providers -const ( - GitHub Provider = iota - Bitbucket - GitLab - Gogs -) - -// Webhook interface defines a webhook to receive events -type Webhook interface { - Provider() Provider - ParsePayload(w http.ResponseWriter, r *http.Request) -} - -type server struct { - hook Webhook - path string - includePathCheck bool -} - -// ProcessPayloadFunc is a common function for payload return values -type ProcessPayloadFunc func(payload interface{}, header Header) - -// Handler returns the webhook http.Handler for use in your own Mux implementation -func Handler(hook Webhook) http.Handler { - return &server{ - hook: hook, - } -} - -// Run runs a server -func Run(hook Webhook, addr string, path string) error { - srv := &server{ - hook: hook, - path: path, - includePathCheck: true, - } - s := &http.Server{Addr: addr, Handler: srv} - - DefaultLog.Info(fmt.Sprintf("Listening on addr: %s path: %s", addr, path)) - return s.ListenAndServe() -} - -// RunServer runs a custom server. -func RunServer(s *http.Server, hook Webhook, path string) error { - - srv := &server{ - hook: hook, - path: path, - includePathCheck: true, - } - - s.Handler = srv - DefaultLog.Info(fmt.Sprintf("Listening on addr: %s path: %s", s.Addr, path)) - return s.ListenAndServe() -} - -// RunTLSServer runs a custom server with TLS configuration. -// NOTE: http.Server Handler will be overridden by this library, just set it to nil. -// Setting the Certificates can be done in the http.Server.TLSConfig.Certificates -// see example here: https://github.com/go-playground/webhooks/blob/v2/webhooks_test.go#L178 -func RunTLSServer(s *http.Server, hook Webhook, path string) error { - - srv := &server{ - hook: hook, - path: path, - includePathCheck: true, - } - - s.Handler = srv - DefaultLog.Info(fmt.Sprintf("Listening on addr: %s path: %s", s.Addr, path)) - return s.ListenAndServeTLS("", "") -} - -// ServeHTTP is the Handler for every posted WebHook Event -func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) { - defer r.Body.Close() - DefaultLog.Info("Webhook received") - - if r.Method != "POST" { - DefaultLog.Error(fmt.Sprintf("405 Method not allowed, attempt made using Method: %s", r.Method)) - http.Error(w, "405 Method not allowed", http.StatusMethodNotAllowed) - return - } - - DefaultLog.Debug(fmt.Sprintf("Include path check: %t", s.includePathCheck)) - if s.includePathCheck { - if r.URL.Path != s.path { - DefaultLog.Error(fmt.Sprintf("404 Not found, POST made using path: %s, but expected %s", r.URL.Path, s.path)) - http.Error(w, "404 Not found", http.StatusNotFound) - return - } - } - - s.hook.ParsePayload(w, r) -} diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/runtime/scheme/scheme.go b/vendor/sigs.k8s.io/controller-runtime/pkg/runtime/scheme/scheme.go new file mode 100644 index 00000000000..79868214e34 --- /dev/null +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/runtime/scheme/scheme.go @@ -0,0 +1,56 @@ +/* +Copyright 2018 The Kubernetes 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 scheme + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +// Builder builds a new Scheme for mapping go types to Kubernetes GroupVersionKinds. +type Builder struct { + GroupVersion schema.GroupVersion + runtime.SchemeBuilder +} + +// Register adds one or objects to the SchemeBuilder so they can be added to a Scheme. Register mutates bld. +func (bld *Builder) Register(object ...runtime.Object) *Builder { + bld.SchemeBuilder.Register(func(scheme *runtime.Scheme) error { + scheme.AddKnownTypes(bld.GroupVersion, object...) + metav1.AddToGroupVersion(scheme, bld.GroupVersion) + return nil + }) + return bld +} + +// RegisterAll registers all types from the Builder argument. RegisterAll mutates bld. +func (bld *Builder) RegisterAll(b *Builder) *Builder { + bld.SchemeBuilder = append(bld.SchemeBuilder, b.SchemeBuilder...) + return bld +} + +// AddToScheme adds all registered types to s. +func (bld *Builder) AddToScheme(s *runtime.Scheme) error { + return bld.SchemeBuilder.AddToScheme(s) +} + +// Build returns a new Scheme containing the registered types. +func (bld *Builder) Build() (*runtime.Scheme, error) { + s := runtime.NewScheme() + return s, bld.AddToScheme(s) +}